@speeq/store-mongodb 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 speeq contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @speeq/store-mongodb
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A MongoDB `ConversationStore` for [speeq](../../../README.md). It **reuses your app's existing
4
+ connection**, so speeq keeps the audit log and conversation history in your own database, next
5
+ to your data.
6
+
7
+ ```bash
8
+ pnpm add @speeq/store-mongodb@next mongodb
9
+ ```
10
+
11
+ `mongodb` (v6 or later) is a peer dependency, so the store uses the driver you already have.
12
+
13
+ ```ts
14
+ import { createMongoStore } from "@speeq/store-mongodb";
15
+ import clientPromise from "@/lib/mongodb"; // your existing cached MongoClient
16
+
17
+ export const store = createMongoStore({
18
+ db: async () => (await clientPromise).db(), // Db | Promise<Db> | () => Db | Promise<Db>
19
+ });
20
+ ```
21
+
22
+ ## Collections and indexes
23
+
24
+ | Collection | Contents | Indexes (created on first use) |
25
+ | ---------------- | ----------------------------------------------- | ------------------------------------------------------------------ |
26
+ | `speeq_sessions` | one document per session, with summary counters | `userId+startedAt`, `startedAt+_id`, `lastEventAt` |
27
+ | `speeq_events` | one document per audit event | unique `sessionId+seq`, unique partial `sessionId+dedupeKey`, `ts` |
28
+
29
+ Change the prefix with `collectionPrefix`. Pass `ensureIndexes: false` if you manage indexes in
30
+ migrations.
31
+
32
+ ## Guarantees
33
+
34
+ - `seq` numbers are reserved atomically (`$inc`), so concurrent serverless requests never collide.
35
+ - Each confirmation can be resolved only once: the unique `dedupeKey` index makes a replay or race
36
+ fail with `CONFLICT`.
37
+ - A failed batch is rolled back, so `appendEvents` is all-or-nothing.
38
+ - `deleteOlderThan` removes old sessions and their events in batches of 500.
39
+
40
+ No transactions are required, so it works on standalone servers, replica sets and Atlas free tier
41
+ (M0). Tested against a real `mongod` with `mongodb-memory-server` and the shared store contract.
42
+
43
+ [Related guide or reference](../../../docs/guides/stores.md)
package/dist/index.cjs ADDED
@@ -0,0 +1,214 @@
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 src_exports = {};
22
+ __export(src_exports, {
23
+ MongoStore: () => MongoStore,
24
+ createMongoStore: () => createMongoStore
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+ var import_core = require("@speeq/core");
28
+ var DUPLICATE_KEY = 11e3;
29
+ function isDuplicateKey(error) {
30
+ if (typeof error !== "object" || error === null) return false;
31
+ const e = error;
32
+ return e.code === DUPLICATE_KEY || (e.writeErrors ?? []).some((w) => w.code === DUPLICATE_KEY);
33
+ }
34
+ function toSummary(doc) {
35
+ const { _id, nextSeq: _seq, ...rest } = doc;
36
+ return { id: _id, ...rest };
37
+ }
38
+ function toEvent(doc) {
39
+ const { _id, ...rest } = doc;
40
+ return { id: _id, ...rest };
41
+ }
42
+ function counterDelta(events) {
43
+ const inc = {
44
+ eventCount: events.length,
45
+ turnCount: 0,
46
+ toolCallCount: 0,
47
+ navigationCount: 0,
48
+ errorCount: 0
49
+ };
50
+ for (const e of events) {
51
+ if (e.type === "user.message") inc.turnCount += 1;
52
+ else if (e.type === "tool.called") inc.toolCallCount += 1;
53
+ else if (e.type === "navigation") inc.navigationCount += 1;
54
+ else if (e.type === "error") inc.errorCount += 1;
55
+ }
56
+ return inc;
57
+ }
58
+ var MongoStore = class {
59
+ constructor(options) {
60
+ this.options = options;
61
+ }
62
+ options;
63
+ kind = "mongodb";
64
+ ready = null;
65
+ collections() {
66
+ this.ready ??= (async () => {
67
+ const source = this.options.db;
68
+ const db = await (typeof source === "function" ? source() : source);
69
+ const prefix = this.options.collectionPrefix ?? "speeq_";
70
+ const sessions = db.collection(`${prefix}sessions`);
71
+ const events = db.collection(`${prefix}events`);
72
+ if (this.options.ensureIndexes !== false) {
73
+ await Promise.all([
74
+ events.createIndex({ sessionId: 1, seq: 1 }, { unique: true, name: "session_seq" }),
75
+ events.createIndex(
76
+ { sessionId: 1, dedupeKey: 1 },
77
+ {
78
+ unique: true,
79
+ name: "session_dedupe",
80
+ partialFilterExpression: { dedupeKey: { $type: "string" } }
81
+ }
82
+ ),
83
+ events.createIndex({ ts: 1 }, { name: "ts" }),
84
+ sessions.createIndex({ userId: 1, startedAt: -1 }, { name: "user_started" }),
85
+ sessions.createIndex({ startedAt: -1, _id: -1 }, { name: "started" }),
86
+ sessions.createIndex({ lastEventAt: 1 }, { name: "last_event" })
87
+ ]);
88
+ }
89
+ return { sessions, events };
90
+ })().catch((error) => {
91
+ this.ready = null;
92
+ throw error;
93
+ });
94
+ return this.ready;
95
+ }
96
+ async createSession(session) {
97
+ const { sessions } = await this.collections();
98
+ try {
99
+ await sessions.insertOne({
100
+ _id: session.id,
101
+ userId: session.userId,
102
+ language: session.language,
103
+ startedAt: session.startedAt,
104
+ lastEventAt: session.startedAt,
105
+ eventCount: 0,
106
+ turnCount: 0,
107
+ toolCallCount: 0,
108
+ navigationCount: 0,
109
+ errorCount: 0,
110
+ nextSeq: 0
111
+ });
112
+ } catch (error) {
113
+ if (isDuplicateKey(error)) throw new import_core.SpeeqError("CONFLICT", { message: "Session exists." });
114
+ throw error;
115
+ }
116
+ }
117
+ async appendEvents(sessionId, events) {
118
+ if (events.length === 0) return [];
119
+ const { sessions, events: eventsCol } = await this.collections();
120
+ const keys = events.map((e) => e.dedupeKey).filter((k) => k !== void 0);
121
+ if (new Set(keys).size !== keys.length) throw new import_core.SpeeqError("CONFLICT");
122
+ if (keys.length > 0 && await eventsCol.countDocuments({ sessionId, dedupeKey: { $in: keys } }, { limit: 1 }) > 0) {
123
+ throw new import_core.SpeeqError("CONFLICT");
124
+ }
125
+ const before = await sessions.findOneAndUpdate(
126
+ { _id: sessionId },
127
+ { $inc: { nextSeq: events.length } },
128
+ { returnDocument: "before", projection: { nextSeq: 1 } }
129
+ );
130
+ if (!before) throw new import_core.SpeeqError("NOT_FOUND", { message: "Session not found." });
131
+ const stored = events.map((e, i) => ({ ...e, seq: before.nextSeq + i }));
132
+ const docs = stored.map(({ id, ...rest }) => ({ _id: id, ...rest }));
133
+ try {
134
+ await eventsCol.insertMany(docs, { ordered: true });
135
+ } catch (error) {
136
+ await eventsCol.deleteMany({ _id: { $in: docs.map((d) => d._id) } });
137
+ if (isDuplicateKey(error)) throw new import_core.SpeeqError("CONFLICT");
138
+ throw error;
139
+ }
140
+ const lastEventAt = stored.reduce((max, e) => e.ts.localeCompare(max) > 0 ? e.ts : max, "");
141
+ await sessions.updateOne(
142
+ { _id: sessionId },
143
+ { $inc: counterDelta(events), $max: { lastEventAt } }
144
+ );
145
+ const firstUser = stored.find((e) => e.type === "user.message");
146
+ if (firstUser?.type === "user.message") {
147
+ await sessions.updateOne(
148
+ { _id: sessionId, preview: { $exists: false } },
149
+ { $set: { preview: firstUser.data.text.slice(0, 140) } }
150
+ );
151
+ }
152
+ return stored;
153
+ }
154
+ async listEvents(sessionId, options = {}) {
155
+ const { events } = await this.collections();
156
+ const filter = { sessionId };
157
+ if (options.afterSeq !== void 0) filter.seq = { $gt: options.afterSeq };
158
+ const last = options.last === true && options.limit !== void 0;
159
+ let cursor = events.find(filter).sort({ seq: last ? -1 : 1 });
160
+ if (options.limit !== void 0) cursor = cursor.limit(options.limit);
161
+ const docs = await cursor.toArray();
162
+ return (last ? docs.reverse() : docs).map(toEvent);
163
+ }
164
+ async listSessions(filter, cursor) {
165
+ const { sessions } = await this.collections();
166
+ const limit = filter.limit ?? 20;
167
+ const and = [];
168
+ if (filter.userId !== void 0) and.push({ userId: filter.userId });
169
+ if (filter.from !== void 0) and.push({ startedAt: { $gte: filter.from } });
170
+ if (filter.to !== void 0) and.push({ startedAt: { $lte: filter.to } });
171
+ const after = cursor ? (0, import_core.decodeCursor)(cursor) : null;
172
+ if (after) {
173
+ and.push({
174
+ $or: [
175
+ { startedAt: { $lt: after.startedAt } },
176
+ { startedAt: after.startedAt, _id: { $lt: after.id } }
177
+ ]
178
+ });
179
+ }
180
+ const docs = await sessions.find(and.length > 0 ? { $and: and } : {}).sort({ startedAt: -1, _id: -1 }).limit(limit + 1).toArray();
181
+ const page = docs.slice(0, limit).map(toSummary);
182
+ const last = page.at(-1);
183
+ return {
184
+ sessions: page,
185
+ nextCursor: docs.length > limit && last ? (0, import_core.encodeCursor)(last.startedAt, last.id) : null
186
+ };
187
+ }
188
+ async getSessionSummary(sessionId) {
189
+ const { sessions } = await this.collections();
190
+ const doc = await sessions.findOne({ _id: sessionId });
191
+ return doc ? toSummary(doc) : null;
192
+ }
193
+ async deleteOlderThan(date) {
194
+ const { sessions, events } = await this.collections();
195
+ const cutoff = date.toISOString();
196
+ const result = { sessions: 0, events: 0 };
197
+ for (; ; ) {
198
+ const batch = await sessions.find({ lastEventAt: { $lt: cutoff } }, { projection: { _id: 1 } }).limit(500).toArray();
199
+ if (batch.length === 0) return result;
200
+ const ids = batch.map((d) => d._id);
201
+ result.events += (await events.deleteMany({ sessionId: { $in: ids } })).deletedCount;
202
+ result.sessions += (await sessions.deleteMany({ _id: { $in: ids } })).deletedCount;
203
+ }
204
+ }
205
+ };
206
+ function createMongoStore(options) {
207
+ return new MongoStore(options);
208
+ }
209
+ // Annotate the CommonJS export names for ESM import in node:
210
+ 0 && (module.exports = {
211
+ MongoStore,
212
+ createMongoStore
213
+ });
214
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/store-mongodb`: a {@link ConversationStore} on your existing MongoDB connection.\n * It reuses the `Db` your app already has, so there is no second connection pool.\n * @packageDocumentation\n */\nimport {\n type ConversationEvent,\n type ConversationStore,\n decodeCursor,\n encodeCursor,\n type ListEventsOptions,\n type NewConversationEvent,\n type NewSession,\n type RetentionResult,\n type SessionFilter,\n type SessionPage,\n type SessionSummary,\n SpeeqError,\n} from \"@speeq/core\";\nimport type { Collection, Db, Filter } from \"mongodb\";\n\n/** Options for {@link createMongoStore}. */\nexport interface MongoStoreOptions {\n /** Your app's `Db`, a promise of it, or a function returning one (e.g. from a cached client). */\n db: Db | Promise<Db> | (() => Db | Promise<Db>);\n /** Collection name prefix. Default `speeq_` → `speeq_sessions`, `speeq_events`. */\n collectionPrefix?: string;\n /** Create indexes on first use. Default `true`. Set `false` if you manage indexes yourself. */\n ensureIndexes?: boolean;\n}\n\n/** Stored session document. */\ninterface SessionDoc extends Omit<SessionSummary, \"id\"> {\n _id: string;\n nextSeq: number;\n}\n\n/** Stored event document. */\ntype EventDoc = Omit<ConversationEvent, \"id\"> & { _id: string };\n\nconst DUPLICATE_KEY = 11000;\n\nfunction isDuplicateKey(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const e = error as { code?: unknown; writeErrors?: Array<{ code?: unknown }> };\n return e.code === DUPLICATE_KEY || (e.writeErrors ?? []).some((w) => w.code === DUPLICATE_KEY);\n}\n\nfunction toSummary(doc: SessionDoc): SessionSummary {\n const { _id, nextSeq: _seq, ...rest } = doc;\n return { id: _id, ...rest };\n}\n\nfunction toEvent(doc: EventDoc): ConversationEvent {\n const { _id, ...rest } = doc;\n return { id: _id, ...rest } as ConversationEvent;\n}\n\nfunction counterDelta(events: NewConversationEvent[]) {\n const inc = {\n eventCount: events.length,\n turnCount: 0,\n toolCallCount: 0,\n navigationCount: 0,\n errorCount: 0,\n };\n for (const e of events) {\n if (e.type === \"user.message\") inc.turnCount += 1;\n else if (e.type === \"tool.called\") inc.toolCallCount += 1;\n else if (e.type === \"navigation\") inc.navigationCount += 1;\n else if (e.type === \"error\") inc.errorCount += 1;\n }\n return inc;\n}\n\n/** A MongoDB-backed {@link ConversationStore}. Create it with {@link createMongoStore}. */\nexport class MongoStore implements ConversationStore {\n readonly kind = \"mongodb\";\n private ready: Promise<{\n sessions: Collection<SessionDoc>;\n events: Collection<EventDoc>;\n }> | null = null;\n\n constructor(private readonly options: MongoStoreOptions) {}\n\n private collections() {\n this.ready ??= (async () => {\n const source = this.options.db;\n const db = await (typeof source === \"function\" ? source() : source);\n const prefix = this.options.collectionPrefix ?? \"speeq_\";\n const sessions = db.collection<SessionDoc>(`${prefix}sessions`);\n const events = db.collection<EventDoc>(`${prefix}events`);\n if (this.options.ensureIndexes !== false) {\n await Promise.all([\n events.createIndex({ sessionId: 1, seq: 1 }, { unique: true, name: \"session_seq\" }),\n events.createIndex(\n { sessionId: 1, dedupeKey: 1 },\n {\n unique: true,\n name: \"session_dedupe\",\n partialFilterExpression: { dedupeKey: { $type: \"string\" } },\n },\n ),\n events.createIndex({ ts: 1 }, { name: \"ts\" }),\n sessions.createIndex({ userId: 1, startedAt: -1 }, { name: \"user_started\" }),\n sessions.createIndex({ startedAt: -1, _id: -1 }, { name: \"started\" }),\n sessions.createIndex({ lastEventAt: 1 }, { name: \"last_event\" }),\n ]);\n }\n return { sessions, events };\n })().catch((error: unknown) => {\n this.ready = null; // retry on the next call\n throw error;\n });\n return this.ready;\n }\n\n async createSession(session: NewSession): Promise<void> {\n const { sessions } = await this.collections();\n try {\n await sessions.insertOne({\n _id: session.id,\n userId: session.userId,\n language: session.language,\n startedAt: session.startedAt,\n lastEventAt: session.startedAt,\n eventCount: 0,\n turnCount: 0,\n toolCallCount: 0,\n navigationCount: 0,\n errorCount: 0,\n nextSeq: 0,\n });\n } catch (error) {\n if (isDuplicateKey(error)) throw new SpeeqError(\"CONFLICT\", { message: \"Session exists.\" });\n throw error;\n }\n }\n\n async appendEvents(\n sessionId: string,\n events: NewConversationEvent[],\n ): Promise<ConversationEvent[]> {\n if (events.length === 0) return [];\n const { sessions, events: eventsCol } = await this.collections();\n const keys = events.map((e) => e.dedupeKey).filter((k): k is string => k !== undefined);\n if (new Set(keys).size !== keys.length) throw new SpeeqError(\"CONFLICT\");\n if (\n keys.length > 0 &&\n (await eventsCol.countDocuments({ sessionId, dedupeKey: { $in: keys } }, { limit: 1 })) > 0\n ) {\n throw new SpeeqError(\"CONFLICT\");\n }\n\n // Reserve a block of sequence numbers atomically.\n const before = await sessions.findOneAndUpdate(\n { _id: sessionId },\n { $inc: { nextSeq: events.length } },\n { returnDocument: \"before\", projection: { nextSeq: 1 } },\n );\n if (!before) throw new SpeeqError(\"NOT_FOUND\", { message: \"Session not found.\" });\n const stored = events.map((e, i) => ({ ...e, seq: before.nextSeq + i }) as ConversationEvent);\n const docs = stored.map(({ id, ...rest }) => ({ _id: id, ...rest }) as EventDoc);\n\n try {\n await eventsCol.insertMany(docs, { ordered: true });\n } catch (error) {\n // Undo a partial batch so the call is all-or-nothing, then report the conflict.\n await eventsCol.deleteMany({ _id: { $in: docs.map((d) => d._id) } });\n if (isDuplicateKey(error)) throw new SpeeqError(\"CONFLICT\");\n throw error;\n }\n\n const lastEventAt = stored.reduce((max, e) => (e.ts.localeCompare(max) > 0 ? e.ts : max), \"\");\n await sessions.updateOne(\n { _id: sessionId },\n { $inc: counterDelta(events), $max: { lastEventAt } },\n );\n const firstUser = stored.find((e) => e.type === \"user.message\");\n if (firstUser?.type === \"user.message\") {\n await sessions.updateOne(\n { _id: sessionId, preview: { $exists: false } },\n { $set: { preview: firstUser.data.text.slice(0, 140) } },\n );\n }\n return stored;\n }\n\n async listEvents(\n sessionId: string,\n options: ListEventsOptions = {},\n ): Promise<ConversationEvent[]> {\n const { events } = await this.collections();\n const filter: Filter<EventDoc> = { sessionId };\n if (options.afterSeq !== undefined) filter.seq = { $gt: options.afterSeq };\n const last = options.last === true && options.limit !== undefined;\n let cursor = events.find(filter).sort({ seq: last ? -1 : 1 });\n if (options.limit !== undefined) cursor = cursor.limit(options.limit);\n const docs = await cursor.toArray();\n return (last ? docs.reverse() : docs).map(toEvent);\n }\n\n async listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage> {\n const { sessions } = await this.collections();\n const limit = filter.limit ?? 20;\n const and: Filter<SessionDoc>[] = [];\n if (filter.userId !== undefined) and.push({ userId: filter.userId });\n if (filter.from !== undefined) and.push({ startedAt: { $gte: filter.from } });\n if (filter.to !== undefined) and.push({ startedAt: { $lte: filter.to } });\n const after = cursor ? decodeCursor(cursor) : null;\n if (after) {\n and.push({\n $or: [\n { startedAt: { $lt: after.startedAt } },\n { startedAt: after.startedAt, _id: { $lt: after.id } },\n ],\n });\n }\n const docs = await sessions\n .find(and.length > 0 ? { $and: and } : {})\n .sort({ startedAt: -1, _id: -1 })\n .limit(limit + 1)\n .toArray();\n const page = docs.slice(0, limit).map(toSummary);\n const last = page.at(-1);\n return {\n sessions: page,\n nextCursor: docs.length > limit && last ? encodeCursor(last.startedAt, last.id) : null,\n };\n }\n\n async getSessionSummary(sessionId: string): Promise<SessionSummary | null> {\n const { sessions } = await this.collections();\n const doc = await sessions.findOne({ _id: sessionId });\n return doc ? toSummary(doc) : null;\n }\n\n async deleteOlderThan(date: Date): Promise<RetentionResult> {\n const { sessions, events } = await this.collections();\n const cutoff = date.toISOString();\n const result: RetentionResult = { sessions: 0, events: 0 };\n for (;;) {\n const batch = await sessions\n .find({ lastEventAt: { $lt: cutoff } }, { projection: { _id: 1 } })\n .limit(500)\n .toArray();\n if (batch.length === 0) return result;\n const ids = batch.map((d) => d._id);\n result.events += (await events.deleteMany({ sessionId: { $in: ids } })).deletedCount;\n result.sessions += (await sessions.deleteMany({ _id: { $in: ids } })).deletedCount;\n }\n }\n}\n\n/**\n * Creates a MongoDB store from your existing connection.\n *\n * @example\n * import clientPromise from \"@/lib/mongodb\"; // your app's cached MongoClient\n * const store = createMongoStore({ db: async () => (await clientPromise).db() });\n */\nexport function createMongoStore(options: MongoStoreOptions): MongoStore {\n return new MongoStore(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,kBAaO;AAsBP,IAAM,gBAAgB;AAEtB,SAAS,eAAe,OAAyB;AAC/C,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,IAAI;AACV,SAAO,EAAE,SAAS,kBAAkB,EAAE,eAAe,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,SA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AG,EAAE,YAAY,EAAE,KAAK,EAAE,EAAE,CAAC,EACjE,MAAM,GAAG,EACT,QAAQ;AACX,UAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,YAAM,MAAM,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG;AAClC,aAAO,WAAW,MAAM,OAAO,WAAW,EAAE,WAAW,EAAE,KAAK,IAAI,EAAE,CAAC,GAAG;AACxE,aAAO,aAAa,MAAM,SAAS,WAAW,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,GAAG;AAAA,IACxE;AAAA,EACF;AACF;AASO,SAAS,iBAAiB,SAAwC;AACvE,SAAO,IAAI,WAAW,OAAO;AAC/B;","names":[]}
@@ -0,0 +1,43 @@
1
+ import { ConversationStore, NewSession, NewConversationEvent, ConversationEvent, ListEventsOptions, SessionFilter, SessionPage, SessionSummary, RetentionResult } from '@speeq/core';
2
+ import { Db } from 'mongodb';
3
+
4
+ /**
5
+ * `@speeq/store-mongodb`: a {@link ConversationStore} on your existing MongoDB connection.
6
+ * It reuses the `Db` your app already has, so there is no second connection pool.
7
+ * @packageDocumentation
8
+ */
9
+
10
+ /** Options for {@link createMongoStore}. */
11
+ interface MongoStoreOptions {
12
+ /** Your app's `Db`, a promise of it, or a function returning one (e.g. from a cached client). */
13
+ db: Db | Promise<Db> | (() => Db | Promise<Db>);
14
+ /** Collection name prefix. Default `speeq_` → `speeq_sessions`, `speeq_events`. */
15
+ collectionPrefix?: string;
16
+ /** Create indexes on first use. Default `true`. Set `false` if you manage indexes yourself. */
17
+ ensureIndexes?: boolean;
18
+ }
19
+ /** A MongoDB-backed {@link ConversationStore}. Create it with {@link createMongoStore}. */
20
+ declare class MongoStore implements ConversationStore {
21
+ private readonly options;
22
+ readonly kind = "mongodb";
23
+ private ready;
24
+ constructor(options: MongoStoreOptions);
25
+ private collections;
26
+ createSession(session: NewSession): Promise<void>;
27
+ appendEvents(sessionId: string, events: NewConversationEvent[]): Promise<ConversationEvent[]>;
28
+ listEvents(sessionId: string, options?: ListEventsOptions): Promise<ConversationEvent[]>;
29
+ listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage>;
30
+ getSessionSummary(sessionId: string): Promise<SessionSummary | null>;
31
+ deleteOlderThan(date: Date): Promise<RetentionResult>;
32
+ }
33
+ /**
34
+ * Creates a MongoDB store from your existing connection.
35
+ *
36
+ * @example
37
+ * import clientPromise from "@/lib/mongodb"; // your app's cached MongoClient
38
+ * const store = createMongoStore({ db: async () => (await clientPromise).db() });
39
+ */
40
+ declare function createMongoStore(options: MongoStoreOptions): MongoStore;
41
+
42
+ export { MongoStore, createMongoStore };
43
+ export type { MongoStoreOptions };
@@ -0,0 +1,43 @@
1
+ import { ConversationStore, NewSession, NewConversationEvent, ConversationEvent, ListEventsOptions, SessionFilter, SessionPage, SessionSummary, RetentionResult } from '@speeq/core';
2
+ import { Db } from 'mongodb';
3
+
4
+ /**
5
+ * `@speeq/store-mongodb`: a {@link ConversationStore} on your existing MongoDB connection.
6
+ * It reuses the `Db` your app already has, so there is no second connection pool.
7
+ * @packageDocumentation
8
+ */
9
+
10
+ /** Options for {@link createMongoStore}. */
11
+ interface MongoStoreOptions {
12
+ /** Your app's `Db`, a promise of it, or a function returning one (e.g. from a cached client). */
13
+ db: Db | Promise<Db> | (() => Db | Promise<Db>);
14
+ /** Collection name prefix. Default `speeq_` → `speeq_sessions`, `speeq_events`. */
15
+ collectionPrefix?: string;
16
+ /** Create indexes on first use. Default `true`. Set `false` if you manage indexes yourself. */
17
+ ensureIndexes?: boolean;
18
+ }
19
+ /** A MongoDB-backed {@link ConversationStore}. Create it with {@link createMongoStore}. */
20
+ declare class MongoStore implements ConversationStore {
21
+ private readonly options;
22
+ readonly kind = "mongodb";
23
+ private ready;
24
+ constructor(options: MongoStoreOptions);
25
+ private collections;
26
+ createSession(session: NewSession): Promise<void>;
27
+ appendEvents(sessionId: string, events: NewConversationEvent[]): Promise<ConversationEvent[]>;
28
+ listEvents(sessionId: string, options?: ListEventsOptions): Promise<ConversationEvent[]>;
29
+ listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage>;
30
+ getSessionSummary(sessionId: string): Promise<SessionSummary | null>;
31
+ deleteOlderThan(date: Date): Promise<RetentionResult>;
32
+ }
33
+ /**
34
+ * Creates a MongoDB store from your existing connection.
35
+ *
36
+ * @example
37
+ * import clientPromise from "@/lib/mongodb"; // your app's cached MongoClient
38
+ * const store = createMongoStore({ db: async () => (await clientPromise).db() });
39
+ */
40
+ declare function createMongoStore(options: MongoStoreOptions): MongoStore;
41
+
42
+ export { MongoStore, createMongoStore };
43
+ export type { MongoStoreOptions };
package/dist/index.js ADDED
@@ -0,0 +1,192 @@
1
+ // src/index.ts
2
+ import {
3
+ decodeCursor,
4
+ encodeCursor,
5
+ SpeeqError
6
+ } from "@speeq/core";
7
+ var DUPLICATE_KEY = 11e3;
8
+ function isDuplicateKey(error) {
9
+ if (typeof error !== "object" || error === null) return false;
10
+ const e = error;
11
+ return e.code === DUPLICATE_KEY || (e.writeErrors ?? []).some((w) => w.code === DUPLICATE_KEY);
12
+ }
13
+ function toSummary(doc) {
14
+ const { _id, nextSeq: _seq, ...rest } = doc;
15
+ return { id: _id, ...rest };
16
+ }
17
+ function toEvent(doc) {
18
+ const { _id, ...rest } = doc;
19
+ return { id: _id, ...rest };
20
+ }
21
+ function counterDelta(events) {
22
+ const inc = {
23
+ eventCount: events.length,
24
+ turnCount: 0,
25
+ toolCallCount: 0,
26
+ navigationCount: 0,
27
+ errorCount: 0
28
+ };
29
+ for (const e of events) {
30
+ if (e.type === "user.message") inc.turnCount += 1;
31
+ else if (e.type === "tool.called") inc.toolCallCount += 1;
32
+ else if (e.type === "navigation") inc.navigationCount += 1;
33
+ else if (e.type === "error") inc.errorCount += 1;
34
+ }
35
+ return inc;
36
+ }
37
+ var MongoStore = class {
38
+ constructor(options) {
39
+ this.options = options;
40
+ }
41
+ options;
42
+ kind = "mongodb";
43
+ ready = null;
44
+ collections() {
45
+ this.ready ??= (async () => {
46
+ const source = this.options.db;
47
+ const db = await (typeof source === "function" ? source() : source);
48
+ const prefix = this.options.collectionPrefix ?? "speeq_";
49
+ const sessions = db.collection(`${prefix}sessions`);
50
+ const events = db.collection(`${prefix}events`);
51
+ if (this.options.ensureIndexes !== false) {
52
+ await Promise.all([
53
+ events.createIndex({ sessionId: 1, seq: 1 }, { unique: true, name: "session_seq" }),
54
+ events.createIndex(
55
+ { sessionId: 1, dedupeKey: 1 },
56
+ {
57
+ unique: true,
58
+ name: "session_dedupe",
59
+ partialFilterExpression: { dedupeKey: { $type: "string" } }
60
+ }
61
+ ),
62
+ events.createIndex({ ts: 1 }, { name: "ts" }),
63
+ sessions.createIndex({ userId: 1, startedAt: -1 }, { name: "user_started" }),
64
+ sessions.createIndex({ startedAt: -1, _id: -1 }, { name: "started" }),
65
+ sessions.createIndex({ lastEventAt: 1 }, { name: "last_event" })
66
+ ]);
67
+ }
68
+ return { sessions, events };
69
+ })().catch((error) => {
70
+ this.ready = null;
71
+ throw error;
72
+ });
73
+ return this.ready;
74
+ }
75
+ async createSession(session) {
76
+ const { sessions } = await this.collections();
77
+ try {
78
+ await sessions.insertOne({
79
+ _id: session.id,
80
+ userId: session.userId,
81
+ language: session.language,
82
+ startedAt: session.startedAt,
83
+ lastEventAt: session.startedAt,
84
+ eventCount: 0,
85
+ turnCount: 0,
86
+ toolCallCount: 0,
87
+ navigationCount: 0,
88
+ errorCount: 0,
89
+ nextSeq: 0
90
+ });
91
+ } catch (error) {
92
+ if (isDuplicateKey(error)) throw new SpeeqError("CONFLICT", { message: "Session exists." });
93
+ throw error;
94
+ }
95
+ }
96
+ async appendEvents(sessionId, events) {
97
+ if (events.length === 0) return [];
98
+ const { sessions, events: eventsCol } = await this.collections();
99
+ const keys = events.map((e) => e.dedupeKey).filter((k) => k !== void 0);
100
+ if (new Set(keys).size !== keys.length) throw new SpeeqError("CONFLICT");
101
+ if (keys.length > 0 && await eventsCol.countDocuments({ sessionId, dedupeKey: { $in: keys } }, { limit: 1 }) > 0) {
102
+ throw new SpeeqError("CONFLICT");
103
+ }
104
+ const before = await sessions.findOneAndUpdate(
105
+ { _id: sessionId },
106
+ { $inc: { nextSeq: events.length } },
107
+ { returnDocument: "before", projection: { nextSeq: 1 } }
108
+ );
109
+ if (!before) throw new SpeeqError("NOT_FOUND", { message: "Session not found." });
110
+ const stored = events.map((e, i) => ({ ...e, seq: before.nextSeq + i }));
111
+ const docs = stored.map(({ id, ...rest }) => ({ _id: id, ...rest }));
112
+ try {
113
+ await eventsCol.insertMany(docs, { ordered: true });
114
+ } catch (error) {
115
+ await eventsCol.deleteMany({ _id: { $in: docs.map((d) => d._id) } });
116
+ if (isDuplicateKey(error)) throw new SpeeqError("CONFLICT");
117
+ throw error;
118
+ }
119
+ const lastEventAt = stored.reduce((max, e) => e.ts.localeCompare(max) > 0 ? e.ts : max, "");
120
+ await sessions.updateOne(
121
+ { _id: sessionId },
122
+ { $inc: counterDelta(events), $max: { lastEventAt } }
123
+ );
124
+ const firstUser = stored.find((e) => e.type === "user.message");
125
+ if (firstUser?.type === "user.message") {
126
+ await sessions.updateOne(
127
+ { _id: sessionId, preview: { $exists: false } },
128
+ { $set: { preview: firstUser.data.text.slice(0, 140) } }
129
+ );
130
+ }
131
+ return stored;
132
+ }
133
+ async listEvents(sessionId, options = {}) {
134
+ const { events } = await this.collections();
135
+ const filter = { sessionId };
136
+ if (options.afterSeq !== void 0) filter.seq = { $gt: options.afterSeq };
137
+ const last = options.last === true && options.limit !== void 0;
138
+ let cursor = events.find(filter).sort({ seq: last ? -1 : 1 });
139
+ if (options.limit !== void 0) cursor = cursor.limit(options.limit);
140
+ const docs = await cursor.toArray();
141
+ return (last ? docs.reverse() : docs).map(toEvent);
142
+ }
143
+ async listSessions(filter, cursor) {
144
+ const { sessions } = await this.collections();
145
+ const limit = filter.limit ?? 20;
146
+ const and = [];
147
+ if (filter.userId !== void 0) and.push({ userId: filter.userId });
148
+ if (filter.from !== void 0) and.push({ startedAt: { $gte: filter.from } });
149
+ if (filter.to !== void 0) and.push({ startedAt: { $lte: filter.to } });
150
+ const after = cursor ? decodeCursor(cursor) : null;
151
+ if (after) {
152
+ and.push({
153
+ $or: [
154
+ { startedAt: { $lt: after.startedAt } },
155
+ { startedAt: after.startedAt, _id: { $lt: after.id } }
156
+ ]
157
+ });
158
+ }
159
+ const docs = await sessions.find(and.length > 0 ? { $and: and } : {}).sort({ startedAt: -1, _id: -1 }).limit(limit + 1).toArray();
160
+ const page = docs.slice(0, limit).map(toSummary);
161
+ const last = page.at(-1);
162
+ return {
163
+ sessions: page,
164
+ nextCursor: docs.length > limit && last ? encodeCursor(last.startedAt, last.id) : null
165
+ };
166
+ }
167
+ async getSessionSummary(sessionId) {
168
+ const { sessions } = await this.collections();
169
+ const doc = await sessions.findOne({ _id: sessionId });
170
+ return doc ? toSummary(doc) : null;
171
+ }
172
+ async deleteOlderThan(date) {
173
+ const { sessions, events } = await this.collections();
174
+ const cutoff = date.toISOString();
175
+ const result = { sessions: 0, events: 0 };
176
+ for (; ; ) {
177
+ const batch = await sessions.find({ lastEventAt: { $lt: cutoff } }, { projection: { _id: 1 } }).limit(500).toArray();
178
+ if (batch.length === 0) return result;
179
+ const ids = batch.map((d) => d._id);
180
+ result.events += (await events.deleteMany({ sessionId: { $in: ids } })).deletedCount;
181
+ result.sessions += (await sessions.deleteMany({ _id: { $in: ids } })).deletedCount;
182
+ }
183
+ }
184
+ };
185
+ function createMongoStore(options) {
186
+ return new MongoStore(options);
187
+ }
188
+ export {
189
+ MongoStore,
190
+ createMongoStore
191
+ };
192
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/store-mongodb`: a {@link ConversationStore} on your existing MongoDB connection.\n * It reuses the `Db` your app already has, so there is no second connection pool.\n * @packageDocumentation\n */\nimport {\n type ConversationEvent,\n type ConversationStore,\n decodeCursor,\n encodeCursor,\n type ListEventsOptions,\n type NewConversationEvent,\n type NewSession,\n type RetentionResult,\n type SessionFilter,\n type SessionPage,\n type SessionSummary,\n SpeeqError,\n} from \"@speeq/core\";\nimport type { Collection, Db, Filter } from \"mongodb\";\n\n/** Options for {@link createMongoStore}. */\nexport interface MongoStoreOptions {\n /** Your app's `Db`, a promise of it, or a function returning one (e.g. from a cached client). */\n db: Db | Promise<Db> | (() => Db | Promise<Db>);\n /** Collection name prefix. Default `speeq_` → `speeq_sessions`, `speeq_events`. */\n collectionPrefix?: string;\n /** Create indexes on first use. Default `true`. Set `false` if you manage indexes yourself. */\n ensureIndexes?: boolean;\n}\n\n/** Stored session document. */\ninterface SessionDoc extends Omit<SessionSummary, \"id\"> {\n _id: string;\n nextSeq: number;\n}\n\n/** Stored event document. */\ntype EventDoc = Omit<ConversationEvent, \"id\"> & { _id: string };\n\nconst DUPLICATE_KEY = 11000;\n\nfunction isDuplicateKey(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const e = error as { code?: unknown; writeErrors?: Array<{ code?: unknown }> };\n return e.code === DUPLICATE_KEY || (e.writeErrors ?? []).some((w) => w.code === DUPLICATE_KEY);\n}\n\nfunction toSummary(doc: SessionDoc): SessionSummary {\n const { _id, nextSeq: _seq, ...rest } = doc;\n return { id: _id, ...rest };\n}\n\nfunction toEvent(doc: EventDoc): ConversationEvent {\n const { _id, ...rest } = doc;\n return { id: _id, ...rest } as ConversationEvent;\n}\n\nfunction counterDelta(events: NewConversationEvent[]) {\n const inc = {\n eventCount: events.length,\n turnCount: 0,\n toolCallCount: 0,\n navigationCount: 0,\n errorCount: 0,\n };\n for (const e of events) {\n if (e.type === \"user.message\") inc.turnCount += 1;\n else if (e.type === \"tool.called\") inc.toolCallCount += 1;\n else if (e.type === \"navigation\") inc.navigationCount += 1;\n else if (e.type === \"error\") inc.errorCount += 1;\n }\n return inc;\n}\n\n/** A MongoDB-backed {@link ConversationStore}. Create it with {@link createMongoStore}. */\nexport class MongoStore implements ConversationStore {\n readonly kind = \"mongodb\";\n private ready: Promise<{\n sessions: Collection<SessionDoc>;\n events: Collection<EventDoc>;\n }> | null = null;\n\n constructor(private readonly options: MongoStoreOptions) {}\n\n private collections() {\n this.ready ??= (async () => {\n const source = this.options.db;\n const db = await (typeof source === \"function\" ? source() : source);\n const prefix = this.options.collectionPrefix ?? \"speeq_\";\n const sessions = db.collection<SessionDoc>(`${prefix}sessions`);\n const events = db.collection<EventDoc>(`${prefix}events`);\n if (this.options.ensureIndexes !== false) {\n await Promise.all([\n events.createIndex({ sessionId: 1, seq: 1 }, { unique: true, name: \"session_seq\" }),\n events.createIndex(\n { sessionId: 1, dedupeKey: 1 },\n {\n unique: true,\n name: \"session_dedupe\",\n partialFilterExpression: { dedupeKey: { $type: \"string\" } },\n },\n ),\n events.createIndex({ ts: 1 }, { name: \"ts\" }),\n sessions.createIndex({ userId: 1, startedAt: -1 }, { name: \"user_started\" }),\n sessions.createIndex({ startedAt: -1, _id: -1 }, { name: \"started\" }),\n sessions.createIndex({ lastEventAt: 1 }, { name: \"last_event\" }),\n ]);\n }\n return { sessions, events };\n })().catch((error: unknown) => {\n this.ready = null; // retry on the next call\n throw error;\n });\n return this.ready;\n }\n\n async createSession(session: NewSession): Promise<void> {\n const { sessions } = await this.collections();\n try {\n await sessions.insertOne({\n _id: session.id,\n userId: session.userId,\n language: session.language,\n startedAt: session.startedAt,\n lastEventAt: session.startedAt,\n eventCount: 0,\n turnCount: 0,\n toolCallCount: 0,\n navigationCount: 0,\n errorCount: 0,\n nextSeq: 0,\n });\n } catch (error) {\n if (isDuplicateKey(error)) throw new SpeeqError(\"CONFLICT\", { message: \"Session exists.\" });\n throw error;\n }\n }\n\n async appendEvents(\n sessionId: string,\n events: NewConversationEvent[],\n ): Promise<ConversationEvent[]> {\n if (events.length === 0) return [];\n const { sessions, events: eventsCol } = await this.collections();\n const keys = events.map((e) => e.dedupeKey).filter((k): k is string => k !== undefined);\n if (new Set(keys).size !== keys.length) throw new SpeeqError(\"CONFLICT\");\n if (\n keys.length > 0 &&\n (await eventsCol.countDocuments({ sessionId, dedupeKey: { $in: keys } }, { limit: 1 })) > 0\n ) {\n throw new SpeeqError(\"CONFLICT\");\n }\n\n // Reserve a block of sequence numbers atomically.\n const before = await sessions.findOneAndUpdate(\n { _id: sessionId },\n { $inc: { nextSeq: events.length } },\n { returnDocument: \"before\", projection: { nextSeq: 1 } },\n );\n if (!before) throw new SpeeqError(\"NOT_FOUND\", { message: \"Session not found.\" });\n const stored = events.map((e, i) => ({ ...e, seq: before.nextSeq + i }) as ConversationEvent);\n const docs = stored.map(({ id, ...rest }) => ({ _id: id, ...rest }) as EventDoc);\n\n try {\n await eventsCol.insertMany(docs, { ordered: true });\n } catch (error) {\n // Undo a partial batch so the call is all-or-nothing, then report the conflict.\n await eventsCol.deleteMany({ _id: { $in: docs.map((d) => d._id) } });\n if (isDuplicateKey(error)) throw new SpeeqError(\"CONFLICT\");\n throw error;\n }\n\n const lastEventAt = stored.reduce((max, e) => (e.ts.localeCompare(max) > 0 ? e.ts : max), \"\");\n await sessions.updateOne(\n { _id: sessionId },\n { $inc: counterDelta(events), $max: { lastEventAt } },\n );\n const firstUser = stored.find((e) => e.type === \"user.message\");\n if (firstUser?.type === \"user.message\") {\n await sessions.updateOne(\n { _id: sessionId, preview: { $exists: false } },\n { $set: { preview: firstUser.data.text.slice(0, 140) } },\n );\n }\n return stored;\n }\n\n async listEvents(\n sessionId: string,\n options: ListEventsOptions = {},\n ): Promise<ConversationEvent[]> {\n const { events } = await this.collections();\n const filter: Filter<EventDoc> = { sessionId };\n if (options.afterSeq !== undefined) filter.seq = { $gt: options.afterSeq };\n const last = options.last === true && options.limit !== undefined;\n let cursor = events.find(filter).sort({ seq: last ? -1 : 1 });\n if (options.limit !== undefined) cursor = cursor.limit(options.limit);\n const docs = await cursor.toArray();\n return (last ? docs.reverse() : docs).map(toEvent);\n }\n\n async listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage> {\n const { sessions } = await this.collections();\n const limit = filter.limit ?? 20;\n const and: Filter<SessionDoc>[] = [];\n if (filter.userId !== undefined) and.push({ userId: filter.userId });\n if (filter.from !== undefined) and.push({ startedAt: { $gte: filter.from } });\n if (filter.to !== undefined) and.push({ startedAt: { $lte: filter.to } });\n const after = cursor ? decodeCursor(cursor) : null;\n if (after) {\n and.push({\n $or: [\n { startedAt: { $lt: after.startedAt } },\n { startedAt: after.startedAt, _id: { $lt: after.id } },\n ],\n });\n }\n const docs = await sessions\n .find(and.length > 0 ? { $and: and } : {})\n .sort({ startedAt: -1, _id: -1 })\n .limit(limit + 1)\n .toArray();\n const page = docs.slice(0, limit).map(toSummary);\n const last = page.at(-1);\n return {\n sessions: page,\n nextCursor: docs.length > limit && last ? encodeCursor(last.startedAt, last.id) : null,\n };\n }\n\n async getSessionSummary(sessionId: string): Promise<SessionSummary | null> {\n const { sessions } = await this.collections();\n const doc = await sessions.findOne({ _id: sessionId });\n return doc ? toSummary(doc) : null;\n }\n\n async deleteOlderThan(date: Date): Promise<RetentionResult> {\n const { sessions, events } = await this.collections();\n const cutoff = date.toISOString();\n const result: RetentionResult = { sessions: 0, events: 0 };\n for (;;) {\n const batch = await sessions\n .find({ lastEventAt: { $lt: cutoff } }, { projection: { _id: 1 } })\n .limit(500)\n .toArray();\n if (batch.length === 0) return result;\n const ids = batch.map((d) => d._id);\n result.events += (await events.deleteMany({ sessionId: { $in: ids } })).deletedCount;\n result.sessions += (await sessions.deleteMany({ _id: { $in: ids } })).deletedCount;\n }\n }\n}\n\n/**\n * Creates a MongoDB store from your existing connection.\n *\n * @example\n * import clientPromise from \"@/lib/mongodb\"; // your app's cached MongoClient\n * const store = createMongoStore({ db: async () => (await clientPromise).db() });\n */\nexport function createMongoStore(options: MongoStoreOptions): MongoStore {\n return new MongoStore(options);\n}\n"],"mappings":";AAKA;AAAA,EAGE;AAAA,EACA;AAAA,EAQA;AAAA,OACK;AAsBP,IAAM,gBAAgB;AAEtB,SAAS,eAAe,OAAyB;AAC/C,MAAI,OAA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AA0B,EAAE,UAAU,GAAG,QAAQ,EAAE;AACzD,eAAS;AACP,YAAM,QAAQ,MAAM,SACjB,KAAK,EAAE,aAAa,EAAE,KAAK,OAAO,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,EAAE,CAAC,EACjE,MAAM,GAAG,EACT,QAAQ;AACX,UAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,YAAM,MAAM,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG;AAClC,aAAO,WAAW,MAAM,OAAO,WAAW,EAAE,WAAW,EAAE,KAAK,IAAI,EAAE,CAAC,GAAG;AACxE,aAAO,aAAa,MAAM,SAAS,WAAW,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,GAAG;AAAA,IACxE;AAAA,EACF;AACF;AASO,SAAS,iBAAiB,SAAwC;AACvE,SAAO,IAAI,WAAW,OAAO;AAC/B;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@speeq/store-mongodb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "MongoDB ConversationStore for speeq that reuses your existing Db connection.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Mudavath-Giri-Naik/speeq.git",
11
+ "directory": "packages/adapters/store-mongodb"
12
+ },
13
+ "homepage": "https://github.com/Mudavath-Giri-Naik/speeq#readme",
14
+ "keywords": [
15
+ "speeq",
16
+ "voice",
17
+ "agent",
18
+ "conversational-ai",
19
+ "headless"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md"
27
+ ],
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "@speeq/source": "./src/index.ts",
34
+ "import": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "require": {
39
+ "types": "./dist/index.d.cts",
40
+ "default": "./dist/index.cjs"
41
+ }
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@speeq/core": "0.2.0"
50
+ },
51
+ "peerDependencies": {
52
+ "mongodb": ">=6.0.0"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "mongodb": {
56
+ "optional": true
57
+ }
58
+ },
59
+ "devDependencies": {
60
+ "@speeq/tsconfig": "0.0.0",
61
+ "@speeq/testing": "0.2.0",
62
+ "mongodb": "7.9.1",
63
+ "mongodb-memory-server": "11.4.0",
64
+ "zod": "4.6.7"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup",
68
+ "typecheck": "tsc --noEmit",
69
+ "test": "vitest run"
70
+ }
6
71
  }