@devwithbobby/loops 0.1.17 → 0.1.19

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 (49) hide show
  1. package/README.md +46 -23
  2. package/dist/client/index.d.ts +105 -85
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +26 -7
  5. package/dist/component/_generated/api.d.ts +44 -0
  6. package/dist/component/_generated/api.d.ts.map +1 -0
  7. package/{src → dist}/component/_generated/api.js +10 -3
  8. package/dist/component/_generated/component.d.ts +259 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -0
  10. package/dist/component/_generated/component.js +9 -0
  11. package/dist/component/_generated/dataModel.d.ts +46 -0
  12. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  13. package/dist/component/_generated/dataModel.js +10 -0
  14. package/{src → dist}/component/_generated/server.d.ts +10 -38
  15. package/dist/component/_generated/server.d.ts.map +1 -0
  16. package/{src → dist}/component/_generated/server.js +9 -22
  17. package/dist/component/convex.config.d.ts.map +1 -1
  18. package/dist/component/convex.config.js +0 -22
  19. package/dist/component/helpers.d.ts +1 -1
  20. package/dist/component/helpers.d.ts.map +1 -1
  21. package/dist/component/helpers.js +1 -2
  22. package/dist/component/http.d.ts.map +1 -1
  23. package/dist/component/http.js +0 -1
  24. package/dist/component/lib.d.ts +7 -0
  25. package/dist/component/lib.d.ts.map +1 -1
  26. package/dist/component/lib.js +62 -20
  27. package/dist/component/schema.d.ts +2 -2
  28. package/dist/component/tables/contacts.d.ts.map +1 -1
  29. package/dist/component/tables/emailOperations.d.ts +4 -4
  30. package/dist/component/tables/emailOperations.d.ts.map +1 -1
  31. package/dist/test.d.ts +83 -0
  32. package/dist/test.d.ts.map +1 -0
  33. package/dist/test.js +16 -0
  34. package/dist/utils.d.ts +6 -6
  35. package/package.json +15 -9
  36. package/src/client/index.ts +31 -14
  37. package/src/component/_generated/api.ts +60 -0
  38. package/src/component/_generated/component.ts +323 -0
  39. package/src/component/_generated/{dataModel.d.ts → dataModel.ts} +1 -1
  40. package/src/component/_generated/server.ts +161 -0
  41. package/src/component/convex.config.ts +0 -27
  42. package/src/component/helpers.ts +2 -2
  43. package/src/component/http.ts +0 -4
  44. package/src/component/lib.ts +69 -20
  45. package/src/test.ts +27 -0
  46. package/dist/client/types.d.ts +0 -24
  47. package/dist/client/types.d.ts.map +0 -1
  48. package/dist/client/types.js +0 -0
  49. package/src/component/_generated/api.d.ts +0 -47
@@ -0,0 +1,323 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ lib: {
27
+ addContact: FunctionReference<
28
+ "action",
29
+ "internal",
30
+ {
31
+ apiKey: string;
32
+ contact: {
33
+ email: string;
34
+ firstName?: string;
35
+ lastName?: string;
36
+ source?: string;
37
+ subscribed?: boolean;
38
+ userGroup?: string;
39
+ userId?: string;
40
+ };
41
+ },
42
+ { id?: string; success: boolean },
43
+ Name
44
+ >;
45
+ batchCreateContacts: FunctionReference<
46
+ "action",
47
+ "internal",
48
+ {
49
+ apiKey: string;
50
+ contacts: Array<{
51
+ email: string;
52
+ firstName?: string;
53
+ lastName?: string;
54
+ source?: string;
55
+ subscribed?: boolean;
56
+ userGroup?: string;
57
+ userId?: string;
58
+ }>;
59
+ },
60
+ {
61
+ created?: number;
62
+ failed?: number;
63
+ results?: Array<{ email: string; error?: string; success: boolean }>;
64
+ success: boolean;
65
+ },
66
+ Name
67
+ >;
68
+ checkActorRateLimit: FunctionReference<
69
+ "query",
70
+ "internal",
71
+ { actorId: string; maxEmails: number; timeWindowMs: number },
72
+ {
73
+ allowed: boolean;
74
+ count: number;
75
+ limit: number;
76
+ retryAfter?: number;
77
+ timeWindowMs: number;
78
+ },
79
+ Name
80
+ >;
81
+ checkGlobalRateLimit: FunctionReference<
82
+ "query",
83
+ "internal",
84
+ { maxEmails: number; timeWindowMs: number },
85
+ {
86
+ allowed: boolean;
87
+ count: number;
88
+ limit: number;
89
+ timeWindowMs: number;
90
+ },
91
+ Name
92
+ >;
93
+ checkRecipientRateLimit: FunctionReference<
94
+ "query",
95
+ "internal",
96
+ { email: string; maxEmails: number; timeWindowMs: number },
97
+ {
98
+ allowed: boolean;
99
+ count: number;
100
+ limit: number;
101
+ retryAfter?: number;
102
+ timeWindowMs: number;
103
+ },
104
+ Name
105
+ >;
106
+ countContacts: FunctionReference<
107
+ "query",
108
+ "internal",
109
+ { source?: string; subscribed?: boolean; userGroup?: string },
110
+ number,
111
+ Name
112
+ >;
113
+ deleteContact: FunctionReference<
114
+ "action",
115
+ "internal",
116
+ { apiKey: string; email: string },
117
+ { success: boolean },
118
+ Name
119
+ >;
120
+ detectActorSpam: FunctionReference<
121
+ "query",
122
+ "internal",
123
+ { maxEmailsPerActor?: number; timeWindowMs?: number },
124
+ Array<{ actorId: string; count: number; timeWindowMs: number }>,
125
+ Name
126
+ >;
127
+ detectRapidFirePatterns: FunctionReference<
128
+ "query",
129
+ "internal",
130
+ { minEmailsInWindow?: number; timeWindowMs?: number },
131
+ Array<{
132
+ actorId?: string;
133
+ count: number;
134
+ email?: string;
135
+ firstTimestamp: number;
136
+ lastTimestamp: number;
137
+ timeWindowMs: number;
138
+ }>,
139
+ Name
140
+ >;
141
+ detectRecipientSpam: FunctionReference<
142
+ "query",
143
+ "internal",
144
+ { maxEmailsPerRecipient?: number; timeWindowMs?: number },
145
+ Array<{ count: number; email: string; timeWindowMs: number }>,
146
+ Name
147
+ >;
148
+ findContact: FunctionReference<
149
+ "action",
150
+ "internal",
151
+ { apiKey: string; email: string },
152
+ {
153
+ contact?: {
154
+ createdAt?: string | null;
155
+ email?: string | null;
156
+ firstName?: string | null;
157
+ id?: string | null;
158
+ lastName?: string | null;
159
+ source?: string | null;
160
+ subscribed?: boolean | null;
161
+ userGroup?: string | null;
162
+ userId?: string | null;
163
+ };
164
+ success: boolean;
165
+ },
166
+ Name
167
+ >;
168
+ getEmailStats: FunctionReference<
169
+ "query",
170
+ "internal",
171
+ { timeWindowMs?: number },
172
+ {
173
+ failedOperations: number;
174
+ operationsByType: Record<string, number>;
175
+ successfulOperations: number;
176
+ totalOperations: number;
177
+ uniqueActors: number;
178
+ uniqueRecipients: number;
179
+ },
180
+ Name
181
+ >;
182
+ listContacts: FunctionReference<
183
+ "query",
184
+ "internal",
185
+ {
186
+ limit?: number;
187
+ offset?: number;
188
+ source?: string;
189
+ subscribed?: boolean;
190
+ userGroup?: string;
191
+ },
192
+ {
193
+ contacts: Array<{
194
+ _id: string;
195
+ createdAt: number;
196
+ email: string;
197
+ firstName?: string;
198
+ lastName?: string;
199
+ loopsContactId?: string;
200
+ source?: string;
201
+ subscribed: boolean;
202
+ updatedAt: number;
203
+ userGroup?: string;
204
+ userId?: string;
205
+ }>;
206
+ hasMore: boolean;
207
+ limit: number;
208
+ offset: number;
209
+ total: number;
210
+ },
211
+ Name
212
+ >;
213
+ logEmailOperation: FunctionReference<
214
+ "mutation",
215
+ "internal",
216
+ {
217
+ actorId?: string;
218
+ campaignId?: string;
219
+ email: string;
220
+ eventName?: string;
221
+ loopId?: string;
222
+ messageId?: string;
223
+ metadata?: Record<string, any>;
224
+ operationType: "transactional" | "event" | "campaign" | "loop";
225
+ success: boolean;
226
+ transactionalId?: string;
227
+ },
228
+ any,
229
+ Name
230
+ >;
231
+ removeContact: FunctionReference<
232
+ "mutation",
233
+ "internal",
234
+ { email: string },
235
+ any,
236
+ Name
237
+ >;
238
+ resubscribeContact: FunctionReference<
239
+ "action",
240
+ "internal",
241
+ { apiKey: string; email: string },
242
+ { success: boolean },
243
+ Name
244
+ >;
245
+ sendEvent: FunctionReference<
246
+ "action",
247
+ "internal",
248
+ {
249
+ apiKey: string;
250
+ email: string;
251
+ eventName: string;
252
+ eventProperties?: Record<string, any>;
253
+ },
254
+ { success: boolean },
255
+ Name
256
+ >;
257
+ sendTransactional: FunctionReference<
258
+ "action",
259
+ "internal",
260
+ {
261
+ apiKey: string;
262
+ dataVariables?: Record<string, any>;
263
+ email: string;
264
+ transactionalId: string;
265
+ },
266
+ { messageId?: string; success: boolean },
267
+ Name
268
+ >;
269
+ storeContact: FunctionReference<
270
+ "mutation",
271
+ "internal",
272
+ {
273
+ email: string;
274
+ firstName?: string;
275
+ lastName?: string;
276
+ loopsContactId?: string;
277
+ source?: string;
278
+ subscribed?: boolean;
279
+ userGroup?: string;
280
+ userId?: string;
281
+ },
282
+ any,
283
+ Name
284
+ >;
285
+ triggerLoop: FunctionReference<
286
+ "action",
287
+ "internal",
288
+ {
289
+ apiKey: string;
290
+ dataVariables?: Record<string, any>;
291
+ email: string;
292
+ eventName?: string;
293
+ loopId: string;
294
+ },
295
+ { success: boolean; warning?: string },
296
+ Name
297
+ >;
298
+ unsubscribeContact: FunctionReference<
299
+ "action",
300
+ "internal",
301
+ { apiKey: string; email: string },
302
+ { success: boolean },
303
+ Name
304
+ >;
305
+ updateContact: FunctionReference<
306
+ "action",
307
+ "internal",
308
+ {
309
+ apiKey: string;
310
+ dataVariables?: Record<string, any>;
311
+ email: string;
312
+ firstName?: string;
313
+ lastName?: string;
314
+ source?: string;
315
+ subscribed?: boolean;
316
+ userGroup?: string;
317
+ userId?: string;
318
+ },
319
+ { success: boolean },
320
+ Name
321
+ >;
322
+ };
323
+ };
@@ -38,7 +38,7 @@ export type Doc<TableName extends TableNames> = DocumentByName<
38
38
  * Convex documents are uniquely identified by their `Id`, which is accessible
39
39
  * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
40
  *
41
- * Documents can be loaded using `db.get(id)` in query and mutation functions.
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
42
  *
43
43
  * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
44
  * strings when type checking.
@@ -0,0 +1,161 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ type GenericCtx =
111
+ | GenericActionCtx<DataModel>
112
+ | GenericMutationCtx<DataModel>
113
+ | GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex query functions.
117
+ *
118
+ * The query context is passed as the first argument to any Convex query
119
+ * function run on the server.
120
+ *
121
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
122
+ */
123
+ export type QueryCtx = GenericQueryCtx<DataModel>;
124
+
125
+ /**
126
+ * A set of services for use within Convex mutation functions.
127
+ *
128
+ * The mutation context is passed as the first argument to any Convex mutation
129
+ * function run on the server.
130
+ *
131
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
132
+ */
133
+ export type MutationCtx = GenericMutationCtx<DataModel>;
134
+
135
+ /**
136
+ * A set of services for use within Convex action functions.
137
+ *
138
+ * The action context is passed as the first argument to any Convex action
139
+ * function run on the server.
140
+ */
141
+ export type ActionCtx = GenericActionCtx<DataModel>;
142
+
143
+ /**
144
+ * An interface to read from the database within Convex query functions.
145
+ *
146
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
147
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
148
+ * building a query.
149
+ */
150
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
151
+
152
+ /**
153
+ * An interface to read from and write to the database within Convex mutation
154
+ * functions.
155
+ *
156
+ * Convex guarantees that all writes within a single mutation are
157
+ * executed atomically, so you never have to worry about partial writes leaving
158
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
159
+ * for the guarantees Convex provides your functions.
160
+ */
161
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -1,32 +1,5 @@
1
1
  import { defineComponent } from "convex/server";
2
- import { api } from "./_generated/api";
3
2
 
4
3
  const component = defineComponent("loops");
5
4
 
6
- type ExportableComponent = typeof component & {
7
- export: (apiRef: typeof api, functions: Record<string, unknown>) => void;
8
- };
9
-
10
- (component as ExportableComponent).export(api, {
11
- addContact: api.lib.addContact,
12
- updateContact: api.lib.updateContact,
13
- findContact: api.lib.findContact,
14
- batchCreateContacts: api.lib.batchCreateContacts,
15
- unsubscribeContact: api.lib.unsubscribeContact,
16
- resubscribeContact: api.lib.resubscribeContact,
17
- countContacts: api.lib.countContacts,
18
- listContacts: api.lib.listContacts,
19
- sendTransactional: api.lib.sendTransactional,
20
- sendEvent: api.lib.sendEvent,
21
- triggerLoop: api.lib.triggerLoop,
22
- deleteContact: api.lib.deleteContact,
23
- detectRecipientSpam: api.lib.detectRecipientSpam,
24
- detectActorSpam: api.lib.detectActorSpam,
25
- getEmailStats: api.lib.getEmailStats,
26
- detectRapidFirePatterns: api.lib.detectRapidFirePatterns,
27
- checkRecipientRateLimit: api.lib.checkRecipientRateLimit,
28
- checkActorRateLimit: api.lib.checkActorRateLimit,
29
- checkGlobalRateLimit: api.lib.checkGlobalRateLimit,
30
- });
31
-
32
5
  export default component;
@@ -1,4 +1,4 @@
1
- import { type HeadersInitParam } from "../types";
1
+ import type { HeadersInitParam } from "../types";
2
2
 
3
3
  const allowedOrigin =
4
4
  process.env.CONVEX_URL ??
@@ -82,7 +82,7 @@ export const emptyResponse = (init?: ResponseInit) => {
82
82
  export const readJsonBody = async <T>(request: Request): Promise<T> => {
83
83
  try {
84
84
  return (await request.json()) as T;
85
- } catch (error) {
85
+ } catch (_error) {
86
86
  throw new Error("Invalid JSON body");
87
87
  }
88
88
  };
@@ -22,10 +22,6 @@ import { httpAction } from "./_generated/server";
22
22
 
23
23
  const http = httpRouter();
24
24
 
25
- const allowedOrigin =
26
- process.env.LOOPS_HTTP_ALLOWED_ORIGIN ?? process.env.CLIENT_ORIGIN ?? "*";
27
-
28
-
29
25
  http.route({
30
26
  pathPrefix: "/loops/",
31
27
  method: "OPTIONS",
@@ -117,6 +117,10 @@ export const logEmailOperation = zm({
117
117
  /**
118
118
  * Count contacts in the database
119
119
  * Can filter by audience criteria (userGroup, source, subscribed status)
120
+ *
121
+ * Note: When multiple filters are provided, only one index can be used.
122
+ * Additional filters are applied in-memory, which is efficient for small result sets.
123
+ * For large contact lists with multiple filters, consider using a composite index.
120
124
  */
121
125
  export const countContacts = zq({
122
126
  args: z.object({
@@ -126,7 +130,10 @@ export const countContacts = zq({
126
130
  }),
127
131
  returns: z.number(),
128
132
  handler: async (ctx, args) => {
133
+ // Build query using the most selective index available
134
+ // Priority: userGroup > source > subscribed
129
135
  let contacts: Doc<"contacts">[];
136
+
130
137
  if (args.userGroup !== undefined) {
131
138
  contacts = await ctx.db
132
139
  .query("contacts")
@@ -146,17 +153,32 @@ export const countContacts = zq({
146
153
  contacts = await ctx.db.query("contacts").collect();
147
154
  }
148
155
 
149
- if (args.userGroup !== undefined && contacts) {
150
- contacts = contacts.filter((c) => c.userGroup === args.userGroup);
151
- }
152
- if (args.source !== undefined && contacts) {
153
- contacts = contacts.filter((c) => c.source === args.source);
154
- }
155
- if (args.subscribed !== undefined && contacts) {
156
- contacts = contacts.filter((c) => c.subscribed === args.subscribed);
156
+ // Apply additional filters if multiple criteria were provided
157
+ // This avoids redundant filtering when only one filter was used
158
+ const needsFiltering =
159
+ (args.userGroup !== undefined ? 1 : 0) +
160
+ (args.source !== undefined ? 1 : 0) +
161
+ (args.subscribed !== undefined ? 1 : 0) >
162
+ 1;
163
+
164
+ if (!needsFiltering) {
165
+ return contacts.length;
157
166
  }
158
167
 
159
- return contacts.length;
168
+ const filtered = contacts.filter((c) => {
169
+ if (args.userGroup !== undefined && c.userGroup !== args.userGroup) {
170
+ return false;
171
+ }
172
+ if (args.source !== undefined && c.source !== args.source) {
173
+ return false;
174
+ }
175
+ if (args.subscribed !== undefined && c.subscribed !== args.subscribed) {
176
+ return false;
177
+ }
178
+ return true;
179
+ });
180
+
181
+ return filtered.length;
160
182
  },
161
183
  });
162
184
 
@@ -164,6 +186,9 @@ export const countContacts = zq({
164
186
  * List contacts from the database with pagination
165
187
  * Can filter by audience criteria (userGroup, source, subscribed status)
166
188
  * Returns actual contact data, not just a count
189
+ *
190
+ * Note: When multiple filters are provided, only one index can be used.
191
+ * Additional filters are applied in-memory before pagination.
167
192
  */
168
193
  export const listContacts = zq({
169
194
  args: z.object({
@@ -195,9 +220,9 @@ export const listContacts = zq({
195
220
  hasMore: z.boolean(),
196
221
  }),
197
222
  handler: async (ctx, args) => {
223
+ // Build query using the most selective index available
198
224
  let allContacts: Doc<"contacts">[];
199
225
 
200
- // Get all contacts matching the filters
201
226
  if (args.userGroup !== undefined) {
202
227
  allContacts = await ctx.db
203
228
  .query("contacts")
@@ -217,15 +242,26 @@ export const listContacts = zq({
217
242
  allContacts = await ctx.db.query("contacts").collect();
218
243
  }
219
244
 
220
- // Apply additional filters (for cases where we need to filter by multiple criteria)
221
- if (args.userGroup !== undefined && allContacts) {
222
- allContacts = allContacts.filter((c) => c.userGroup === args.userGroup);
223
- }
224
- if (args.source !== undefined && allContacts) {
225
- allContacts = allContacts.filter((c) => c.source === args.source);
226
- }
227
- if (args.subscribed !== undefined && allContacts) {
228
- allContacts = allContacts.filter((c) => c.subscribed === args.subscribed);
245
+ // Apply additional filters if multiple criteria were provided
246
+ const needsFiltering =
247
+ (args.userGroup !== undefined ? 1 : 0) +
248
+ (args.source !== undefined ? 1 : 0) +
249
+ (args.subscribed !== undefined ? 1 : 0) >
250
+ 1;
251
+
252
+ if (needsFiltering) {
253
+ allContacts = allContacts.filter((c) => {
254
+ if (args.userGroup !== undefined && c.userGroup !== args.userGroup) {
255
+ return false;
256
+ }
257
+ if (args.source !== undefined && c.source !== args.source) {
258
+ return false;
259
+ }
260
+ if (args.subscribed !== undefined && c.subscribed !== args.subscribed) {
261
+ return false;
262
+ }
263
+ return true;
264
+ });
229
265
  }
230
266
 
231
267
  // Sort by createdAt (newest first)
@@ -488,7 +524,7 @@ export const sendEvent = za({
488
524
  returns: z.object({
489
525
  success: z.boolean(),
490
526
  }),
491
- handler: async (_ctx, args) => {
527
+ handler: async (ctx, args) => {
492
528
  const response = await loopsFetch(args.apiKey, "/events/send", {
493
529
  method: "POST",
494
530
  json: {
@@ -501,9 +537,22 @@ export const sendEvent = za({
501
537
  if (!response.ok) {
502
538
  const errorText = await response.text();
503
539
  console.error(`Loops API error [${response.status}]:`, errorText);
540
+ await ctx.runMutation(internalLib.logEmailOperation, {
541
+ operationType: "event",
542
+ email: args.email,
543
+ success: false,
544
+ eventName: args.eventName,
545
+ });
504
546
  throw sanitizeLoopsError(response.status, errorText);
505
547
  }
506
548
 
549
+ await ctx.runMutation(internalLib.logEmailOperation, {
550
+ operationType: "event",
551
+ email: args.email,
552
+ success: true,
553
+ eventName: args.eventName,
554
+ });
555
+
507
556
  return { success: true };
508
557
  },
509
558
  });