ai-database 0.1.0 → 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 (72) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/.turbo/turbo-test.log +102 -0
  3. package/README.md +381 -68
  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 +50 -191
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +79 -462
  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 -37
  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/dist/index.d.mts +0 -195
  72. package/dist/index.mjs +0 -430
package/dist/index.d.ts CHANGED
@@ -1,195 +1,54 @@
1
- import { ListResponse } from 'apis.do/types';
2
- export { ClientOptions, ErrorResponse, ListResponse, QueryParams } from 'apis.do/types';
3
-
4
1
  /**
5
- * Types for ai-database package
6
- */
7
-
8
- /**
9
- * Options for embedding generation
10
- */
11
- interface EmbeddingOptions {
12
- /** Embedding model to use (defaults to openai:text-embedding-3-small) */
13
- model?: string;
14
- /** Additional options for the embedding model */
15
- [key: string]: any;
16
- }
17
- /**
18
- * Result of embedding generation
19
- */
20
- interface EmbeddingResult {
21
- /** Generated embedding vectors */
22
- embedding: number[][] | null;
23
- /** Model used for embedding generation */
24
- model: string;
25
- /** Whether the embedding generation was successful */
26
- success: boolean;
27
- /** Error message if embedding generation failed */
28
- error?: string;
29
- }
30
- /**
31
- * Generic collection data type
32
- */
33
- type CollectionData = Record<string, any>;
34
- /**
35
- * Query options for database operations
36
- */
37
- interface QueryOptions {
38
- /** Filter criteria */
39
- where?: Record<string, any>;
40
- /** Sorting options (field:direction) */
41
- sort?: string | string[];
42
- /** Number of results per page */
43
- limit?: number;
44
- /** Page number for pagination */
45
- page?: number;
46
- /** Fields to include in the result */
47
- select?: string | string[];
48
- /** Relations to populate */
49
- populate?: string | string[];
50
- }
51
- /**
52
- * Methods available for each collection
53
- * @template T Document type for the collection
54
- */
55
- interface CollectionMethods<T = CollectionData> {
56
- /** Find documents in the collection */
57
- find: (options?: QueryOptions) => Promise<ListResponse<T>>;
58
- /** Find a single document by ID */
59
- findOne: (id: string) => Promise<T>;
60
- /** Create a new document */
61
- create: (data: Partial<T>) => Promise<T>;
62
- /** Update an existing document */
63
- update: (id: string, data: Partial<T>) => Promise<T>;
64
- /** Delete a document */
65
- delete: (id: string) => Promise<T>;
66
- /** Search for documents */
67
- search: (query: string, options?: QueryOptions) => Promise<ListResponse<T>>;
68
- }
69
- /**
70
- * Database client interface
71
- */
72
- interface DatabaseClientType {
73
- /** Dynamic access to any collection */
74
- [collection: string]: CollectionMethods;
75
- }
76
- /**
77
- * Payload instance interface defining the minimum required methods
78
- */
79
- interface PayloadInstance {
80
- find?: (options: any) => Promise<any>;
81
- findByID?: (options: any) => Promise<any>;
82
- create?: (options: any) => Promise<any>;
83
- update?: (options: any) => Promise<any>;
84
- delete?: (options: any) => Promise<any>;
85
- db?: any;
86
- [key: string]: any;
87
- }
88
- /**
89
- * Configuration for REST API-based Payload client
90
- */
91
- interface RestClientConfig {
92
- apiUrl: string;
93
- apiKey?: string;
94
- headers?: Record<string, string>;
95
- fetchOptions?: RequestInit;
96
- }
97
- /**
98
- * Options for DB initialization
99
- */
100
- interface DBOptions {
101
- baseUrl?: string;
102
- apiKey?: string;
103
- payload?: PayloadInstance;
104
- apiUrl?: string;
105
- headers?: Record<string, string>;
106
- fetchOptions?: RequestInit;
107
- [collection: string]: any;
108
- }
109
- /**
110
- * Collection handler options
111
- */
112
- interface CollectionHandlerOptions {
113
- payload: PayloadInstance;
114
- collectionName: string;
115
- }
116
-
117
- /**
118
- * Node.js adapter for ai-database
119
- */
120
-
121
- /**
122
- * Creates a database client for Node.js environments
123
- * @param options Configuration options
124
- * @returns Database client instance
125
- * @example
126
- * import { getPayload } from 'payload'
127
- * import config from '@payload-config'
128
- * import { createNodeClient } from 'ai-database/adapters'
2
+ * ai-database - Schema-first database with promise pipelining
129
3
  *
130
- * const payload = await getPayload({ config })
131
- * const db = createNodeClient({ payload })
132
- */
133
- declare const createNodeClient: (options?: DBOptions) => DatabaseClientType;
134
-
135
- /**
136
- * Edge runtime adapter for ai-database
137
- */
138
-
139
- /**
140
- * Creates a database client for Edge runtime environments
141
- * @param options Configuration options (must include apiUrl)
142
- * @returns Database client instance
143
- * @example
144
- * import { createEdgeClient } from 'ai-database/adapters'
4
+ * Supports both direct and destructured usage:
145
5
  *
146
- * const db = createEdgeClient({
147
- * apiUrl: 'https://your-payload-api.com/api',
148
- * apiKey: 'your-api-key'
6
+ * @example Direct usage - everything on one object
7
+ * ```ts
8
+ * const { db } = DB({
9
+ * Lead: {
10
+ * name: 'string',
11
+ * company: 'Company.leads',
12
+ * },
13
+ * Company: {
14
+ * name: 'string',
15
+ * }
149
16
  * })
150
- */
151
- declare const createEdgeClient: (options?: DBOptions) => DatabaseClientType;
152
-
153
- /**
154
- * Embedding functionality for ai-database
155
- * Uses OpenAI API directly for generating embeddings
156
- */
157
-
158
- /**
159
- * Generate embeddings for text using OpenAI API
160
- * @param text Text to generate embeddings for
161
- * @param options Embedding options
162
- * @returns Promise resolving to embedding result
163
- */
164
- declare function generateEmbedding(text: string | string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
165
- /**
166
- * Calculate cosine similarity between two embeddings
167
- * @param embedding1 First embedding vector
168
- * @param embedding2 Second embedding vector
169
- * @returns Cosine similarity score (0-1)
170
- */
171
- declare function calculateSimilarity(embedding1: number[], embedding2: number[]): number;
172
-
173
- /**
174
- * ai-database
175
- * Direct interface to Payload CMS with database.do compatibility
176
- */
177
-
178
- /**
179
- * Creates a database client with the provided options
180
- * @param options Configuration options for the database client
181
- * @returns A proxy-based database client that provides collection-based access
182
- * @example
183
- * const db = DB({ payload }) // Node.js with Payload instance
184
- * const db = DB({ apiUrl: 'https://api.example.com' }) // Edge with REST API
185
- */
186
- declare const DB: (options?: DBOptions) => DatabaseClientType;
187
- /**
188
- * Default database client instance
189
- * Note: This will attempt to use a global Payload instance if available,
190
- * otherwise it will throw an error. In most cases, you should use the DB
191
- * function directly with explicit options.
192
- */
193
- declare const db: DatabaseClientType;
194
-
195
- export { type CollectionData, type CollectionHandlerOptions, type CollectionMethods, DB, type DBOptions, type DatabaseClientType, type EmbeddingOptions, type EmbeddingResult, type PayloadInstance, type QueryOptions, type RestClientConfig, calculateSimilarity, createEdgeClient, createNodeClient, db, DB as default, generateEmbedding };
17
+ *
18
+ * // Chain without await
19
+ * const leads = db.Lead.list()
20
+ * const qualified = await leads.filter(l => l.score > 80)
21
+ *
22
+ * // Batch relationship loading
23
+ * const withCompanies = await leads.map(l => ({
24
+ * name: l.name,
25
+ * company: l.company, // Batch loaded!
26
+ * }))
27
+ *
28
+ * // Natural language queries
29
+ * const results = await db.Lead`who closed deals this month?`
30
+ * ```
31
+ *
32
+ * Provider is resolved transparently from environment (DATABASE_URL).
33
+ *
34
+ * @packageDocumentation
35
+ */
36
+ export { DB } from './schema.js';
37
+ export type { ThingFlat, ThingExpanded, DatabaseSchema, EntitySchema, FieldDefinition, PrimitiveType, ParsedSchema, ParsedEntity, ParsedField, TypedDB, EntityOperations, PipelineEntityOperations, DBProvider, ListOptions, SearchOptions, InferEntity, GenerateOptions, DBResult, Noun, NounProperty, NounRelationship, Verb, TypeMeta, EventsAPI, ActionsAPI, ArtifactsAPI, NounsAPI, VerbsAPI, DBEvent, ActorData, CreateEventOptions as DBCreateEventOptions, DBAction, CreateActionOptions as DBCreateActionOptions, DBArtifact, NLQueryResult, NLQueryFn, NLQueryGenerator, NLQueryContext, NLQueryPlan, EntityId, Thing, Relationship, QueryOptions, ThingSearchOptions, CreateOptions, UpdateOptions, RelateOptions, StoreArtifactOptions, EventQueryOptions, ActionQueryOptions, ActionStatus, ArtifactType, DBClient, DBClientExtended, } from './schema.js';
38
+ export type { CreateEventOptions, CreateActionOptions, } from './types.js';
39
+ export { toExpanded, toFlat, setProvider, setNLQueryGenerator, parseSchema, defineNoun, defineVerb, nounToSchema, Verbs, conjugate, pluralize, singularize, inferNoun, Type, resolveUrl, resolveShortUrl, parseUrl, } from './schema.js';
40
+ export { MemoryProvider, createMemoryProvider, Semaphore, } from './memory-provider.js';
41
+ export type { Event as MemoryEvent, Action as MemoryAction, Artifact as MemoryArtifact, MemoryProviderOptions, } from './memory-provider.js';
42
+ export type { Event, Action, Artifact } from './schema.js';
43
+ export { DBPromise, isDBPromise, getRawDBPromise, createListPromise, createEntityPromise, createSearchPromise, wrapEntityOperations, DB_PROMISE_SYMBOL, RAW_DB_PROMISE_SYMBOL, } from './ai-promise-db.js';
44
+ export type { DBPromiseOptions, ForEachOptions, ForEachResult, ForEachProgress, ForEachErrorAction, } from './ai-promise-db.js';
45
+ export type { Subject, SubjectType, Resource, ResourceRef, ResourceType, Permission, Role, RoleLevel, Assignment, AssignmentInput, AuthzCheckRequest, AuthzCheckResult, AuthzBatchCheckRequest, AuthzBatchCheckResult, ResourceHierarchy, AuthorizedNoun, BusinessRole, AuthorizationEngine, } from './authorization.js';
46
+ export { StandardHierarchies, StandardPermissions, CRUDPermissions, createStandardRoles, verbPermission, nounPermissions, matchesPermission, parseSubject, formatSubject, parseResource, formatResource, subjectMatches, resourceMatches, authorizeNoun, linkBusinessRole, InMemoryAuthorizationEngine, RoleNoun, AssignmentNoun, PermissionNoun, AuthorizationNouns, } from './authorization.js';
47
+ export type { Document, DocWithScore, DocListOptions, DocListResult, DocSearchOptions, DocSearchResult, DocGetOptions, DocSetOptions, DocSetResult, DocDeleteOptions, DocDeleteResult, DocumentDatabase, DocumentDatabaseConfig, CreateDocumentDatabase, DocumentDatabaseWithViews, ViewEntityItem, ViewComponent, ViewDocument, ViewContext, ViewRenderResult, ViewRelationshipMutation, ViewSyncResult, ViewManager, } from './types.js';
48
+ export { DurablePromise, isDurablePromise, durable, DURABLE_PROMISE_SYMBOL, getCurrentContext, withContext, setDefaultContext, getBatchScheduler, setBatchScheduler, } from './durable-promise.js';
49
+ export type { ExecutionPriority, DurablePromiseOptions, DurablePromiseResult, BatchScheduler, } from './durable-promise.js';
50
+ export { ExecutionQueue, createExecutionQueue, getDefaultQueue, setDefaultQueue, } from './execution-queue.js';
51
+ export type { ExecutionQueueOptions, QueueStats, BatchSubmission, BatchProvider, BatchRequest, BatchStatus, BatchResult, } from './execution-queue.js';
52
+ export { ClickHouseDurableProvider, createClickHouseDurableProvider, } from './durable-clickhouse.js';
53
+ export type { ClickHouseExecutor, ClickHouseDurableConfig, } from './durable-clickhouse.js';
54
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAA;AAChC,YAAY,EAEV,SAAS,EACT,aAAa,EAEb,cAAc,EACd,YAAY,EACZ,eAAe,EACf,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,OAAO,EACP,gBAAgB,EAChB,wBAAwB,EACxB,UAAU,EACV,WAAW,EACX,aAAa,EACb,WAAW,EACX,eAAe,EAEf,QAAQ,EAER,IAAI,EACJ,YAAY,EACZ,gBAAgB,EAChB,IAAI,EACJ,QAAQ,EAER,SAAS,EACT,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,QAAQ,EAER,OAAO,EACP,SAAS,EACT,kBAAkB,IAAI,oBAA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