ai-database 2.1.3 → 2.3.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 (260) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/README.md +880 -669
  3. package/dist/actions.d.ts +2 -2
  4. package/dist/actions.d.ts.map +1 -1
  5. package/dist/actions.js +1 -1
  6. package/dist/actions.js.map +1 -1
  7. package/dist/ai-promise-db.d.ts +49 -23
  8. package/dist/ai-promise-db.d.ts.map +1 -1
  9. package/dist/ai-promise-db.js +91 -63
  10. package/dist/ai-promise-db.js.map +1 -1
  11. package/dist/authorization.d.ts.map +1 -1
  12. package/dist/authorization.js +38 -30
  13. package/dist/authorization.js.map +1 -1
  14. package/dist/cascade-orchestrator.d.ts +404 -0
  15. package/dist/cascade-orchestrator.d.ts.map +1 -0
  16. package/dist/cascade-orchestrator.js +828 -0
  17. package/dist/cascade-orchestrator.js.map +1 -0
  18. package/dist/cascade-write-strategy.d.ts +584 -0
  19. package/dist/cascade-write-strategy.d.ts.map +1 -0
  20. package/dist/cascade-write-strategy.js +590 -0
  21. package/dist/cascade-write-strategy.js.map +1 -0
  22. package/dist/ch-adapter.d.ts +358 -0
  23. package/dist/ch-adapter.d.ts.map +1 -0
  24. package/dist/ch-adapter.js +929 -0
  25. package/dist/ch-adapter.js.map +1 -0
  26. package/dist/client/index.d.ts +42 -0
  27. package/dist/client/index.d.ts.map +1 -0
  28. package/dist/client/index.js +43 -0
  29. package/dist/client/index.js.map +1 -0
  30. package/dist/client.d.ts +266 -0
  31. package/dist/client.d.ts.map +1 -0
  32. package/dist/client.js +81 -0
  33. package/dist/client.js.map +1 -0
  34. package/dist/constants.d.ts +64 -1
  35. package/dist/constants.d.ts.map +1 -1
  36. package/dist/constants.js +52 -2
  37. package/dist/constants.js.map +1 -1
  38. package/dist/dataloader.d.ts +99 -0
  39. package/dist/dataloader.d.ts.map +1 -0
  40. package/dist/dataloader.js +225 -0
  41. package/dist/dataloader.js.map +1 -0
  42. package/dist/db-provider-port.d.ts +501 -0
  43. package/dist/db-provider-port.d.ts.map +1 -0
  44. package/dist/db-provider-port.js +113 -0
  45. package/dist/db-provider-port.js.map +1 -0
  46. package/dist/digital-objects-provider.d.ts +49 -0
  47. package/dist/digital-objects-provider.d.ts.map +1 -0
  48. package/dist/digital-objects-provider.js +55 -0
  49. package/dist/digital-objects-provider.js.map +1 -0
  50. package/dist/do-sqlite-adapter.d.ts +402 -0
  51. package/dist/do-sqlite-adapter.d.ts.map +1 -0
  52. package/dist/do-sqlite-adapter.js +745 -0
  53. package/dist/do-sqlite-adapter.js.map +1 -0
  54. package/dist/docs-rels/custom-types.d.ts +134 -0
  55. package/dist/docs-rels/custom-types.d.ts.map +1 -0
  56. package/dist/docs-rels/custom-types.js +70 -0
  57. package/dist/docs-rels/custom-types.js.map +1 -0
  58. package/dist/docs-rels/index.d.ts +16 -0
  59. package/dist/docs-rels/index.d.ts.map +1 -0
  60. package/dist/docs-rels/index.js +16 -0
  61. package/dist/docs-rels/index.js.map +1 -0
  62. package/dist/docs-rels/migrations/index.d.ts +30 -0
  63. package/dist/docs-rels/migrations/index.d.ts.map +1 -0
  64. package/dist/docs-rels/migrations/index.js +128 -0
  65. package/dist/docs-rels/migrations/index.js.map +1 -0
  66. package/dist/docs-rels/schema.d.ts +2961 -0
  67. package/dist/docs-rels/schema.d.ts.map +1 -0
  68. package/dist/docs-rels/schema.js +244 -0
  69. package/dist/docs-rels/schema.js.map +1 -0
  70. package/dist/durable-clickhouse.d.ts.map +1 -1
  71. package/dist/durable-clickhouse.js +16 -13
  72. package/dist/durable-clickhouse.js.map +1 -1
  73. package/dist/durable-promise.d.ts.map +1 -1
  74. package/dist/durable-promise.js +34 -15
  75. package/dist/durable-promise.js.map +1 -1
  76. package/dist/errors.d.ts +127 -0
  77. package/dist/errors.d.ts.map +1 -0
  78. package/dist/errors.js +210 -0
  79. package/dist/errors.js.map +1 -0
  80. package/dist/eventbridge.d.ts +117 -0
  81. package/dist/eventbridge.d.ts.map +1 -0
  82. package/dist/eventbridge.js +238 -0
  83. package/dist/eventbridge.js.map +1 -0
  84. package/dist/events.d.ts +2 -2
  85. package/dist/events.d.ts.map +1 -1
  86. package/dist/events.js +1 -1
  87. package/dist/events.js.map +1 -1
  88. package/dist/execution-queue.d.ts.map +1 -1
  89. package/dist/execution-queue.js +4 -5
  90. package/dist/execution-queue.js.map +1 -1
  91. package/dist/index.d.ts +35 -8
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +106 -6
  94. package/dist/index.js.map +1 -1
  95. package/dist/linguistic.d.ts +3 -108
  96. package/dist/linguistic.d.ts.map +1 -1
  97. package/dist/linguistic.js +3 -372
  98. package/dist/linguistic.js.map +1 -1
  99. package/dist/logger.d.ts +132 -0
  100. package/dist/logger.d.ts.map +1 -0
  101. package/dist/logger.js +137 -0
  102. package/dist/logger.js.map +1 -0
  103. package/dist/memory-provider.d.ts +128 -0
  104. package/dist/memory-provider.d.ts.map +1 -1
  105. package/dist/memory-provider.js +592 -257
  106. package/dist/memory-provider.js.map +1 -1
  107. package/dist/pg-adapter.d.ts +424 -0
  108. package/dist/pg-adapter.d.ts.map +1 -0
  109. package/dist/pg-adapter.js +921 -0
  110. package/dist/pg-adapter.js.map +1 -0
  111. package/dist/pipelines-iceberg-emitter.d.ts +327 -0
  112. package/dist/pipelines-iceberg-emitter.d.ts.map +1 -0
  113. package/dist/pipelines-iceberg-emitter.js +351 -0
  114. package/dist/pipelines-iceberg-emitter.js.map +1 -0
  115. package/dist/provider-capabilities.d.ts +146 -0
  116. package/dist/provider-capabilities.d.ts.map +1 -0
  117. package/dist/provider-capabilities.js +214 -0
  118. package/dist/provider-capabilities.js.map +1 -0
  119. package/dist/rdb-provider-adapter.d.ts +195 -0
  120. package/dist/rdb-provider-adapter.d.ts.map +1 -0
  121. package/dist/rdb-provider-adapter.js +291 -0
  122. package/dist/rdb-provider-adapter.js.map +1 -0
  123. package/dist/schema/cascade.d.ts +48 -17
  124. package/dist/schema/cascade.d.ts.map +1 -1
  125. package/dist/schema/cascade.js +477 -278
  126. package/dist/schema/cascade.js.map +1 -1
  127. package/dist/schema/definition-caches.d.ts +24 -0
  128. package/dist/schema/definition-caches.d.ts.map +1 -0
  129. package/dist/schema/definition-caches.js +26 -0
  130. package/dist/schema/definition-caches.js.map +1 -0
  131. package/dist/schema/dependency-graph.d.ts +21 -109
  132. package/dist/schema/dependency-graph.d.ts.map +1 -1
  133. package/dist/schema/dependency-graph.js +25 -333
  134. package/dist/schema/dependency-graph.js.map +1 -1
  135. package/dist/schema/diff.d.ts +103 -0
  136. package/dist/schema/diff.d.ts.map +1 -0
  137. package/dist/schema/diff.js +329 -0
  138. package/dist/schema/diff.js.map +1 -0
  139. package/dist/schema/entity-operations.d.ts +99 -0
  140. package/dist/schema/entity-operations.d.ts.map +1 -0
  141. package/dist/schema/entity-operations.js +818 -0
  142. package/dist/schema/entity-operations.js.map +1 -0
  143. package/dist/schema/index.d.ts +28 -34
  144. package/dist/schema/index.d.ts.map +1 -1
  145. package/dist/schema/index.js +454 -521
  146. package/dist/schema/index.js.map +1 -1
  147. package/dist/schema/migration.d.ts +205 -0
  148. package/dist/schema/migration.d.ts.map +1 -0
  149. package/dist/schema/migration.js +327 -0
  150. package/dist/schema/migration.js.map +1 -0
  151. package/dist/schema/nl-query-generator.d.ts +68 -0
  152. package/dist/schema/nl-query-generator.d.ts.map +1 -0
  153. package/dist/schema/nl-query-generator.js +362 -0
  154. package/dist/schema/nl-query-generator.js.map +1 -0
  155. package/dist/schema/nl-query.d.ts +65 -0
  156. package/dist/schema/nl-query.d.ts.map +1 -0
  157. package/dist/schema/nl-query.js +178 -0
  158. package/dist/schema/nl-query.js.map +1 -0
  159. package/dist/schema/parse.d.ts.map +1 -1
  160. package/dist/schema/parse.js +144 -89
  161. package/dist/schema/parse.js.map +1 -1
  162. package/dist/schema/provider.d.ts +37 -0
  163. package/dist/schema/provider.d.ts.map +1 -1
  164. package/dist/schema/provider.js +15 -7
  165. package/dist/schema/provider.js.map +1 -1
  166. package/dist/schema/resolve.d.ts +46 -5
  167. package/dist/schema/resolve.d.ts.map +1 -1
  168. package/dist/schema/resolve.js +237 -95
  169. package/dist/schema/resolve.js.map +1 -1
  170. package/dist/schema/search-utils.d.ts +76 -0
  171. package/dist/schema/search-utils.d.ts.map +1 -0
  172. package/dist/schema/search-utils.js +86 -0
  173. package/dist/schema/search-utils.js.map +1 -0
  174. package/dist/schema/seed.d.ts +53 -0
  175. package/dist/schema/seed.d.ts.map +1 -0
  176. package/dist/schema/seed.js +94 -0
  177. package/dist/schema/seed.js.map +1 -0
  178. package/dist/schema/semantic.d.ts +10 -0
  179. package/dist/schema/semantic.d.ts.map +1 -1
  180. package/dist/schema/semantic.js +192 -86
  181. package/dist/schema/semantic.js.map +1 -1
  182. package/dist/schema/sub-apis.d.ts +52 -0
  183. package/dist/schema/sub-apis.d.ts.map +1 -0
  184. package/dist/schema/sub-apis.js +216 -0
  185. package/dist/schema/sub-apis.js.map +1 -0
  186. package/dist/schema/system-entities.d.ts +42 -0
  187. package/dist/schema/system-entities.d.ts.map +1 -0
  188. package/dist/schema/system-entities.js +101 -0
  189. package/dist/schema/system-entities.js.map +1 -0
  190. package/dist/schema/types.d.ts +91 -9
  191. package/dist/schema/types.d.ts.map +1 -1
  192. package/dist/schema/union-fallback.d.ts.map +1 -1
  193. package/dist/schema/union-fallback.js +21 -15
  194. package/dist/schema/union-fallback.js.map +1 -1
  195. package/dist/schema/value-generators/ai.d.ts +54 -0
  196. package/dist/schema/value-generators/ai.d.ts.map +1 -0
  197. package/dist/schema/value-generators/ai.js +136 -0
  198. package/dist/schema/value-generators/ai.js.map +1 -0
  199. package/dist/schema/value-generators/index.d.ts +126 -0
  200. package/dist/schema/value-generators/index.d.ts.map +1 -0
  201. package/dist/schema/value-generators/index.js +219 -0
  202. package/dist/schema/value-generators/index.js.map +1 -0
  203. package/dist/schema/value-generators/placeholder.d.ts +52 -0
  204. package/dist/schema/value-generators/placeholder.d.ts.map +1 -0
  205. package/dist/schema/value-generators/placeholder.js +328 -0
  206. package/dist/schema/value-generators/placeholder.js.map +1 -0
  207. package/dist/schema/value-generators/types.d.ts +116 -0
  208. package/dist/schema/value-generators/types.d.ts.map +1 -0
  209. package/dist/schema/value-generators/types.js +11 -0
  210. package/dist/schema/value-generators/types.js.map +1 -0
  211. package/dist/schema/version.d.ts +111 -0
  212. package/dist/schema/version.d.ts.map +1 -0
  213. package/dist/schema/version.js +190 -0
  214. package/dist/schema/version.js.map +1 -0
  215. package/dist/schema.d.ts +1095 -24
  216. package/dist/schema.d.ts.map +1 -1
  217. package/dist/schema.js +2852 -40
  218. package/dist/schema.js.map +1 -1
  219. package/dist/semantic-vectors.d.ts +39 -0
  220. package/dist/semantic-vectors.d.ts.map +1 -0
  221. package/dist/semantic-vectors.js +334 -0
  222. package/dist/semantic-vectors.js.map +1 -0
  223. package/dist/semantic.d.ts +29 -1
  224. package/dist/semantic.d.ts.map +1 -1
  225. package/dist/semantic.js +26 -16
  226. package/dist/semantic.js.map +1 -1
  227. package/dist/telemetry.d.ts +128 -0
  228. package/dist/telemetry.d.ts.map +1 -0
  229. package/dist/telemetry.js +305 -0
  230. package/dist/telemetry.js.map +1 -0
  231. package/dist/tests.d.ts.map +1 -1
  232. package/dist/tests.js +30 -22
  233. package/dist/tests.js.map +1 -1
  234. package/dist/type-guards.d.ts +50 -5
  235. package/dist/type-guards.d.ts.map +1 -1
  236. package/dist/type-guards.js +87 -16
  237. package/dist/type-guards.js.map +1 -1
  238. package/dist/types.d.ts +33 -245
  239. package/dist/types.d.ts.map +1 -1
  240. package/dist/types.js +62 -72
  241. package/dist/types.js.map +1 -1
  242. package/dist/validation.d.ts +2 -5
  243. package/dist/validation.d.ts.map +1 -1
  244. package/dist/validation.js +65 -93
  245. package/dist/validation.js.map +1 -1
  246. package/dist/worker/db-provider.d.ts +168 -0
  247. package/dist/worker/db-provider.d.ts.map +1 -0
  248. package/dist/worker/db-provider.js +277 -0
  249. package/dist/worker/db-provider.js.map +1 -0
  250. package/dist/worker/index.d.ts +35 -0
  251. package/dist/worker/index.d.ts.map +1 -0
  252. package/dist/worker/index.js +37 -0
  253. package/dist/worker/index.js.map +1 -0
  254. package/dist/worker.d.ts +779 -0
  255. package/dist/worker.d.ts.map +1 -0
  256. package/dist/worker.js +2786 -0
  257. package/dist/worker.js.map +1 -0
  258. package/package.json +46 -16
  259. package/src/docs-rels/migrations/0001-init.sql +125 -0
  260. package/LICENSE +0 -21
package/dist/schema.d.ts CHANGED
@@ -1,17 +1,8 @@
1
1
  /**
2
2
  * Schema-first Database Definition
3
3
  *
4
- * This file re-exports all schema functionality from the modular `./schema/` directory.
5
- * It serves as the main entry point for backwards compatibility.
6
- *
7
- * The actual implementation is split into smaller modules:
8
- * - schema/types.ts - TypeScript types/interfaces
9
- * - schema/parse.ts - Schema parsing logic
10
- * - schema/provider.ts - Database provider interface and resolution
11
- * - schema/resolve.ts - Resolution functions for entity hydration
12
- * - schema/cascade.ts - Cascade generation and context-aware value generation
13
- * - schema/semantic.ts - Fuzzy/semantic resolution functions
14
- * - schema/index.ts - Main factory and entity operations
4
+ * Declarative schema with automatic bi-directional relationships.
5
+ * Uses mdxld conventions for entity structure.
15
6
  *
16
7
  * @example
17
8
  * ```ts
@@ -36,22 +27,1102 @@
36
27
  * post.author // Author (single)
37
28
  * post.tags // Tag[] (array)
38
29
  * ```
39
- *
40
- * @packageDocumentation
41
30
  */
31
+ import { DBPromise, type ForEachOptions, type ForEachResult } from './ai-promise-db.js';
32
+ import { type EmbeddingsConfig } from './semantic.js';
33
+ import { type EventBridgeAPI } from './eventbridge.js';
34
+ export type { EventBridgeAPI } from './eventbridge.js';
42
35
  export type { ThingFlat, ThingExpanded, PrimitiveType, FieldDefinition, EntitySchema, DatabaseSchema, ParsedField, ParsedEntity, ParsedSchema, Verb, Noun, NounProperty, NounRelationship, TypeMeta, EntityId, Thing, Relationship, QueryOptions, ThingSearchOptions, CreateOptions, UpdateOptions, RelateOptions, Event, ActionStatus, Action, ArtifactType, Artifact, StoreArtifactOptions, EventQueryOptions, ActionQueryOptions, DBClient, DBClientExtended, CreateEventOptions as GraphCreateEventOptions, CreateActionOptions as GraphCreateActionOptions, } from './types.js';
43
36
  export { toExpanded, toFlat, Verbs, resolveUrl, resolveShortUrl, parseUrl } from './types.js';
44
37
  export type { EmbeddingsConfig } from './semantic.js';
38
+ export { configureAIGeneration, getAIGenerationConfig, setValueGenerator, getValueGenerator, createEntityOperations, createEdgeEntityOperations, FORWARD_TO_REVERSE, BIDIRECTIONAL_PAIRS, deriveReverseVerb, fieldNameToVerb, isPassiveVerb, registerVerbPair, registerBidirectionalPair, registerFieldVerb, hasSemanticSearch, hasHybridSearch, hasEventsAPI, hasActionsAPI, hasArtifactsAPI, hasEmbeddingsConfig, computeSchemaHash, getSchemaVersion, setSchemaVersion, hasSchemaChanged, diffSchemas, describeDiff, defineMigration, runMigrations, getPendingMigrations, rollbackLastMigration, parseOperator, parseField, parseSchema, isPrimitiveType, } from './schema/index.js';
39
+ import type { AIGenerationConfig } from './schema/cascade.js';
40
+ export type { AIGenerationConfig, EntityOperationsConfig, GenerationDetails, SeedResult, SchemaVersionInfo, FieldChange, PossibleRename, EntityDiff, SchemaDiff, MigrationOperationType, AddEntityOperation, RemoveEntityOperation, AddFieldOperation, RemoveFieldOperation, RenameFieldOperation, ChangeTypeOperation, TransformDataOperation, MigrationOperation, Migration, MigrationResult, OperatorParseResult, DBProvider, NLQueryGenerator, NLQueryContext, NLQueryPlan, NLQueryResult, NLQueryFn, } from './schema/index.js';
41
+ import { parseSchema } from './schema/parse.js';
42
+ import { type DBProvider } from './schema/provider.js';
43
+ import type { NLQueryGenerator, NLQueryContext, NLQueryResult, NLQueryFn } from './schema/types.js';
45
44
  export { conjugate, pluralize, singularize, inferNoun, createTypeMeta, getTypeMeta, Type, getVerbFields, } from './linguistic.js';
46
- export type { ReferenceSpec, Draft, Resolved, DraftOptions, ResolveOptions, CascadeProgress, CreateEntityOptions, OperatorParseResult, ListOptions, SearchOptions, SemanticSearchOptions, HybridSearchOptions, EmbeddingTypeConfig, ActorData, DBEvent, CreateEventOptions, DBAction, CreateActionOptions, DBArtifact, EventsAPI, ActionsAPI, ArtifactsAPI, NounsAPI, VerbsAPI, NLQueryResult, NLQueryFn, NLQueryContext, NLQueryPlan, NLQueryGenerator, GenerateOptions, DBOptions, } from './schema/types.js';
47
- export { parseOperator, parseField, parseSchema, isPrimitiveType } from './schema/parse.js';
48
- export type { DBProvider, DBProviderExtended } from './schema/provider.js';
49
- export { setProvider, resolveProvider } from './schema/provider.js';
50
- export { isEntityId, inferTypeFromField, resolveContextPath, resolveInstructions, prefetchContext, isPromptField, resolveNestedPending, resolveReferenceSpec, hydrateEntity, } from './schema/resolve.js';
51
- export { generateContextAwareValue, generateAIFields, generateEntity, resolveForwardExact, generateNaturalLanguageContent, } from './schema/cascade.js';
52
- export { resolveBackwardFuzzy, resolveForwardFuzzy } from './schema/semantic.js';
53
- export { FORWARD_TO_REVERSE, BIDIRECTIONAL_PAIRS, deriveReverseVerb, fieldNameToVerb, isPassiveVerb, registerVerbPair, registerBidirectionalPair, registerFieldVerb, } from './schema/verb-derivation.js';
54
- export { defineNoun, defineVerb, nounToSchema, ThingSchema, NounSchema, VerbSchema, EdgeSchema, SystemSchema, createEdgeRecords, createNounRecord, setNLQueryGenerator, DB, } from './schema/index.js';
55
- export type { InferEntity, EntityOperations, PipelineEntityOperations, TypedDB, DBResult, } from './schema/index.js';
56
- export { parseSchema as parse } from './schema/parse.js';
45
+ import type { EntitySchema, DatabaseSchema, ParsedEntity, ParsedSchema, Verb, Noun } from './types.js';
46
+ /**
47
+ * Create a Noun definition with type inference
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const Post = defineNoun({
52
+ * singular: 'post',
53
+ * plural: 'posts',
54
+ * description: 'A blog post',
55
+ * properties: {
56
+ * title: { type: 'string', description: 'Post title' },
57
+ * content: { type: 'markdown' },
58
+ * },
59
+ * relationships: {
60
+ * author: { type: 'Author', backref: 'posts' },
61
+ * },
62
+ * })
63
+ * ```
64
+ */
65
+ export declare function defineNoun<T extends Noun>(noun: T): T;
66
+ /**
67
+ * Create a Verb definition with type inference
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * const publish = defineVerb({
72
+ * action: 'publish',
73
+ * actor: 'publisher',
74
+ * act: 'publishes',
75
+ * activity: 'publishing',
76
+ * result: 'publication',
77
+ * reverse: { at: 'publishedAt', by: 'publishedBy' },
78
+ * inverse: 'unpublish',
79
+ * })
80
+ * ```
81
+ */
82
+ export declare function defineVerb<T extends Verb>(verb: T): T;
83
+ /**
84
+ * Convert a Noun to an EntitySchema for use with DB()
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const postNoun = defineNoun({
89
+ * singular: 'post',
90
+ * plural: 'posts',
91
+ * properties: { title: { type: 'string' } },
92
+ * relationships: { author: { type: 'Author', backref: 'posts' } },
93
+ * })
94
+ *
95
+ * const db = DB({
96
+ * Post: nounToSchema(postNoun),
97
+ * })
98
+ * ```
99
+ */
100
+ export declare function nounToSchema(noun: Noun): EntitySchema;
101
+ /**
102
+ * Built-in Thing schema - base type for all entities
103
+ *
104
+ * Every entity instance is a Thing with a relationship to its Noun.
105
+ * This creates a complete graph: Thing.type -> Noun.things
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * // Every post instance:
110
+ * post.$type // 'Post' (string)
111
+ * post.type // -> Noun('Post') (relationship)
112
+ *
113
+ * // From Noun, get all instances:
114
+ * const postNoun = await db.Noun.get('Post')
115
+ * const allPosts = await postNoun.things // -> Post[]
116
+ * ```
117
+ */
118
+ export declare const ThingSchema: EntitySchema;
119
+ /**
120
+ * Built-in Noun schema for storing type definitions
121
+ *
122
+ * Every Type/Collection automatically gets a Noun record stored in the database.
123
+ * This enables introspection and self-describing schemas.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * // When you define:
128
+ * const db = DB({ Post: { title: 'string' } })
129
+ *
130
+ * // The database auto-creates:
131
+ * // db.Noun.get('Post') => { singular: 'post', plural: 'posts', ... }
132
+ *
133
+ * // Query all types:
134
+ * const types = await db.Noun.list()
135
+ *
136
+ * // Get all instances of a type:
137
+ * const postNoun = await db.Noun.get('Post')
138
+ * const allPosts = await postNoun.things
139
+ *
140
+ * // Listen for new types:
141
+ * on.Noun.created(noun => console.log(`New type: ${noun.name}`))
142
+ * ```
143
+ */
144
+ export declare const NounSchema: EntitySchema;
145
+ /**
146
+ * Built-in Verb schema for storing action definitions
147
+ */
148
+ export declare const VerbSchema: EntitySchema;
149
+ /**
150
+ * Built-in Edge schema for relationships between types
151
+ *
152
+ * Every relationship in a schema creates an Edge record.
153
+ * This enables graph queries across the type system.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * // Post.author -> Author creates:
158
+ * // Edge { from: 'Post', name: 'author', to: 'Author', backref: 'posts', cardinality: 'many-to-one' }
159
+ *
160
+ * // Query the graph:
161
+ * const edges = await db.Edge.find({ to: 'Author' })
162
+ * // => [{ from: 'Post', name: 'author' }, { from: 'Comment', name: 'author' }]
163
+ *
164
+ * // What types reference Author?
165
+ * const referencing = edges.map(e => e.from) // ['Post', 'Comment']
166
+ * ```
167
+ */
168
+ export declare const EdgeSchema: EntitySchema;
169
+ /**
170
+ * System types that are auto-created in every database
171
+ *
172
+ * The graph structure:
173
+ * - Thing.type -> Noun (every instance links to its type)
174
+ * - Noun.things -> Thing[] (every type has its instances)
175
+ * - Edge connects Nouns (relationships between types)
176
+ * - Verb describes actions on Nouns
177
+ */
178
+ export declare const SystemSchema: DatabaseSchema;
179
+ /**
180
+ * Create Edge records from schema relationships
181
+ *
182
+ * @internal Used by DB() to auto-populate Edge records
183
+ *
184
+ * For backward edges (direction === 'backward'), the from/to are inverted:
185
+ * - Forward: from = typeName, to = relatedType
186
+ * - Backward: from = relatedType, to = typeName
187
+ *
188
+ * This enables proper graph traversal where backward edges represent
189
+ * "pointing to" relationships (e.g., Post.comments -> Comments that point TO Post)
190
+ */
191
+ export declare function createEdgeRecords(typeName: string, schema: EntitySchema, parsedEntity: ParsedEntity): Array<Record<string, unknown>>;
192
+ /**
193
+ * Create a Noun record from a type name and optional schema
194
+ *
195
+ * @internal Used by DB() to auto-populate Noun records
196
+ */
197
+ export declare function createNounRecord(typeName: string, schema?: EntitySchema, nounDef?: Partial<Noun>): Record<string, unknown>;
198
+ /**
199
+ * Reference specification for unresolved relationships in a draft
200
+ */
201
+ export interface ReferenceSpec {
202
+ /** Field name on the entity */
203
+ field: string;
204
+ /** The relationship operator: ->, ~>, <-, <~ */
205
+ operator: '->' | '~>' | '<-' | '<~';
206
+ /** Target entity type */
207
+ type: string;
208
+ /** Match mode for resolving */
209
+ matchMode: 'exact' | 'fuzzy';
210
+ /** Whether this reference is resolved */
211
+ resolved: boolean;
212
+ /** Natural language prompt for generation */
213
+ prompt?: string;
214
+ /** Generated natural language text (before resolution) */
215
+ generatedText?: string;
216
+ /** Instructions from the source entity's $instructions metadata */
217
+ sourceInstructions?: string;
218
+ /** Fuzzy match threshold */
219
+ threshold?: number;
220
+ /** Union types for polymorphic references */
221
+ unionTypes?: string[];
222
+ }
223
+ /**
224
+ * Draft entity with unresolved references
225
+ *
226
+ * A draft is an entity that has been generated but whose relationships
227
+ * have not yet been resolved to actual entity IDs. This allows:
228
+ * - Streaming draft content to users before relationships are resolved
229
+ * - Batch resolution of multiple references for efficiency
230
+ * - Draft-only mode for preview/editing before final creation
231
+ */
232
+ export interface Draft<T> {
233
+ /** Phase marker indicating this is a draft */
234
+ $phase: 'draft';
235
+ /** Unresolved reference specifications */
236
+ $refs: Record<string, ReferenceSpec | ReferenceSpec[]>;
237
+ /** Entity data with natural language placeholders for references */
238
+ [key: string]: unknown;
239
+ }
240
+ /**
241
+ * Resolved entity after resolution phase
242
+ */
243
+ export interface Resolved<T> {
244
+ /** Phase marker indicating this has been resolved */
245
+ $phase: 'resolved';
246
+ /** Any errors that occurred during resolution */
247
+ $errors?: Array<{
248
+ field: string;
249
+ error: string;
250
+ }>;
251
+ /** Entity data with resolved reference IDs */
252
+ [key: string]: unknown;
253
+ }
254
+ /**
255
+ * Options for the draft() method
256
+ */
257
+ export interface DraftOptions {
258
+ /** Enable streaming of draft content */
259
+ stream?: boolean;
260
+ /** Callback for streaming chunks */
261
+ onChunk?: (chunk: string) => void;
262
+ }
263
+ /**
264
+ * Options for the resolve() method
265
+ */
266
+ export interface ResolveOptions {
267
+ /** How to handle resolution errors */
268
+ onError?: 'throw' | 'skip';
269
+ /** Callback when a reference is resolved */
270
+ onResolved?: (fieldName: string, entityId: string) => void;
271
+ }
272
+ /**
273
+ * Progress tracking for cascade generation
274
+ */
275
+ export interface CascadeProgress {
276
+ /** Current phase of cascade generation */
277
+ phase: 'generating' | 'complete' | 'error';
278
+ /** Type currently being generated */
279
+ currentType?: string;
280
+ /** Current recursion depth */
281
+ currentDepth: number;
282
+ /** Alias for currentDepth for convenience */
283
+ depth: number;
284
+ /** Total number of entities created during cascade */
285
+ totalEntitiesCreated: number;
286
+ /** List of types that have been generated */
287
+ typesGenerated: string[];
288
+ }
289
+ /**
290
+ * Options for cascade generation
291
+ */
292
+ export interface CascadeOptions {
293
+ /** Enable cascade generation through relationships */
294
+ cascade?: boolean;
295
+ /** Maximum depth for cascade recursion (default: 3) */
296
+ maxDepth?: number;
297
+ /** Limit cascade to specific types */
298
+ cascadeTypes?: string[];
299
+ /** Progress callback for tracking cascade generation */
300
+ onProgress?: (progress: CascadeProgress) => void;
301
+ /** Error callback for handling cascade errors */
302
+ onError?: (error: Error, context: {
303
+ type: string;
304
+ depth: number;
305
+ }) => void;
306
+ /** Stop cascade on first error */
307
+ stopOnError?: boolean;
308
+ }
309
+ /**
310
+ * Options for the create() method
311
+ */
312
+ export interface CreateEntityOptions extends CascadeOptions {
313
+ /** Only create a draft, don't resolve references */
314
+ draftOnly?: boolean;
315
+ }
316
+ /**
317
+ * Map field type to TypeScript type
318
+ */
319
+ type FieldToTS<T extends string> = T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'date' | 'datetime' ? Date : T extends 'json' ? Record<string, unknown> : T extends 'markdown' ? string : T extends 'url' ? string : unknown;
320
+ /**
321
+ * Parse a union string like 'A | B | C' into a union type
322
+ */
323
+ type ParseUnion<T extends string> = T extends `${infer A} | ${infer B}` ? A | ParseUnion<B> : T;
324
+ /**
325
+ * Infer the TypeScript type for a single field string value, given the full schema
326
+ */
327
+ type InferFieldValue<TSchema extends DatabaseSchema, V extends string> = V extends `->${infer Target}` ? Target extends keyof TSchema ? InferEntity<TSchema, Target> : string : V extends `<-${infer Target}` ? Target extends keyof TSchema ? InferEntity<TSchema, Target> : string : V extends `~>${infer Target}` ? Target extends keyof TSchema ? InferEntity<TSchema, Target> : string : V extends `<~${infer Target}` ? Target extends keyof TSchema ? InferEntity<TSchema, Target> : string : V extends `${infer Type}.${string}` ? Type extends keyof TSchema ? InferEntity<TSchema, Type> : unknown : V extends `${infer Type}[]` ? Type extends keyof TSchema ? InferEntity<TSchema, Type>[] : FieldToTS<Type>[] : V extends `${infer Type}?` ? FieldToTS<Type> | undefined : V extends `${string} | ${string}` ? ParseUnion<V> : FieldToTS<V>;
328
+ /**
329
+ * Infer entity type from schema definition
330
+ */
331
+ export type InferEntity<TSchema extends DatabaseSchema, TEntity extends keyof TSchema> = {
332
+ $id: string;
333
+ $type: TEntity;
334
+ } & {
335
+ [K in keyof TSchema[TEntity]]: TSchema[TEntity][K] extends readonly [infer Inner extends string] ? InferFieldValue<TSchema, Inner> extends infer R ? R[] : never : TSchema[TEntity][K] extends [infer Inner extends string] ? InferFieldValue<TSchema, Inner> extends infer R ? R[] : never : TSchema[TEntity][K] extends string ? InferFieldValue<TSchema, TSchema[TEntity][K]> : unknown;
336
+ };
337
+ /**
338
+ * Operations available on each entity type
339
+ */
340
+ export interface EntityOperations<T> {
341
+ /** Get an entity by ID */
342
+ get(id: string): Promise<T | null>;
343
+ /** List all entities */
344
+ list(options?: ListOptions): Promise<T[]>;
345
+ /** Find entities matching criteria */
346
+ find(where: Partial<T>): Promise<T[]>;
347
+ /** Search entities */
348
+ search(query: string, options?: SearchOptions): Promise<T[]>;
349
+ /** Create a new entity */
350
+ create(data: Omit<T, '$id' | '$type'>): Promise<T>;
351
+ create(id: string, data: Omit<T, '$id' | '$type'>): Promise<T>;
352
+ /** Update an entity */
353
+ update(id: string, data: Partial<Omit<T, '$id' | '$type'>>): Promise<T>;
354
+ /** Upsert an entity */
355
+ upsert(id: string, data: Omit<T, '$id' | '$type'>): Promise<T>;
356
+ /** Delete an entity */
357
+ delete(id: string): Promise<boolean>;
358
+ /** Iterate over entities */
359
+ forEach(callback: (entity: T) => void | Promise<void>): Promise<void>;
360
+ forEach(options: ListOptions, callback: (entity: T) => void | Promise<void>): Promise<void>;
361
+ /** Semantic search */
362
+ semanticSearch?(query: string, options?: SemanticSearchOptions): Promise<Array<T & {
363
+ $score: number;
364
+ }>>;
365
+ /** Hybrid search */
366
+ hybridSearch?(query: string, options?: HybridSearchOptions): Promise<Array<T & {
367
+ $rrfScore: number;
368
+ $ftsRank: number;
369
+ $semanticRank: number;
370
+ $score: number;
371
+ }>>;
372
+ /** Create draft entity */
373
+ draft?(data: Partial<Omit<T, '$id' | '$type'>>, options?: DraftOptions): Promise<Draft<T>>;
374
+ /** Resolve draft entity */
375
+ resolve?(draft: Draft<T>, options?: ResolveOptions): Promise<Resolved<T>>;
376
+ }
377
+ /**
378
+ * Operations with promise pipelining support
379
+ *
380
+ * Query methods return DBPromise for chainable operations:
381
+ * - `.map()` with batch optimization
382
+ * - `.filter()`, `.sort()`, `.limit()`
383
+ * - Property access tracking for projections
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * // Chain without await
388
+ * const leads = db.Lead.list()
389
+ * const qualified = await leads
390
+ * .filter(l => l.score > 80)
391
+ * .map(l => ({ name: l.name, company: l.company }))
392
+ *
393
+ * // Batch relationship loading
394
+ * const orders = await db.Order.list().map(o => ({
395
+ * order: o,
396
+ * customer: o.customer, // Batch loaded!
397
+ * }))
398
+ * ```
399
+ */
400
+ export interface PipelineEntityOperations<T> {
401
+ /** Get an entity by ID */
402
+ get(id: string): DBPromise<T | null>;
403
+ /** List all entities */
404
+ list(options?: ListOptions): DBPromise<T[]>;
405
+ /** Find entities matching criteria */
406
+ find(where: Partial<T>): DBPromise<T[]>;
407
+ /** Search entities */
408
+ search(query: string, options?: SearchOptions): DBPromise<T[]>;
409
+ /** Get first matching entity */
410
+ first(): DBPromise<T | null>;
411
+ /** Create a new entity */
412
+ create(data: Omit<T, '$id' | '$type'>, options?: CreateEntityOptions): Promise<T | Draft<T>>;
413
+ create(id: string, data: Omit<T, '$id' | '$type'>, options?: CreateEntityOptions): Promise<T | Draft<T>>;
414
+ /**
415
+ * Create a draft entity with natural language placeholders for references
416
+ *
417
+ * The draft phase generates entity content but leaves relationship fields
418
+ * as natural language descriptions that will be resolved later.
419
+ *
420
+ * @example
421
+ * ```ts
422
+ * const draft = await db.Startup.draft({ name: 'Acme' })
423
+ * // draft.idea contains natural language like "A revolutionary SaaS idea"
424
+ * // draft.$refs.idea contains reference spec for resolution
425
+ * ```
426
+ */
427
+ draft(data: Partial<Omit<T, '$id' | '$type'>>, options?: DraftOptions): Promise<Draft<T>>;
428
+ /**
429
+ * Resolve a draft entity by converting natural language references to entity IDs
430
+ *
431
+ * The resolve phase creates or matches related entities and replaces
432
+ * natural language placeholders with actual entity IDs.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * const draft = await db.Startup.draft({ name: 'Acme' })
437
+ * const resolved = await db.Startup.resolve(draft)
438
+ * // resolved.idea is now an actual entity ID
439
+ * ```
440
+ */
441
+ resolve(draft: Draft<T>, options?: ResolveOptions): Promise<Resolved<T>>;
442
+ /** Update an entity */
443
+ update(id: string, data: Partial<Omit<T, '$id' | '$type'>>): Promise<T>;
444
+ /** Upsert an entity */
445
+ upsert(id: string, data: Omit<T, '$id' | '$type'>): Promise<T>;
446
+ /** Delete an entity */
447
+ delete(id: string): Promise<boolean>;
448
+ /**
449
+ * Process each entity with concurrency control, progress tracking, and error handling
450
+ *
451
+ * Designed for large-scale operations like AI generations or workflows.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * // Simple iteration
456
+ * await db.Lead.forEach(lead => console.log(lead.name))
457
+ *
458
+ * // With AI and concurrency
459
+ * const result = await db.Lead.forEach(async lead => {
460
+ * const analysis = await ai`analyze ${lead}`
461
+ * await db.Lead.update(lead.$id, { analysis })
462
+ * }, {
463
+ * concurrency: 10,
464
+ * onProgress: p => console.log(`${p.completed}/${p.total}`),
465
+ * })
466
+ *
467
+ * // With error handling
468
+ * await db.Order.forEach(async order => {
469
+ * await sendInvoice(order)
470
+ * }, {
471
+ * maxRetries: 3,
472
+ * onError: (err, order) => err.code === 'RATE_LIMIT' ? 'retry' : 'continue',
473
+ * })
474
+ * ```
475
+ */
476
+ forEach<U>(callback: (entity: T, index: number) => U | Promise<U>, options?: ForEachOptions<T>): Promise<ForEachResult>;
477
+ /**
478
+ * Semantic search using embedding similarity
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * const results = await db.Document.semanticSearch('deep learning neural networks')
483
+ * // Returns documents with $score field sorted by similarity
484
+ * ```
485
+ */
486
+ semanticSearch(query: string, options?: SemanticSearchOptions): Promise<Array<T & {
487
+ $score: number;
488
+ }>>;
489
+ /**
490
+ * Hybrid search combining FTS and semantic search with RRF scoring
491
+ *
492
+ * @example
493
+ * ```ts
494
+ * const results = await db.Post.hybridSearch('React useState')
495
+ * // Returns posts with $rrfScore, $ftsRank, $semanticRank fields
496
+ * ```
497
+ */
498
+ hybridSearch(query: string, options?: HybridSearchOptions): Promise<Array<T & {
499
+ $rrfScore: number;
500
+ $ftsRank: number;
501
+ $semanticRank: number;
502
+ $score: number;
503
+ }>>;
504
+ }
505
+ export interface ListOptions {
506
+ where?: Record<string, unknown>;
507
+ orderBy?: string;
508
+ order?: 'asc' | 'desc';
509
+ limit?: number;
510
+ offset?: number;
511
+ /**
512
+ * Suppress errors and return empty array instead of throwing.
513
+ * Useful for graceful degradation when the database is unavailable.
514
+ */
515
+ suppressErrors?: boolean;
516
+ /**
517
+ * Error handler callback. If provided, errors are passed to this callback
518
+ * instead of being thrown. The callback can return a fallback value.
519
+ */
520
+ onError?: (error: Error) => unknown[] | void;
521
+ }
522
+ export interface SearchOptions extends ListOptions {
523
+ fields?: string[];
524
+ minScore?: number;
525
+ }
526
+ /**
527
+ * Options for semantic search
528
+ */
529
+ export interface SemanticSearchOptions {
530
+ /** Minimum similarity score (0-1) */
531
+ minScore?: number;
532
+ /** Maximum number of results */
533
+ limit?: number;
534
+ }
535
+ /**
536
+ * Options for hybrid search (FTS + semantic)
537
+ */
538
+ export interface HybridSearchOptions {
539
+ /** Minimum similarity score for semantic results */
540
+ minScore?: number;
541
+ /** Maximum number of results */
542
+ limit?: number;
543
+ /** Offset for pagination */
544
+ offset?: number;
545
+ /** RRF k parameter (default: 60) */
546
+ rrfK?: number;
547
+ /** Weight for FTS results (default: 0.5) */
548
+ ftsWeight?: number;
549
+ /** Weight for semantic results (default: 0.5) */
550
+ semanticWeight?: number;
551
+ }
552
+ /**
553
+ * Embedding configuration for a specific entity type
554
+ */
555
+ export interface EmbeddingTypeConfig {
556
+ /** Fields to embed (defaults to text/markdown fields) */
557
+ fields?: string[];
558
+ }
559
+ /**
560
+ * DB Options for configuring embeddings and other settings
561
+ */
562
+ export interface DBOptions {
563
+ /** Embedding configuration per type */
564
+ embeddings?: EmbeddingsConfig;
565
+ /**
566
+ * Database provider instance or factory function.
567
+ * When provided, this provider is used instead of the global provider.
568
+ * This enables dependency injection for testing and isolated DB instances.
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * // Direct provider instance
573
+ * const db = DB(schema, { provider: myProvider })
574
+ *
575
+ * // Lazy factory function (created on first use)
576
+ * const db = DB(schema, { provider: () => createMyProvider() })
577
+ * ```
578
+ */
579
+ provider?: DBProvider | (() => DBProvider) | (() => Promise<DBProvider>);
580
+ /**
581
+ * AI generation configuration.
582
+ * When provided, these settings are used instead of the global aiConfig.
583
+ * This enables dependency injection for testing and isolated DB instances.
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * const db = DB(schema, {
588
+ * aiGeneration: {
589
+ * model: 'gpt-4',
590
+ * enabled: true,
591
+ * onGenerate: (details) => console.log('Generated:', details)
592
+ * }
593
+ * })
594
+ * ```
595
+ */
596
+ aiGeneration?: Partial<AIGenerationConfig>;
597
+ }
598
+ /**
599
+ * Typed database client based on schema
600
+ *
601
+ * Entity operations return DBPromise for chainable queries:
602
+ * ```ts
603
+ * const { db } = DB({ Lead: { name: 'string', company: 'Company.leads' } })
604
+ *
605
+ * // Chain without await
606
+ * const leads = db.Lead.list()
607
+ * const qualified = await leads.filter(l => l.score > 80)
608
+ *
609
+ * // Batch relationship loading
610
+ * const withCompanies = await leads.map(l => ({
611
+ * lead: l,
612
+ * company: l.company, // Batch loaded!
613
+ * }))
614
+ * ```
615
+ */
616
+ export type TypedDB<TSchema extends DatabaseSchema> = {
617
+ [K in keyof TSchema]: PipelineEntityOperations<InferEntity<TSchema, K>> & NLQueryFn<InferEntity<TSchema, K>>;
618
+ } & {
619
+ /** The parsed schema */
620
+ readonly $schema: ParsedSchema;
621
+ /** Get any entity by URL */
622
+ get(url: string): Promise<unknown>;
623
+ /** Search across all entities */
624
+ search(query: string, options?: SearchOptions): Promise<unknown[]>;
625
+ /** Count entities of a type */
626
+ count(type: string, where?: Record<string, unknown>): Promise<number>;
627
+ /** Iterate over entities with a callback */
628
+ forEach(options: {
629
+ type: string;
630
+ where?: Record<string, unknown>;
631
+ concurrency?: number;
632
+ }, callback: (entity: unknown) => void | Promise<void>): Promise<void>;
633
+ /** Set entity data by ID (creates or replaces) */
634
+ set(type: string, id: string, data: Record<string, unknown>): Promise<unknown>;
635
+ /** Generate entities using AI */
636
+ generate(options: GenerateOptions): Promise<unknown | {
637
+ id: string;
638
+ }>;
639
+ /**
640
+ * Natural language query across all types
641
+ *
642
+ * @example
643
+ * ```ts
644
+ * const results = await db`what orders are pending for customers in california?`
645
+ * const results = await db`show me joe's recent activity`
646
+ * const results = await db`what changed in the last hour?`
647
+ * ```
648
+ */
649
+ ask: NLQueryFn;
650
+ /**
651
+ * Global semantic search across all entity types
652
+ *
653
+ * @example
654
+ * ```ts
655
+ * const results = await db.semanticSearch('artificial intelligence')
656
+ * // Returns results from all types with $type and $score fields
657
+ * ```
658
+ */
659
+ semanticSearch(query: string, options?: SemanticSearchOptions): Promise<Array<{
660
+ $id: string;
661
+ $type: string;
662
+ $score: number;
663
+ [key: string]: unknown;
664
+ }>>;
665
+ /**
666
+ * Subscribe to database events (draft, resolve, create, update, delete)
667
+ *
668
+ * @example
669
+ * ```ts
670
+ * db.on('draft', (entity) => console.log('Draft created:', entity.$type))
671
+ * db.on('resolve', (entity) => console.log('Entity resolved:', entity.$type))
672
+ * db.on('Post.created', (event) => console.log('Post created'))
673
+ * ```
674
+ */
675
+ on(event: string, handler: (data: unknown) => void): () => void;
676
+ };
677
+ /**
678
+ * Options for AI-powered entity generation
679
+ */
680
+ export interface GenerateOptions {
681
+ type: string;
682
+ count?: number;
683
+ data?: Record<string, unknown>;
684
+ mode?: 'sync' | 'background';
685
+ }
686
+ /**
687
+ * Actor data - who performed the action
688
+ *
689
+ * @example
690
+ * ```ts
691
+ * const actorData: ActorData = {
692
+ * name: 'John Doe',
693
+ * email: 'john@example.com',
694
+ * org: 'Acme Corp',
695
+ * role: 'admin',
696
+ * }
697
+ * ```
698
+ */
699
+ export interface ActorData {
700
+ /** Actor's display name */
701
+ name?: string;
702
+ /** Actor's email */
703
+ email?: string;
704
+ /** Actor's organization */
705
+ org?: string;
706
+ /** Actor's role or access level */
707
+ role?: string;
708
+ /** Additional actor metadata */
709
+ [key: string]: unknown;
710
+ }
711
+ /**
712
+ * Event data structure - Actor-Event-Object-Result pattern
713
+ *
714
+ * Following ActivityStreams semantics:
715
+ * - Actor: Who did it (user, system, agent)
716
+ * - Event: What happened (created, updated, published)
717
+ * - Object: What it was done to (the entity)
718
+ * - Result: What was the outcome (optional)
719
+ *
720
+ * @example
721
+ * ```ts
722
+ * const event: DBEvent = {
723
+ * id: '01HGXYZ...',
724
+ * actor: 'user:john',
725
+ * actorData: { name: 'John Doe', email: 'john@example.com' },
726
+ * event: 'Post.published',
727
+ * object: 'https://example.com/Post/hello-world',
728
+ * objectData: { title: 'Hello World' },
729
+ * result: 'https://example.com/Publication/123',
730
+ * resultData: { url: 'https://blog.example.com/hello-world' },
731
+ * timestamp: new Date(),
732
+ * }
733
+ * ```
734
+ */
735
+ export interface DBEvent {
736
+ /** Unique event ID (ULID recommended) */
737
+ id: string;
738
+ /** Actor identifier (user:id, system, agent:name) */
739
+ actor: string;
740
+ /** Actor metadata */
741
+ actorData?: ActorData;
742
+ /** Event type (Entity.action format, e.g., Post.created) */
743
+ event: string;
744
+ /** Object URL/identifier that was acted upon */
745
+ object?: string;
746
+ /** Object data snapshot at time of event */
747
+ objectData?: Record<string, unknown>;
748
+ /** Result URL/identifier (outcome of the action) */
749
+ result?: string;
750
+ /** Result data */
751
+ resultData?: Record<string, unknown>;
752
+ /** Additional metadata */
753
+ meta?: Record<string, unknown>;
754
+ /** When the event occurred */
755
+ timestamp: Date;
756
+ /** @deprecated Use 'event' instead */
757
+ type?: string;
758
+ /** @deprecated Use 'objectData' instead */
759
+ data?: unknown;
760
+ /** @deprecated Use 'object' instead */
761
+ url?: string;
762
+ }
763
+ /**
764
+ * Options for creating an event
765
+ */
766
+ export interface CreateEventOptions {
767
+ /** Actor identifier */
768
+ actor: string;
769
+ /** Actor metadata */
770
+ actorData?: ActorData;
771
+ /** Event type */
772
+ event: string;
773
+ /** Object URL/identifier */
774
+ object?: string;
775
+ /** Object data */
776
+ objectData?: Record<string, unknown>;
777
+ /** Result URL/identifier */
778
+ result?: string;
779
+ /** Result data */
780
+ resultData?: Record<string, unknown>;
781
+ /** Additional metadata */
782
+ meta?: Record<string, unknown>;
783
+ }
784
+ /**
785
+ * Events API for subscribing to and emitting events
786
+ */
787
+ export interface EventsAPI {
788
+ /** Subscribe to events matching a pattern */
789
+ on(pattern: string, handler: (event: DBEvent) => void | Promise<void>): () => void;
790
+ /** Emit an event using Actor-Event-Object-Result pattern */
791
+ emit(options: CreateEventOptions): Promise<DBEvent>;
792
+ /** Emit a simple event (legacy compatibility) */
793
+ emit(type: string, data: unknown): Promise<DBEvent>;
794
+ /** List events with optional filters */
795
+ list(options?: {
796
+ event?: string;
797
+ actor?: string;
798
+ object?: string;
799
+ since?: Date;
800
+ until?: Date;
801
+ limit?: number;
802
+ /** @deprecated Use 'event' instead */
803
+ type?: string;
804
+ }): Promise<DBEvent[]>;
805
+ /** Replay events through a handler */
806
+ replay(options: {
807
+ event?: string;
808
+ actor?: string;
809
+ since?: Date;
810
+ handler: (event: DBEvent) => void | Promise<void>;
811
+ /** @deprecated Use 'event' instead */
812
+ type?: string;
813
+ }): Promise<void>;
814
+ }
815
+ /**
816
+ * Action data structure for durable execution
817
+ *
818
+ * Uses linguistic verb conjugations for semantic clarity:
819
+ * - act: Present tense 3rd person (creates, publishes)
820
+ * - action: Base verb form (create, publish)
821
+ * - activity: Gerund/progressive (creating, publishing)
822
+ *
823
+ * @example
824
+ * ```ts
825
+ * const action: DBAction = {
826
+ * id: '01HGXYZ...',
827
+ * actor: 'user:john',
828
+ * actorData: { name: 'John Doe' },
829
+ * // Verb conjugations
830
+ * act: 'generates', // Present tense: "system generates posts"
831
+ * action: 'generate', // Base form for lookups
832
+ * activity: 'generating', // Progressive: "currently generating posts"
833
+ * // Target
834
+ * object: 'Post',
835
+ * objectData: { count: 100 },
836
+ * // Status
837
+ * status: 'active',
838
+ * progress: 50,
839
+ * total: 100,
840
+ * // Result
841
+ * result: { created: 50 },
842
+ * timestamp: new Date(),
843
+ * }
844
+ * ```
845
+ */
846
+ export interface DBAction {
847
+ /** Unique action ID (ULID recommended) */
848
+ id: string;
849
+ /** Actor identifier (user:id, system, agent:name) */
850
+ actor: string;
851
+ /** Actor metadata */
852
+ actorData?: ActorData;
853
+ /** Present tense 3rd person verb (creates, publishes, generates) */
854
+ act: string;
855
+ /** Base verb form - imperative (create, publish, generate) */
856
+ action: string;
857
+ /** Gerund/progressive form (creating, publishing, generating) */
858
+ activity: string;
859
+ /** Object being acted upon (type name or URL) */
860
+ object?: string;
861
+ /** Object data/parameters for the action */
862
+ objectData?: Record<string, unknown>;
863
+ /** Action status */
864
+ status: 'pending' | 'active' | 'completed' | 'failed' | 'cancelled';
865
+ /** Current progress count */
866
+ progress?: number;
867
+ /** Total items to process */
868
+ total?: number;
869
+ /** Result data on completion */
870
+ result?: Record<string, unknown>;
871
+ /** Error message on failure */
872
+ error?: string;
873
+ /** Additional metadata */
874
+ meta?: Record<string, unknown>;
875
+ /** When the action was created */
876
+ createdAt: Date;
877
+ /** When the action started executing */
878
+ startedAt?: Date;
879
+ /** When the action completed/failed */
880
+ completedAt?: Date;
881
+ /** @deprecated Use 'action' instead */
882
+ type?: string;
883
+ /** @deprecated Use 'objectData' instead */
884
+ data?: unknown;
885
+ }
886
+ /**
887
+ * Options for creating an action
888
+ */
889
+ export interface CreateActionOptions {
890
+ /** Actor identifier */
891
+ actor: string;
892
+ /** Actor metadata */
893
+ actorData?: ActorData;
894
+ /** Base verb (will auto-conjugate to act/activity) */
895
+ action: string;
896
+ /** Object being acted upon */
897
+ object?: string;
898
+ /** Object data/parameters */
899
+ objectData?: Record<string, unknown>;
900
+ /** Total items for progress tracking */
901
+ total?: number;
902
+ /** Additional metadata */
903
+ meta?: Record<string, unknown>;
904
+ /** @deprecated Use 'action' instead */
905
+ type?: string;
906
+ /** @deprecated Use 'objectData' instead */
907
+ data?: unknown;
908
+ }
909
+ /**
910
+ * Actions API for durable execution tracking
911
+ *
912
+ * @example
913
+ * ```ts
914
+ * // Create an action with verb conjugation
915
+ * const action = await actions.create({
916
+ * actor: 'system',
917
+ * action: 'generate', // auto-conjugates to act='generates', activity='generating'
918
+ * object: 'Post',
919
+ * objectData: { count: 100 },
920
+ * total: 100,
921
+ * })
922
+ *
923
+ * // Update progress
924
+ * await actions.update(action.id, { progress: 50 })
925
+ *
926
+ * // Complete with result
927
+ * await actions.update(action.id, {
928
+ * status: 'completed',
929
+ * result: { created: 100 },
930
+ * })
931
+ * ```
932
+ */
933
+ export interface ActionsAPI {
934
+ /** Create a new action (auto-conjugates verb forms) */
935
+ create(options: CreateActionOptions): Promise<DBAction>;
936
+ /** Create with legacy format (deprecated) */
937
+ create(data: {
938
+ type: string;
939
+ data: unknown;
940
+ total?: number;
941
+ }): Promise<DBAction>;
942
+ /** Get an action by ID */
943
+ get(id: string): Promise<DBAction | null>;
944
+ /** Update action progress/status */
945
+ update(id: string, updates: Partial<Pick<DBAction, 'status' | 'progress' | 'result' | 'error'>>): Promise<DBAction>;
946
+ /** List actions with optional filters */
947
+ list(options?: {
948
+ status?: DBAction['status'];
949
+ action?: string;
950
+ actor?: string;
951
+ object?: string;
952
+ since?: Date;
953
+ until?: Date;
954
+ limit?: number;
955
+ /** @deprecated Use 'action' instead */
956
+ type?: string;
957
+ }): Promise<DBAction[]>;
958
+ /** Retry a failed action */
959
+ retry(id: string): Promise<DBAction>;
960
+ /** Cancel a pending/active action */
961
+ cancel(id: string): Promise<void>;
962
+ /** Conjugate a verb to get all forms */
963
+ conjugate(action: string): Verb;
964
+ }
965
+ /**
966
+ * Artifact data structure for cached content
967
+ */
968
+ export interface DBArtifact {
969
+ url: string;
970
+ type: string;
971
+ sourceHash: string;
972
+ content: unknown;
973
+ metadata?: Record<string, unknown>;
974
+ createdAt: Date;
975
+ }
976
+ /**
977
+ * Artifacts API for cached embeddings and computed content
978
+ */
979
+ export interface ArtifactsAPI {
980
+ /** Get an artifact by URL and type */
981
+ get(url: string, type: string): Promise<DBArtifact | null>;
982
+ /** Set an artifact */
983
+ set(url: string, type: string, data: {
984
+ content: unknown;
985
+ sourceHash: string;
986
+ metadata?: Record<string, unknown>;
987
+ }): Promise<void>;
988
+ /** Delete an artifact */
989
+ delete(url: string, type?: string): Promise<void>;
990
+ /** List artifacts for a URL */
991
+ list(url: string): Promise<DBArtifact[]>;
992
+ }
993
+ /**
994
+ * Nouns API for type introspection
995
+ */
996
+ export interface NounsAPI {
997
+ /** Get a noun definition by type name */
998
+ get(name: string): Promise<Noun | null>;
999
+ /** List all noun definitions */
1000
+ list(): Promise<Noun[]>;
1001
+ /** Define a new noun */
1002
+ define(noun: Noun): Promise<void>;
1003
+ }
1004
+ /**
1005
+ * Verbs API for action introspection
1006
+ */
1007
+ export interface VerbsAPI {
1008
+ /** Get a verb definition by action name */
1009
+ get(action: string): Verb | null;
1010
+ /** List all verb definitions */
1011
+ list(): Verb[];
1012
+ /** Define a new verb */
1013
+ define(verb: Verb): void;
1014
+ /** Conjugate a verb from base form */
1015
+ conjugate(action: string): Verb;
1016
+ }
1017
+ /**
1018
+ * Result of DB() factory - supports both direct and destructured usage
1019
+ *
1020
+ * @example
1021
+ * ```ts
1022
+ * // Direct usage - everything on one object
1023
+ * const db = DB(schema)
1024
+ * db.User.create(...) // entity operations
1025
+ * db.events.on(...) // events API
1026
+ * db.actions.create(...) // actions API
1027
+ *
1028
+ * // Destructured usage - cleaner separation
1029
+ * const { db, events, actions } = DB(schema)
1030
+ * db.User.create(...) // just entity ops
1031
+ * events.on(...) // separate events
1032
+ * ```
1033
+ */
1034
+ export type DBResult<TSchema extends DatabaseSchema> = TypedDB<TSchema> & {
1035
+ /** Self-reference for destructuring - same as the parent object but cleaner semantically */
1036
+ db: TypedDB<TSchema>;
1037
+ /** Event subscription and emission */
1038
+ events: EventsAPI;
1039
+ /** Durable action execution */
1040
+ actions: ActionsAPI;
1041
+ /** Cached embeddings and computed content */
1042
+ artifacts: ArtifactsAPI;
1043
+ /** Type introspection */
1044
+ nouns: NounsAPI;
1045
+ /** Action introspection */
1046
+ verbs: VerbsAPI;
1047
+ /** EventBridge for Cloudflare Queues integration */
1048
+ eventBridge: EventBridgeAPI;
1049
+ };
1050
+ /**
1051
+ * Set the AI generator for natural language queries
1052
+ *
1053
+ * @example
1054
+ * ```ts
1055
+ * import { generate } from 'ai-functions'
1056
+ *
1057
+ * setNLQueryGenerator(async (prompt, context) => {
1058
+ * return generate({
1059
+ * prompt: `Given this schema: ${JSON.stringify(context.types)}
1060
+ * Answer this question: ${prompt}
1061
+ * Return a query plan as JSON.`,
1062
+ * schema: NLQueryPlanSchema
1063
+ * })
1064
+ * })
1065
+ * ```
1066
+ */
1067
+ export declare function setNLQueryGenerator(generator: NLQueryGenerator): void;
1068
+ /**
1069
+ * Get the currently configured NL query generator
1070
+ */
1071
+ export declare function getNLQueryGenerator(): NLQueryGenerator | null;
1072
+ /**
1073
+ * Build schema context for NL queries
1074
+ */
1075
+ export declare function buildNLQueryContext(schema: ParsedSchema, targetType?: string): NLQueryContext;
1076
+ /**
1077
+ * Execute a natural language query
1078
+ */
1079
+ export declare function executeNLQuery<T>(question: string, schema: ParsedSchema, targetType?: string): Promise<NLQueryResult<T>>;
1080
+ /**
1081
+ * Create a natural language query function for a specific type
1082
+ */
1083
+ export declare function createNLQueryFn<T>(schema: ParsedSchema, typeName?: string): NLQueryFn<T>;
1084
+ /**
1085
+ * Set the global database provider
1086
+ */
1087
+ export declare function setProvider(provider: DBProvider): void;
1088
+ /**
1089
+ * Create a typed database from a schema definition
1090
+ *
1091
+ * Supports both direct usage and destructuring for flexibility:
1092
+ *
1093
+ * @example Direct usage - everything on one object
1094
+ * ```ts
1095
+ * const db = DB({
1096
+ * Post: { title: 'string', author: 'Author.posts' },
1097
+ * Author: { name: 'string' },
1098
+ * })
1099
+ *
1100
+ * // Entity operations
1101
+ * const post = await db.Post.create({ title: 'Hello' })
1102
+ *
1103
+ * // Events, actions, etc. are also available directly
1104
+ * db.events.on('Post.created', (event) => console.log(event))
1105
+ * db.actions.create({ type: 'generate', data: {} })
1106
+ * ```
1107
+ *
1108
+ * @example Destructured usage - cleaner separation
1109
+ * ```ts
1110
+ * const { db, events, actions, artifacts, nouns, verbs } = DB({
1111
+ * Post: { title: 'string', author: 'Author.posts' },
1112
+ * Author: { name: 'string' },
1113
+ * })
1114
+ *
1115
+ * // CRUD operations on db
1116
+ * const post = await db.Post.create({ title: 'Hello' })
1117
+ * await db.Post.update(post.$id, { title: 'Updated' })
1118
+ *
1119
+ * // Separate events API
1120
+ * events.on('Post.created', (event) => console.log(event))
1121
+ *
1122
+ * // Separate actions API
1123
+ * const action = await actions.create({ type: 'generate', data: {} })
1124
+ * ```
1125
+ */
1126
+ export declare function DB<TSchema extends DatabaseSchema>(schema: TSchema, options?: DBOptions): DBResult<TSchema>;
1127
+ export { parseSchema as parse };
57
1128
  //# sourceMappingURL=schema.d.ts.map