ai-database 0.0.0-development → 0.2.0

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 (79) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/.turbo/turbo-test.log +102 -0
  3. package/README.md +402 -47
  4. package/TESTING.md +410 -0
  5. package/TEST_SUMMARY.md +250 -0
  6. package/TODO.md +128 -0
  7. package/dist/ai-promise-db.d.ts +370 -0
  8. package/dist/ai-promise-db.d.ts.map +1 -0
  9. package/dist/ai-promise-db.js +839 -0
  10. package/dist/ai-promise-db.js.map +1 -0
  11. package/dist/authorization.d.ts +531 -0
  12. package/dist/authorization.d.ts.map +1 -0
  13. package/dist/authorization.js +632 -0
  14. package/dist/authorization.js.map +1 -0
  15. package/dist/durable-clickhouse.d.ts +193 -0
  16. package/dist/durable-clickhouse.d.ts.map +1 -0
  17. package/dist/durable-clickhouse.js +422 -0
  18. package/dist/durable-clickhouse.js.map +1 -0
  19. package/dist/durable-promise.d.ts +182 -0
  20. package/dist/durable-promise.d.ts.map +1 -0
  21. package/dist/durable-promise.js +409 -0
  22. package/dist/durable-promise.js.map +1 -0
  23. package/dist/execution-queue.d.ts +239 -0
  24. package/dist/execution-queue.d.ts.map +1 -0
  25. package/dist/execution-queue.js +400 -0
  26. package/dist/execution-queue.js.map +1 -0
  27. package/dist/index.d.ts +54 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +79 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/linguistic.d.ts +115 -0
  32. package/dist/linguistic.d.ts.map +1 -0
  33. package/dist/linguistic.js +379 -0
  34. package/dist/linguistic.js.map +1 -0
  35. package/dist/memory-provider.d.ts +304 -0
  36. package/dist/memory-provider.d.ts.map +1 -0
  37. package/dist/memory-provider.js +785 -0
  38. package/dist/memory-provider.js.map +1 -0
  39. package/dist/schema.d.ts +899 -0
  40. package/dist/schema.d.ts.map +1 -0
  41. package/dist/schema.js +1165 -0
  42. package/dist/schema.js.map +1 -0
  43. package/dist/tests.d.ts +107 -0
  44. package/dist/tests.d.ts.map +1 -0
  45. package/dist/tests.js +568 -0
  46. package/dist/tests.js.map +1 -0
  47. package/dist/types.d.ts +972 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +126 -0
  50. package/dist/types.js.map +1 -0
  51. package/package.json +37 -23
  52. package/src/ai-promise-db.ts +1243 -0
  53. package/src/authorization.ts +1102 -0
  54. package/src/durable-clickhouse.ts +596 -0
  55. package/src/durable-promise.ts +582 -0
  56. package/src/execution-queue.ts +608 -0
  57. package/src/index.test.ts +868 -0
  58. package/src/index.ts +337 -0
  59. package/src/linguistic.ts +404 -0
  60. package/src/memory-provider.test.ts +1036 -0
  61. package/src/memory-provider.ts +1119 -0
  62. package/src/schema.test.ts +1254 -0
  63. package/src/schema.ts +2296 -0
  64. package/src/tests.ts +725 -0
  65. package/src/types.ts +1177 -0
  66. package/test/README.md +153 -0
  67. package/test/edge-cases.test.ts +646 -0
  68. package/test/provider-resolution.test.ts +402 -0
  69. package/tsconfig.json +9 -0
  70. package/vitest.config.ts +19 -0
  71. package/LICENSE +0 -21
  72. package/dist/types/database.d.ts +0 -46
  73. package/dist/types/document.d.ts +0 -15
  74. package/dist/types/index.d.ts +0 -5
  75. package/dist/types/mdxdb/embedding.d.ts +0 -7
  76. package/dist/types/mdxdb/types.d.ts +0 -59
  77. package/dist/types/synthetic.d.ts +0 -9
  78. package/dist/types/tools.d.ts +0 -10
  79. package/dist/types/vector.d.ts +0 -16
@@ -0,0 +1,972 @@
1
+ /**
2
+ * Core Type Definitions
3
+ *
4
+ * Contains all foundational types for ai-database:
5
+ * - Thing types (mdxld-based entity structure)
6
+ * - Schema definition types
7
+ * - Parsed schema types
8
+ * - Noun & Verb semantic types
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import type { MDXLD } from 'mdxld';
13
+ /**
14
+ * Flat Thing shape with $-prefixed metadata fields
15
+ * Used for JSON-LD compatible serialization
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const post: ThingFlat = {
20
+ * $id: 'post-123',
21
+ * $type: 'Post',
22
+ * $context: 'https://schema.org',
23
+ * title: 'Hello World',
24
+ * content: '...',
25
+ * }
26
+ * ```
27
+ */
28
+ export interface ThingFlat {
29
+ /** Unique identifier */
30
+ $id: string;
31
+ /** Entity type */
32
+ $type: string;
33
+ /** JSON-LD context (optional) */
34
+ $context?: string | Record<string, unknown>;
35
+ /** Additional data fields */
36
+ [key: string]: unknown;
37
+ }
38
+ /**
39
+ * Expanded Thing shape with structured data and content
40
+ * Used for full document representation (mdxld format)
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const post: ThingExpanded = {
45
+ * id: 'post-123',
46
+ * type: 'Post',
47
+ * context: 'https://schema.org',
48
+ * data: { title: 'Hello World', author: 'john' },
49
+ * content: '# Hello World\n\nThis is my post...',
50
+ * }
51
+ * ```
52
+ */
53
+ export interface ThingExpanded extends MDXLD {
54
+ /** Unique identifier */
55
+ id: string;
56
+ /** Entity type */
57
+ type: string;
58
+ }
59
+ /**
60
+ * Convert flat thing to expanded format
61
+ */
62
+ export declare function toExpanded(flat: ThingFlat): ThingExpanded;
63
+ /**
64
+ * Convert expanded thing to flat format
65
+ */
66
+ export declare function toFlat(expanded: ThingExpanded): ThingFlat;
67
+ /**
68
+ * Primitive field types
69
+ */
70
+ export type PrimitiveType = 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'json' | 'markdown' | 'url';
71
+ /**
72
+ * A field definition can be:
73
+ * - A primitive type: 'string', 'number', etc.
74
+ * - A relation: 'Author.posts' (Type.backref)
75
+ * - An array of primitives: 'string[]'
76
+ * - An array relation: ['Author.posts'] (many-to-many with backref)
77
+ * - Optional modifier: 'string?'
78
+ */
79
+ export type FieldDefinition = string | [string];
80
+ /**
81
+ * Schema for a single entity type
82
+ */
83
+ export type EntitySchema = Record<string, FieldDefinition>;
84
+ /**
85
+ * Full database schema
86
+ */
87
+ export type DatabaseSchema = Record<string, EntitySchema>;
88
+ /**
89
+ * Parsed field information
90
+ */
91
+ export interface ParsedField {
92
+ name: string;
93
+ type: string;
94
+ isArray: boolean;
95
+ isOptional: boolean;
96
+ isRelation: boolean;
97
+ relatedType?: string;
98
+ backref?: string;
99
+ }
100
+ /**
101
+ * Parsed entity with all fields including auto-generated backrefs
102
+ */
103
+ export interface ParsedEntity {
104
+ name: string;
105
+ fields: Map<string, ParsedField>;
106
+ }
107
+ /**
108
+ * Fully parsed schema with bi-directional relationships resolved
109
+ */
110
+ export interface ParsedSchema {
111
+ entities: Map<string, ParsedEntity>;
112
+ }
113
+ /**
114
+ * Verb conjugations and related forms
115
+ *
116
+ * Maps an action to its various grammatical forms and semantic relationships.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const create: Verb = {
121
+ * action: 'create', // Base form (imperative)
122
+ * actor: 'creator', // Who does it (noun)
123
+ * act: 'creates', // Present tense (3rd person)
124
+ * activity: 'creating', // Gerund/continuous
125
+ * result: 'creation', // Result noun
126
+ * reverse: { // Passive/result properties
127
+ * at: 'createdAt',
128
+ * by: 'createdBy',
129
+ * in: 'createdIn',
130
+ * for: 'createdFor',
131
+ * },
132
+ * inverse: 'delete', // Opposite action
133
+ * }
134
+ * ```
135
+ */
136
+ export interface Verb {
137
+ /** Base form / imperative (create, update, delete, publish) */
138
+ action: string;
139
+ /** Agent noun - who performs the action (creator, updater, author, publisher) */
140
+ actor?: string;
141
+ /** Present tense 3rd person singular (creates, updates, deletes, publishes) */
142
+ act?: string;
143
+ /** Present participle / gerund (creating, updating, deleting, publishing) */
144
+ activity?: string;
145
+ /** Result noun - what is produced (creation, update, deletion, publication) */
146
+ result?: string;
147
+ /** Reverse/passive forms - properties resulting from the action */
148
+ reverse?: {
149
+ /** Timestamp field (createdAt, updatedAt, deletedAt, publishedAt) */
150
+ at?: string;
151
+ /** Actor reference (createdBy, updatedBy, deletedBy, publishedBy) */
152
+ by?: string;
153
+ /** Location/context (createdIn, updatedIn, publishedIn) */
154
+ in?: string;
155
+ /** Purpose/target (createdFor, publishedFor) */
156
+ for?: string;
157
+ /** Additional reverse forms */
158
+ [key: string]: string | undefined;
159
+ };
160
+ /** Inverse action (create ↔ delete, publish ↔ unpublish, activate ↔ deactivate) */
161
+ inverse?: string;
162
+ /** Description of what this action does */
163
+ description?: string;
164
+ }
165
+ /**
166
+ * Standard CRUD verbs with pre-defined conjugations
167
+ */
168
+ export declare const Verbs: {
169
+ readonly create: {
170
+ readonly action: "create";
171
+ readonly actor: "creator";
172
+ readonly act: "creates";
173
+ readonly activity: "creating";
174
+ readonly result: "creation";
175
+ readonly reverse: {
176
+ readonly at: "createdAt";
177
+ readonly by: "createdBy";
178
+ readonly in: "createdIn";
179
+ readonly for: "createdFor";
180
+ };
181
+ readonly inverse: "delete";
182
+ };
183
+ readonly update: {
184
+ readonly action: "update";
185
+ readonly actor: "updater";
186
+ readonly act: "updates";
187
+ readonly activity: "updating";
188
+ readonly result: "update";
189
+ readonly reverse: {
190
+ readonly at: "updatedAt";
191
+ readonly by: "updatedBy";
192
+ };
193
+ };
194
+ readonly delete: {
195
+ readonly action: "delete";
196
+ readonly actor: "deleter";
197
+ readonly act: "deletes";
198
+ readonly activity: "deleting";
199
+ readonly result: "deletion";
200
+ readonly reverse: {
201
+ readonly at: "deletedAt";
202
+ readonly by: "deletedBy";
203
+ };
204
+ readonly inverse: "create";
205
+ };
206
+ readonly publish: {
207
+ readonly action: "publish";
208
+ readonly actor: "publisher";
209
+ readonly act: "publishes";
210
+ readonly activity: "publishing";
211
+ readonly result: "publication";
212
+ readonly reverse: {
213
+ readonly at: "publishedAt";
214
+ readonly by: "publishedBy";
215
+ };
216
+ readonly inverse: "unpublish";
217
+ };
218
+ readonly archive: {
219
+ readonly action: "archive";
220
+ readonly actor: "archiver";
221
+ readonly act: "archives";
222
+ readonly activity: "archiving";
223
+ readonly result: "archive";
224
+ readonly reverse: {
225
+ readonly at: "archivedAt";
226
+ readonly by: "archivedBy";
227
+ };
228
+ readonly inverse: "unarchive";
229
+ };
230
+ };
231
+ /**
232
+ * Noun definition - semantic description of an entity type
233
+ *
234
+ * Describes a Thing with its properties, relationships, available actions,
235
+ * and metadata like singular/plural forms for natural language generation.
236
+ *
237
+ * @example
238
+ * ```ts
239
+ * const Post: Noun = {
240
+ * singular: 'post',
241
+ * plural: 'posts',
242
+ * description: 'A blog post or article',
243
+ *
244
+ * properties: {
245
+ * title: { type: 'string', description: 'The post title' },
246
+ * content: { type: 'markdown', description: 'The post body' },
247
+ * status: { type: 'string', description: 'draft | published | archived' },
248
+ * },
249
+ *
250
+ * relationships: {
251
+ * author: { type: 'Author', backref: 'posts', description: 'Who wrote this' },
252
+ * tags: { type: 'Tag[]', backref: 'posts', description: 'Categorization' },
253
+ * },
254
+ *
255
+ * actions: ['create', 'update', 'delete', 'publish', 'archive'],
256
+ *
257
+ * events: ['created', 'updated', 'deleted', 'published', 'archived'],
258
+ * }
259
+ * ```
260
+ */
261
+ export interface Noun {
262
+ /** Singular form (post, user, category) */
263
+ singular: string;
264
+ /** Plural form (posts, users, categories) */
265
+ plural: string;
266
+ /** Human-readable description */
267
+ description?: string;
268
+ /** Property definitions with descriptions */
269
+ properties?: Record<string, NounProperty>;
270
+ /** Relationship definitions with descriptions */
271
+ relationships?: Record<string, NounRelationship>;
272
+ /** Actions that can be performed on this noun (verbs) */
273
+ actions?: Array<string | Verb>;
274
+ /** Events that can occur to this noun */
275
+ events?: string[];
276
+ /** Additional metadata */
277
+ metadata?: Record<string, unknown>;
278
+ }
279
+ /**
280
+ * Property definition within a Noun
281
+ */
282
+ export interface NounProperty {
283
+ /** Field type */
284
+ type: PrimitiveType | string;
285
+ /** Human-readable description (also used as generation prompt) */
286
+ description?: string;
287
+ /** Whether the field is optional */
288
+ optional?: boolean;
289
+ /** Whether the field is an array */
290
+ array?: boolean;
291
+ /** Default value */
292
+ default?: unknown;
293
+ /** Example values for documentation/generation */
294
+ examples?: unknown[];
295
+ }
296
+ /**
297
+ * Relationship definition within a Noun
298
+ */
299
+ export interface NounRelationship {
300
+ /** Related entity type (e.g., 'Author', 'Tag[]') */
301
+ type: string;
302
+ /** Backref field name on the related entity */
303
+ backref?: string;
304
+ /** Human-readable description */
305
+ description?: string;
306
+ /** Whether this is a required relationship */
307
+ required?: boolean;
308
+ }
309
+ /**
310
+ * Type metadata - automatically inferred from type name
311
+ *
312
+ * Available on every entity via `entity.$type` or `db.Post.$meta`
313
+ */
314
+ export interface TypeMeta {
315
+ /** Type name as defined in schema (e.g., 'Post', 'BlogPost') */
316
+ name: string;
317
+ /** Singular form (e.g., 'post', 'blog post') */
318
+ singular: string;
319
+ /** Plural form (e.g., 'posts', 'blog posts') */
320
+ plural: string;
321
+ /** URL-safe slug (e.g., 'post', 'blog-post') */
322
+ slug: string;
323
+ /** Plural slug (e.g., 'posts', 'blog-posts') */
324
+ slugPlural: string;
325
+ /** Creator relationship name */
326
+ creator: string;
327
+ /** Created timestamp field */
328
+ createdAt: string;
329
+ /** Created by field */
330
+ createdBy: string;
331
+ /** Updated timestamp field */
332
+ updatedAt: string;
333
+ /** Updated by field */
334
+ updatedBy: string;
335
+ /** Event type for creation (e.g., 'Post.created') */
336
+ created: string;
337
+ /** Event type for update (e.g., 'Post.updated') */
338
+ updated: string;
339
+ /** Event type for deletion (e.g., 'Post.deleted') */
340
+ deleted: string;
341
+ }
342
+ /**
343
+ * Base identifier for all entities (URL-centric)
344
+ */
345
+ export interface EntityId {
346
+ /** Namespace (e.g., 'example.com', 'api.mdx.org.ai') */
347
+ ns: string;
348
+ /** Type of the entity (e.g., 'user', 'post', 'comment') */
349
+ type: string;
350
+ /** Unique identifier within the namespace and type */
351
+ id: string;
352
+ /**
353
+ * Full URL for the entity
354
+ * Defaults to https://{ns}/{type}/{id}
355
+ */
356
+ url?: string;
357
+ }
358
+ /**
359
+ * A Thing is a node in the database (linked data style)
360
+ */
361
+ export interface Thing<T extends Record<string, unknown> = Record<string, unknown>> extends EntityId {
362
+ /** When the thing was created */
363
+ createdAt: Date;
364
+ /** When the thing was last updated */
365
+ updatedAt: Date;
366
+ /** Arbitrary properties */
367
+ data: T;
368
+ /** JSON-LD context (optional) */
369
+ '@context'?: string | Record<string, unknown>;
370
+ }
371
+ /**
372
+ * Relationship between two things (graph edge)
373
+ */
374
+ export interface Relationship<T extends Record<string, unknown> = Record<string, unknown>> {
375
+ /** Unique identifier for the relationship */
376
+ id: string;
377
+ /** Type of relationship (any string) */
378
+ type: string;
379
+ /** Source thing URL */
380
+ from: string;
381
+ /** Target thing URL */
382
+ to: string;
383
+ /** When the relationship was created */
384
+ createdAt: Date;
385
+ /** Optional relationship metadata */
386
+ data?: T;
387
+ }
388
+ /**
389
+ * Resolve the URL for an entity
390
+ */
391
+ export declare function resolveUrl(entity: EntityId): string;
392
+ /**
393
+ * Resolve URL with just ns/id (no type in path)
394
+ */
395
+ export declare function resolveShortUrl(entity: Pick<EntityId, 'ns' | 'id'>): string;
396
+ /**
397
+ * Parse a URL into EntityId components
398
+ */
399
+ export declare function parseUrl(url: string): EntityId;
400
+ /**
401
+ * Query options for finding things
402
+ */
403
+ export interface QueryOptions {
404
+ /** Filter by namespace */
405
+ ns?: string;
406
+ /** Filter by type */
407
+ type?: string;
408
+ /** Filter by properties (exact match) */
409
+ where?: Record<string, unknown>;
410
+ /** Order by field */
411
+ orderBy?: string;
412
+ /** Order direction */
413
+ order?: 'asc' | 'desc';
414
+ /** Limit results */
415
+ limit?: number;
416
+ /** Skip results (for pagination) */
417
+ offset?: number;
418
+ }
419
+ /**
420
+ * Search options for semantic/text search
421
+ */
422
+ export interface ThingSearchOptions extends QueryOptions {
423
+ /** The search query */
424
+ query: string;
425
+ /** Fields to search in */
426
+ fields?: string[];
427
+ /** Minimum relevance score (0-1) */
428
+ minScore?: number;
429
+ }
430
+ /**
431
+ * Options for creating a thing
432
+ */
433
+ export interface CreateOptions<T extends Record<string, unknown>> {
434
+ /** Namespace */
435
+ ns: string;
436
+ /** Type of the thing */
437
+ type: string;
438
+ /** ID (auto-generated if not provided) */
439
+ id?: string;
440
+ /** Custom URL (auto-generated if not provided) */
441
+ url?: string;
442
+ /** Initial data */
443
+ data: T;
444
+ /** JSON-LD context */
445
+ '@context'?: string | Record<string, unknown>;
446
+ }
447
+ /**
448
+ * Options for updating a thing
449
+ */
450
+ export interface UpdateOptions<T extends Record<string, unknown>> {
451
+ /** Partial data to merge */
452
+ data: Partial<T>;
453
+ }
454
+ /**
455
+ * Options for creating a relationship
456
+ */
457
+ export interface RelateOptions<T extends Record<string, unknown> = Record<string, unknown>> {
458
+ /** Type of relationship */
459
+ type: string;
460
+ /** Source thing URL */
461
+ from: string;
462
+ /** Target thing URL */
463
+ to: string;
464
+ /** Optional relationship data */
465
+ data?: T;
466
+ }
467
+ /**
468
+ * Immutable event record
469
+ */
470
+ export interface Event<T extends Record<string, unknown> = Record<string, unknown>> {
471
+ /** Unique identifier for the event */
472
+ id: string;
473
+ /** Event type (e.g., 'Customer.created', 'Order.completed') */
474
+ type: string;
475
+ /** When the event occurred */
476
+ timestamp: Date;
477
+ /** Event source (workflow, user, system) */
478
+ source: string;
479
+ /** Event data payload */
480
+ data: T;
481
+ /** Optional correlation ID for tracing related events */
482
+ correlationId?: string;
483
+ /** Optional causation ID (the event that caused this event) */
484
+ causationId?: string;
485
+ }
486
+ /**
487
+ * Action status
488
+ */
489
+ export type ActionStatus = 'pending' | 'active' | 'completed' | 'failed' | 'cancelled';
490
+ /**
491
+ * Action record for pending/active work
492
+ */
493
+ export interface Action<T extends Record<string, unknown> = Record<string, unknown>> {
494
+ /** Unique identifier for the action */
495
+ id: string;
496
+ /** Actor performing the action (user URL, agent ID, 'system') */
497
+ actor: string;
498
+ /** Object being acted upon (thing URL) */
499
+ object: string;
500
+ /** Action type (e.g., 'approve', 'process', 'review') */
501
+ action: string;
502
+ /** Current status */
503
+ status: ActionStatus;
504
+ /** When the action was created */
505
+ createdAt: Date;
506
+ /** When the action was last updated */
507
+ updatedAt: Date;
508
+ /** When the action started (status became 'active') */
509
+ startedAt?: Date;
510
+ /** When the action completed or failed */
511
+ completedAt?: Date;
512
+ /** Result of the action (when completed) */
513
+ result?: unknown;
514
+ /** Error message (when failed) */
515
+ error?: string;
516
+ /** Additional action metadata */
517
+ metadata?: T;
518
+ }
519
+ /**
520
+ * Artifact type
521
+ */
522
+ export type ArtifactType = 'ast' | 'types' | 'esm' | 'cjs' | 'worker' | 'html' | 'markdown' | 'bundle' | 'sourcemap' | string;
523
+ /**
524
+ * Cached artifact for compiled/parsed content
525
+ */
526
+ export interface Artifact<T = unknown> {
527
+ /** Unique key for the artifact (usually source URL + artifact type) */
528
+ key: string;
529
+ /** Type of artifact */
530
+ type: ArtifactType;
531
+ /** Source URL or identifier */
532
+ source: string;
533
+ /** Hash of the source content (for cache invalidation) */
534
+ sourceHash: string;
535
+ /** When the artifact was created */
536
+ createdAt: Date;
537
+ /** When the artifact expires (optional TTL) */
538
+ expiresAt?: Date;
539
+ /** The artifact content */
540
+ content: T;
541
+ /** Content size in bytes */
542
+ size?: number;
543
+ /** Additional metadata */
544
+ metadata?: Record<string, unknown>;
545
+ }
546
+ /**
547
+ * Options for creating an event
548
+ */
549
+ export interface CreateEventOptions<T extends Record<string, unknown>> {
550
+ /** Event type */
551
+ type: string;
552
+ /** Event source */
553
+ source: string;
554
+ /** Event data */
555
+ data: T;
556
+ /** Optional correlation ID */
557
+ correlationId?: string;
558
+ /** Optional causation ID */
559
+ causationId?: string;
560
+ }
561
+ /**
562
+ * Options for creating an action
563
+ */
564
+ export interface CreateActionOptions<T extends Record<string, unknown> = Record<string, unknown>> {
565
+ /** Actor performing the action */
566
+ actor: string;
567
+ /** Object being acted upon */
568
+ object: string;
569
+ /** Action type */
570
+ action: string;
571
+ /** Initial status (defaults to 'pending') */
572
+ status?: ActionStatus;
573
+ /** Additional metadata */
574
+ metadata?: T;
575
+ }
576
+ /**
577
+ * Options for storing an artifact
578
+ */
579
+ export interface StoreArtifactOptions<T = unknown> {
580
+ /** Unique key for the artifact */
581
+ key: string;
582
+ /** Type of artifact */
583
+ type: ArtifactType;
584
+ /** Source URL or identifier */
585
+ source: string;
586
+ /** Hash of the source content */
587
+ sourceHash: string;
588
+ /** The artifact content */
589
+ content: T;
590
+ /** TTL in milliseconds (optional) */
591
+ ttl?: number;
592
+ /** Additional metadata */
593
+ metadata?: Record<string, unknown>;
594
+ }
595
+ /**
596
+ * Event query options
597
+ */
598
+ export interface EventQueryOptions {
599
+ /** Filter by event type */
600
+ type?: string;
601
+ /** Filter by source */
602
+ source?: string;
603
+ /** Filter by correlation ID */
604
+ correlationId?: string;
605
+ /** Events after this timestamp */
606
+ after?: Date;
607
+ /** Events before this timestamp */
608
+ before?: Date;
609
+ /** Maximum number of events to return */
610
+ limit?: number;
611
+ /** Offset for pagination */
612
+ offset?: number;
613
+ }
614
+ /**
615
+ * Action query options
616
+ */
617
+ export interface ActionQueryOptions {
618
+ /** Filter by actor */
619
+ actor?: string;
620
+ /** Filter by object */
621
+ object?: string;
622
+ /** Filter by action type */
623
+ action?: string;
624
+ /** Filter by status */
625
+ status?: ActionStatus | ActionStatus[];
626
+ /** Maximum number of actions to return */
627
+ limit?: number;
628
+ /** Offset for pagination */
629
+ offset?: number;
630
+ }
631
+ /**
632
+ * Database client interface for graph operations
633
+ */
634
+ export interface DBClient<TData extends Record<string, unknown> = Record<string, unknown>> {
635
+ list(options?: QueryOptions): Promise<Thing<TData>[]>;
636
+ find(options: QueryOptions): Promise<Thing<TData>[]>;
637
+ search(options: ThingSearchOptions): Promise<Thing<TData>[]>;
638
+ get(url: string): Promise<Thing<TData> | null>;
639
+ getById(ns: string, type: string, id: string): Promise<Thing<TData> | null>;
640
+ set(url: string, data: TData): Promise<Thing<TData>>;
641
+ create(options: CreateOptions<TData>): Promise<Thing<TData>>;
642
+ update(url: string, options: UpdateOptions<TData>): Promise<Thing<TData>>;
643
+ upsert(options: CreateOptions<TData>): Promise<Thing<TData>>;
644
+ delete(url: string): Promise<boolean>;
645
+ forEach(options: QueryOptions, callback: (thing: Thing<TData>) => void | Promise<void>): Promise<void>;
646
+ relate<T extends Record<string, unknown> = Record<string, unknown>>(options: RelateOptions<T>): Promise<Relationship<T>>;
647
+ unrelate(from: string, type: string, to: string): Promise<boolean>;
648
+ related(url: string, relationshipType?: string, direction?: 'from' | 'to' | 'both'): Promise<Thing<TData>[]>;
649
+ relationships(url: string, type?: string, direction?: 'from' | 'to' | 'both'): Promise<Relationship[]>;
650
+ references(url: string, relationshipType?: string): Promise<Thing<TData>[]>;
651
+ close?(): Promise<void>;
652
+ }
653
+ /**
654
+ * Extended DBClient with Events, Actions, and Artifacts
655
+ */
656
+ export interface DBClientExtended<TData extends Record<string, unknown> = Record<string, unknown>> extends DBClient<TData> {
657
+ /** Track an event (analytics-style, append-only) */
658
+ track<T extends Record<string, unknown>>(options: CreateEventOptions<T>): Promise<Event<T>>;
659
+ getEvent(id: string): Promise<Event | null>;
660
+ queryEvents(options?: EventQueryOptions): Promise<Event[]>;
661
+ /** Send an action (fire-and-forget, creates in pending state) */
662
+ send<T extends Record<string, unknown>>(options: CreateActionOptions<T>): Promise<Action<T>>;
663
+ /** Do an action (create and immediately start, returns in active state) */
664
+ do<T extends Record<string, unknown>>(options: CreateActionOptions<T>): Promise<Action<T>>;
665
+ /** Try an action (with built-in error handling) */
666
+ try<T extends Record<string, unknown>>(options: CreateActionOptions<T>, fn: () => Promise<unknown>): Promise<Action<T>>;
667
+ getAction(id: string): Promise<Action | null>;
668
+ queryActions(options?: ActionQueryOptions): Promise<Action[]>;
669
+ startAction(id: string): Promise<Action>;
670
+ completeAction(id: string, result?: unknown): Promise<Action>;
671
+ failAction(id: string, error: string): Promise<Action>;
672
+ cancelAction(id: string): Promise<Action>;
673
+ storeArtifact<T>(options: StoreArtifactOptions<T>): Promise<Artifact<T>>;
674
+ getArtifact<T = unknown>(key: string): Promise<Artifact<T> | null>;
675
+ getArtifactBySource(source: string, type: ArtifactType): Promise<Artifact | null>;
676
+ deleteArtifact(key: string): Promise<boolean>;
677
+ cleanExpiredArtifacts(): Promise<number>;
678
+ }
679
+ /**
680
+ * Query options for listing documents
681
+ */
682
+ export interface DocListOptions {
683
+ /** Maximum number of documents to return */
684
+ limit?: number;
685
+ /** Number of documents to skip */
686
+ offset?: number;
687
+ /** Field to sort by */
688
+ sortBy?: string;
689
+ /** Sort order */
690
+ sortOrder?: 'asc' | 'desc';
691
+ /** Filter by type */
692
+ type?: string | string[];
693
+ /** Filter by path prefix */
694
+ prefix?: string;
695
+ }
696
+ /**
697
+ * Document with optional score for search results
698
+ */
699
+ export interface DocWithScore<TData = Record<string, unknown>> {
700
+ /** Document ID/path */
701
+ id?: string;
702
+ /** Document type */
703
+ type?: string;
704
+ /** JSON-LD context */
705
+ context?: string | Record<string, unknown>;
706
+ /** Document data (frontmatter) */
707
+ data: TData;
708
+ /** Document content (markdown body) */
709
+ content: string;
710
+ /** Relevance score (for search results) */
711
+ score?: number;
712
+ }
713
+ /**
714
+ * Query result with pagination info
715
+ */
716
+ export interface DocListResult<TData = Record<string, unknown>> {
717
+ /** List of documents */
718
+ documents: DocWithScore<TData>[];
719
+ /** Total count of matching documents */
720
+ total: number;
721
+ /** Whether there are more results */
722
+ hasMore: boolean;
723
+ }
724
+ /**
725
+ * Search options for querying documents
726
+ */
727
+ export interface DocSearchOptions extends DocListOptions {
728
+ /** Search query string */
729
+ query: string;
730
+ /** Fields to search in */
731
+ fields?: string[];
732
+ /** Enable semantic/vector search */
733
+ semantic?: boolean;
734
+ }
735
+ /**
736
+ * Search result with relevance info
737
+ */
738
+ export interface DocSearchResult<TData = Record<string, unknown>> extends DocListResult<TData> {
739
+ /** Documents with relevance scores */
740
+ documents: Array<DocWithScore<TData> & {
741
+ score?: number;
742
+ }>;
743
+ }
744
+ /**
745
+ * Get options for retrieving a document
746
+ */
747
+ export interface DocGetOptions {
748
+ /** Include AST in response */
749
+ includeAst?: boolean;
750
+ /** Include compiled code in response */
751
+ includeCode?: boolean;
752
+ }
753
+ /**
754
+ * Set options for storing a document
755
+ */
756
+ export interface DocSetOptions {
757
+ /** Create only if document doesn't exist */
758
+ createOnly?: boolean;
759
+ /** Update only if document exists */
760
+ updateOnly?: boolean;
761
+ /** Expected version for optimistic locking */
762
+ version?: string;
763
+ }
764
+ /**
765
+ * Set result with metadata
766
+ */
767
+ export interface DocSetResult {
768
+ /** Document ID/path */
769
+ id: string;
770
+ /** New version after update */
771
+ version?: string;
772
+ /** Whether document was created (vs updated) */
773
+ created: boolean;
774
+ }
775
+ /**
776
+ * Delete options
777
+ */
778
+ export interface DocDeleteOptions {
779
+ /** Soft delete (mark as deleted) */
780
+ soft?: boolean;
781
+ /** Expected version for optimistic locking */
782
+ version?: string;
783
+ }
784
+ /**
785
+ * Delete result
786
+ */
787
+ export interface DocDeleteResult {
788
+ /** Document ID/path that was deleted */
789
+ id: string;
790
+ /** Whether document was found and deleted */
791
+ deleted: boolean;
792
+ }
793
+ /**
794
+ * Document interface for MDX document storage
795
+ *
796
+ * Generic document type for CRUD operations on MDX content.
797
+ * Used as input/output for DocumentDatabase operations.
798
+ */
799
+ export interface Document<TData = Record<string, unknown>> {
800
+ /** Document ID/path */
801
+ id?: string;
802
+ /** Document type ($type) */
803
+ type?: string;
804
+ /** JSON-LD context ($context) */
805
+ context?: string | Record<string, unknown>;
806
+ /** Document data (frontmatter fields) */
807
+ data: TData;
808
+ /** Document content (markdown body) */
809
+ content: string;
810
+ }
811
+ /**
812
+ * Database interface for MDX document storage
813
+ *
814
+ * All backend adapters (fs, sqlite, postgres, api, etc.) implement this interface.
815
+ * Works in any JavaScript runtime (Node.js, Bun, Deno, Workers, Browser).
816
+ *
817
+ * @example
818
+ * ```ts
819
+ * // Using filesystem adapter
820
+ * import { createFsDatabase } from '@mdxdb/fs'
821
+ * const db = createFsDatabase({ root: './content' })
822
+ *
823
+ * // Using API adapter
824
+ * import { createApiDatabase } from '@mdxdb/api'
825
+ * const db = createApiDatabase({ baseUrl: 'https://api.example.com' })
826
+ *
827
+ * // Same interface regardless of backend
828
+ * const doc = await db.get('posts/hello-world')
829
+ * ```
830
+ */
831
+ export interface DocumentDatabase<TData = Record<string, unknown>> {
832
+ /**
833
+ * List documents with optional filtering and pagination
834
+ */
835
+ list(options?: DocListOptions): Promise<DocListResult<TData>>;
836
+ /**
837
+ * Search documents by query
838
+ */
839
+ search(options: DocSearchOptions): Promise<DocSearchResult<TData>>;
840
+ /**
841
+ * Get a document by ID/path
842
+ */
843
+ get(id: string, options?: DocGetOptions): Promise<Document<TData> | null>;
844
+ /**
845
+ * Set/create a document
846
+ */
847
+ set(id: string, document: Document<TData>, options?: DocSetOptions): Promise<DocSetResult>;
848
+ /**
849
+ * Delete a document
850
+ */
851
+ delete(id: string, options?: DocDeleteOptions): Promise<DocDeleteResult>;
852
+ /**
853
+ * Close database connection (for cleanup)
854
+ */
855
+ close?(): Promise<void>;
856
+ }
857
+ /**
858
+ * Database configuration base
859
+ */
860
+ export interface DocumentDatabaseConfig {
861
+ /** Optional namespace/prefix for all operations */
862
+ namespace?: string;
863
+ }
864
+ /**
865
+ * Factory function type for creating database instances
866
+ */
867
+ export type CreateDocumentDatabase<TConfig extends DocumentDatabaseConfig = DocumentDatabaseConfig, TData = Record<string, unknown>> = (config: TConfig) => DocumentDatabase<TData>;
868
+ /**
869
+ * Entity item with standard fields (for views)
870
+ */
871
+ export interface ViewEntityItem {
872
+ /** Entity ID (URL or slug) */
873
+ $id: string;
874
+ /** Entity type */
875
+ $type?: string;
876
+ /** Entity data fields */
877
+ [key: string]: unknown;
878
+ }
879
+ /**
880
+ * View component definition
881
+ */
882
+ export interface ViewComponent {
883
+ /** Component name (e.g., 'Tags', 'Posts') */
884
+ name: string;
885
+ /** Entity type this component renders */
886
+ entityType?: string;
887
+ /** Relationship predicate */
888
+ relationship?: string;
889
+ /** Default columns to render */
890
+ columns?: string[];
891
+ /** Render format */
892
+ format?: 'table' | 'list' | 'cards';
893
+ }
894
+ /**
895
+ * A View document is a template that renders related entities
896
+ */
897
+ export interface ViewDocument {
898
+ /** View template ID */
899
+ id: string;
900
+ /** Entity type this view is for */
901
+ entityType: string;
902
+ /** The template content */
903
+ template: string;
904
+ /** Components discovered in the template */
905
+ components: ViewComponent[];
906
+ }
907
+ /**
908
+ * Context for rendering a view
909
+ */
910
+ export interface ViewContext {
911
+ /** The entity URL this view is being rendered for */
912
+ entityUrl: string;
913
+ /** Optional filters to apply */
914
+ filters?: Record<string, unknown>;
915
+ }
916
+ /**
917
+ * Result of rendering a view
918
+ */
919
+ export interface ViewRenderResult {
920
+ /** The rendered markdown */
921
+ markdown: string;
922
+ /** Entities that were rendered */
923
+ entities: Record<string, ViewEntityItem[]>;
924
+ }
925
+ /**
926
+ * Relationship mutation from view extraction
927
+ */
928
+ export interface ViewRelationshipMutation {
929
+ /** Mutation type */
930
+ type: 'add' | 'remove' | 'update';
931
+ /** Relationship predicate */
932
+ predicate: string;
933
+ /** Source entity URL */
934
+ from: string;
935
+ /** Target entity URL */
936
+ to: string;
937
+ /** Entity data */
938
+ data?: Record<string, unknown>;
939
+ /** Previous entity data */
940
+ previousData?: Record<string, unknown>;
941
+ }
942
+ /**
943
+ * Result of syncing changes from an edited view
944
+ */
945
+ export interface ViewSyncResult {
946
+ /** Relationship mutations to apply */
947
+ mutations: ViewRelationshipMutation[];
948
+ /** Entities that were created */
949
+ created: ViewEntityItem[];
950
+ /** Entities that were updated */
951
+ updated: ViewEntityItem[];
952
+ }
953
+ /**
954
+ * View manager interface
955
+ */
956
+ export interface ViewManager {
957
+ discoverViews(): Promise<ViewDocument[]>;
958
+ getView(viewId: string): Promise<ViewDocument | null>;
959
+ render(viewId: string, context: ViewContext): Promise<ViewRenderResult>;
960
+ sync(viewId: string, context: ViewContext, editedMarkdown: string): Promise<ViewSyncResult>;
961
+ inferRelationship(contextType: string, componentName: string): Promise<{
962
+ predicate: string;
963
+ direction: 'forward' | 'reverse';
964
+ } | null>;
965
+ }
966
+ /**
967
+ * Extended DocumentDatabase interface with view support
968
+ */
969
+ export interface DocumentDatabaseWithViews<TData = Record<string, unknown>> extends DocumentDatabase<TData> {
970
+ views: ViewManager;
971
+ }
972
+ //# sourceMappingURL=types.d.ts.map