ai-database 0.0.0-development → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,462 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DB: () => DB,
24
+ calculateSimilarity: () => calculateSimilarity,
25
+ createEdgeClient: () => createEdgeClient,
26
+ createNodeClient: () => createNodeClient,
27
+ db: () => db,
28
+ default: () => index_default,
29
+ generateEmbedding: () => generateEmbedding
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/utils.ts
34
+ var handleError = (error, operation, collection) => {
35
+ const errorMessage = error.message || "Unknown error";
36
+ const statusCode = error.status || error.statusCode || 500;
37
+ const enhancedError = new Error(`${operation} operation failed on collection '${collection}': ${errorMessage}`);
38
+ Object.assign(enhancedError, {
39
+ statusCode,
40
+ operation,
41
+ collection,
42
+ originalError: error
43
+ });
44
+ throw enhancedError;
45
+ };
46
+ var transformQueryOptions = (options = {}) => {
47
+ const result = {};
48
+ if (options.where) {
49
+ result.where = options.where;
50
+ }
51
+ if (options.sort) {
52
+ if (Array.isArray(options.sort)) {
53
+ result.sort = options.sort.join(",");
54
+ } else {
55
+ result.sort = options.sort;
56
+ }
57
+ }
58
+ if (options.limit) {
59
+ result.limit = options.limit;
60
+ }
61
+ if (options.page) {
62
+ result.page = options.page;
63
+ }
64
+ if (options.select) {
65
+ if (Array.isArray(options.select)) {
66
+ result.fields = options.select;
67
+ } else {
68
+ result.fields = [options.select];
69
+ }
70
+ }
71
+ if (options.populate) {
72
+ if (typeof options.populate === "string") {
73
+ result.depth = 1;
74
+ } else if (Array.isArray(options.populate) && options.populate.length > 0) {
75
+ result.depth = 1;
76
+ }
77
+ }
78
+ return result;
79
+ };
80
+ var getPayloadInstance = (options) => {
81
+ if (options.payload) {
82
+ return options.payload;
83
+ }
84
+ if (options.apiUrl) {
85
+ const restConfig = {
86
+ apiUrl: options.apiUrl,
87
+ apiKey: options.apiKey,
88
+ headers: options.headers,
89
+ fetchOptions: options.fetchOptions
90
+ };
91
+ return createRestClient(restConfig);
92
+ }
93
+ try {
94
+ if (typeof global !== "undefined" && global.payload) {
95
+ return global.payload;
96
+ }
97
+ } catch (e) {
98
+ }
99
+ throw new Error("No Payload instance provided. Please provide a payload instance or apiUrl.");
100
+ };
101
+ var createRestClient = (config) => {
102
+ const { apiUrl, apiKey, headers = {}, fetchOptions = {} } = config;
103
+ const requestHeaders = {
104
+ "Content-Type": "application/json",
105
+ ...headers
106
+ };
107
+ if (apiKey) {
108
+ requestHeaders["Authorization"] = `Bearer ${apiKey}`;
109
+ }
110
+ return {
111
+ find: async (options) => {
112
+ const { collection, ...params } = options;
113
+ const searchParams = new URLSearchParams();
114
+ Object.entries(params).forEach(([key, value]) => {
115
+ if (typeof value === "object") {
116
+ searchParams.append(key, JSON.stringify(value));
117
+ } else {
118
+ searchParams.append(key, String(value));
119
+ }
120
+ });
121
+ const url = `${apiUrl}/${collection}?${searchParams.toString()}`;
122
+ const response = await fetch(url, {
123
+ method: "GET",
124
+ headers: requestHeaders,
125
+ ...fetchOptions
126
+ });
127
+ if (!response.ok) {
128
+ const error = await response.json();
129
+ throw new Error(error.message || `Failed to fetch from ${collection}`);
130
+ }
131
+ return response.json();
132
+ },
133
+ findByID: async (options) => {
134
+ const { collection, id, ...params } = options;
135
+ const searchParams = new URLSearchParams();
136
+ Object.entries(params).forEach(([key, value]) => {
137
+ if (typeof value === "object") {
138
+ searchParams.append(key, JSON.stringify(value));
139
+ } else {
140
+ searchParams.append(key, String(value));
141
+ }
142
+ });
143
+ const url = `${apiUrl}/${collection}/${id}?${searchParams.toString()}`;
144
+ const response = await fetch(url, {
145
+ method: "GET",
146
+ headers: requestHeaders,
147
+ ...fetchOptions
148
+ });
149
+ if (!response.ok) {
150
+ const error = await response.json();
151
+ throw new Error(error.message || `Failed to fetch ${id} from ${collection}`);
152
+ }
153
+ return response.json();
154
+ },
155
+ create: async (options) => {
156
+ const { collection, data } = options;
157
+ const url = `${apiUrl}/${collection}`;
158
+ const response = await fetch(url, {
159
+ method: "POST",
160
+ headers: requestHeaders,
161
+ body: JSON.stringify(data),
162
+ ...fetchOptions
163
+ });
164
+ if (!response.ok) {
165
+ const error = await response.json();
166
+ throw new Error(error.message || `Failed to create document in ${collection}`);
167
+ }
168
+ return response.json();
169
+ },
170
+ update: async (options) => {
171
+ const { collection, id, data } = options;
172
+ const url = `${apiUrl}/${collection}/${id}`;
173
+ const response = await fetch(url, {
174
+ method: "PATCH",
175
+ headers: requestHeaders,
176
+ body: JSON.stringify(data),
177
+ ...fetchOptions
178
+ });
179
+ if (!response.ok) {
180
+ const error = await response.json();
181
+ throw new Error(error.message || `Failed to update document ${id} in ${collection}`);
182
+ }
183
+ return response.json();
184
+ },
185
+ delete: async (options) => {
186
+ const { collection, id } = options;
187
+ const url = `${apiUrl}/${collection}/${id}`;
188
+ const response = await fetch(url, {
189
+ method: "DELETE",
190
+ headers: requestHeaders,
191
+ ...fetchOptions
192
+ });
193
+ if (!response.ok) {
194
+ const error = await response.json();
195
+ throw new Error(error.message || `Failed to delete document ${id} from ${collection}`);
196
+ }
197
+ return response.json();
198
+ }
199
+ };
200
+ };
201
+
202
+ // src/collectionHandler.ts
203
+ var CollectionHandler = class {
204
+ payload;
205
+ collection;
206
+ /**
207
+ * Creates a new collection handler
208
+ * @param options Collection handler options
209
+ */
210
+ constructor(options) {
211
+ this.payload = options.payload;
212
+ this.collection = options.collectionName;
213
+ }
214
+ /**
215
+ * Find documents in the collection
216
+ * @template T Type of documents to return
217
+ * @param options Query options including filtering, sorting, and pagination
218
+ * @returns Promise resolving to a list of documents
219
+ */
220
+ async find(options = {}) {
221
+ try {
222
+ const transformedOptions = transformQueryOptions(options);
223
+ const result = await this.payload.find({
224
+ collection: this.collection,
225
+ ...transformedOptions
226
+ });
227
+ return {
228
+ docs: result.docs || [],
229
+ totalDocs: result.totalDocs || 0,
230
+ page: result.page || 1,
231
+ totalPages: result.totalPages || 1,
232
+ limit: result.limit || 10,
233
+ hasPrevPage: result.hasPrevPage || false,
234
+ hasNextPage: result.hasNextPage || false,
235
+ prevPage: result.prevPage || null,
236
+ nextPage: result.nextPage || null
237
+ };
238
+ } catch (error) {
239
+ return handleError(error, "find", this.collection);
240
+ }
241
+ }
242
+ /**
243
+ * Find a single document by ID
244
+ * @template T Type of document to return
245
+ * @param id Document ID
246
+ * @returns Promise resolving to a single document
247
+ */
248
+ async findOne(id) {
249
+ try {
250
+ return await this.payload.findByID({
251
+ collection: this.collection,
252
+ id
253
+ });
254
+ } catch (error) {
255
+ return handleError(error, "findOne", this.collection);
256
+ }
257
+ }
258
+ /**
259
+ * Create a new document in the collection
260
+ * @template T Type of document to create
261
+ * @param data Document data
262
+ * @returns Promise resolving to the created document
263
+ */
264
+ async create(data) {
265
+ try {
266
+ return await this.payload.create({
267
+ collection: this.collection,
268
+ data
269
+ });
270
+ } catch (error) {
271
+ return handleError(error, "create", this.collection);
272
+ }
273
+ }
274
+ /**
275
+ * Update an existing document
276
+ * @template T Type of document to update
277
+ * @param id Document ID
278
+ * @param data Updated document data
279
+ * @returns Promise resolving to the updated document
280
+ */
281
+ async update(id, data) {
282
+ try {
283
+ return await this.payload.update({
284
+ collection: this.collection,
285
+ id,
286
+ data
287
+ });
288
+ } catch (error) {
289
+ return handleError(error, "update", this.collection);
290
+ }
291
+ }
292
+ /**
293
+ * Delete a document
294
+ * @template T Type of deleted document
295
+ * @param id Document ID
296
+ * @returns Promise resolving to the deleted document
297
+ */
298
+ async delete(id) {
299
+ try {
300
+ return await this.payload.delete({
301
+ collection: this.collection,
302
+ id
303
+ });
304
+ } catch (error) {
305
+ return handleError(error, "delete", this.collection);
306
+ }
307
+ }
308
+ /**
309
+ * Search for documents
310
+ * @template T Type of documents to search
311
+ * @param query Search query string
312
+ * @param options Query options
313
+ * @returns Promise resolving to a list of matching documents
314
+ */
315
+ async search(query, options = {}) {
316
+ try {
317
+ const transformedOptions = transformQueryOptions(options);
318
+ if (typeof this.payload.search === "function") {
319
+ const result2 = await this.payload.search({
320
+ collection: this.collection,
321
+ query,
322
+ ...transformedOptions
323
+ });
324
+ return {
325
+ docs: result2.docs || [],
326
+ totalDocs: result2.totalDocs || 0,
327
+ page: result2.page || 1,
328
+ totalPages: result2.totalPages || 1,
329
+ limit: result2.limit || 10,
330
+ hasPrevPage: result2.hasPrevPage || false,
331
+ hasNextPage: result2.hasNextPage || false,
332
+ prevPage: result2.prevPage || null,
333
+ nextPage: result2.nextPage || null
334
+ };
335
+ }
336
+ const result = await this.payload.find({
337
+ collection: this.collection,
338
+ search: query,
339
+ ...transformedOptions
340
+ });
341
+ return {
342
+ docs: result.docs || [],
343
+ totalDocs: result.totalDocs || 0,
344
+ page: result.page || 1,
345
+ totalPages: result.totalPages || 1,
346
+ limit: result.limit || 10,
347
+ hasPrevPage: result.hasPrevPage || false,
348
+ hasNextPage: result.hasNextPage || false,
349
+ prevPage: result.prevPage || null,
350
+ nextPage: result.nextPage || null
351
+ };
352
+ } catch (error) {
353
+ return handleError(error, "search", this.collection);
354
+ }
355
+ }
356
+ };
357
+
358
+ // src/adapters/node.ts
359
+ var createNodeClient = (options = {}) => {
360
+ return DB(options);
361
+ };
362
+
363
+ // src/adapters/edge.ts
364
+ var createEdgeClient = (options = {}) => {
365
+ if (!options.apiUrl) {
366
+ throw new Error("apiUrl is required for Edge environments");
367
+ }
368
+ return DB(options);
369
+ };
370
+
371
+ // src/embedding.ts
372
+ async function generateEmbedding(text, options = {}) {
373
+ try {
374
+ const modelName = options.model || "text-embedding-3-small";
375
+ const apiKey = options.apiKey || typeof globalThis !== "undefined" && globalThis.process?.env?.OPENAI_API_KEY;
376
+ if (!apiKey) {
377
+ throw new Error("apiKey option or OPENAI_API_KEY environment variable is required for embedding generation");
378
+ }
379
+ const input = Array.isArray(text) ? text : [text];
380
+ const response = await fetch("https://api.openai.com/v1/embeddings", {
381
+ method: "POST",
382
+ headers: {
383
+ "Content-Type": "application/json",
384
+ Authorization: `Bearer ${apiKey}`
385
+ },
386
+ body: JSON.stringify({
387
+ input,
388
+ model: modelName
389
+ })
390
+ });
391
+ if (!response.ok) {
392
+ const errorData = await response.json().catch(() => ({}));
393
+ throw new Error(`OpenAI API error: ${errorData.error?.message || response.statusText}`);
394
+ }
395
+ const data = await response.json();
396
+ const embeddings = [];
397
+ if (data && data.data && Array.isArray(data.data)) {
398
+ for (const item of data.data) {
399
+ if (item && item.embedding && Array.isArray(item.embedding)) {
400
+ embeddings.push(item.embedding);
401
+ }
402
+ }
403
+ }
404
+ return {
405
+ embedding: embeddings.length > 0 ? embeddings : null,
406
+ model: modelName,
407
+ success: embeddings.length > 0
408
+ };
409
+ } catch (error) {
410
+ console.error("Error generating embedding:", error);
411
+ return {
412
+ embedding: null,
413
+ model: options.model || "text-embedding-3-small",
414
+ success: false,
415
+ error: error instanceof Error ? error.message : String(error)
416
+ };
417
+ }
418
+ }
419
+ function calculateSimilarity(embedding1, embedding2) {
420
+ if (embedding1.length !== embedding2.length) {
421
+ throw new Error("Embeddings must have the same dimensions");
422
+ }
423
+ let dotProduct = 0;
424
+ let magnitude1 = 0;
425
+ let magnitude2 = 0;
426
+ for (let i = 0; i < embedding1.length; i++) {
427
+ dotProduct += embedding1[i] * embedding2[i];
428
+ magnitude1 += embedding1[i] * embedding1[i];
429
+ magnitude2 += embedding2[i] * embedding2[i];
430
+ }
431
+ magnitude1 = Math.sqrt(magnitude1);
432
+ magnitude2 = Math.sqrt(magnitude2);
433
+ if (magnitude1 === 0 || magnitude2 === 0) {
434
+ return 0;
435
+ }
436
+ return dotProduct / (magnitude1 * magnitude2);
437
+ }
438
+
439
+ // src/index.ts
440
+ var DB = (options = {}) => {
441
+ const payload = getPayloadInstance(options);
442
+ return new Proxy({}, {
443
+ get: (target, prop) => {
444
+ if (typeof prop === "string" && prop !== "then") {
445
+ const collectionName = prop === "resources" ? "things" : String(prop);
446
+ return new CollectionHandler({ payload, collectionName });
447
+ }
448
+ return target[prop];
449
+ }
450
+ });
451
+ };
452
+ var db = DB();
453
+ var index_default = DB;
454
+ // Annotate the CommonJS export names for ESM import in node:
455
+ 0 && (module.exports = {
456
+ DB,
457
+ calculateSimilarity,
458
+ createEdgeClient,
459
+ createNodeClient,
460
+ db,
461
+ generateEmbedding
462
+ });