@iann29/rastro 0.1.0-alpha.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 (126) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +352 -0
  3. package/assets/rastro-live-atlas.png +0 -0
  4. package/dist/client/_generated/_ignore.d.ts +1 -0
  5. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  6. package/dist/client/_generated/_ignore.js +3 -0
  7. package/dist/client/_generated/_ignore.js.map +1 -0
  8. package/dist/client/index.d.ts +960 -0
  9. package/dist/client/index.d.ts.map +1 -0
  10. package/dist/client/index.js +591 -0
  11. package/dist/client/index.js.map +1 -0
  12. package/dist/component/_generated/api.d.ts +60 -0
  13. package/dist/component/_generated/api.d.ts.map +1 -0
  14. package/dist/component/_generated/api.js +31 -0
  15. package/dist/component/_generated/api.js.map +1 -0
  16. package/dist/component/_generated/component.d.ts +569 -0
  17. package/dist/component/_generated/component.d.ts.map +1 -0
  18. package/dist/component/_generated/component.js +11 -0
  19. package/dist/component/_generated/component.js.map +1 -0
  20. package/dist/component/_generated/dataModel.d.ts +46 -0
  21. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  22. package/dist/component/_generated/dataModel.js +11 -0
  23. package/dist/component/_generated/dataModel.js.map +1 -0
  24. package/dist/component/_generated/server.d.ts +133 -0
  25. package/dist/component/_generated/server.d.ts.map +1 -0
  26. package/dist/component/_generated/server.js +80 -0
  27. package/dist/component/_generated/server.js.map +1 -0
  28. package/dist/component/affiliates.d.ts +28 -0
  29. package/dist/component/affiliates.d.ts.map +1 -0
  30. package/dist/component/affiliates.js +110 -0
  31. package/dist/component/affiliates.js.map +1 -0
  32. package/dist/component/constants.d.ts +28 -0
  33. package/dist/component/constants.d.ts.map +1 -0
  34. package/dist/component/constants.js +28 -0
  35. package/dist/component/constants.js.map +1 -0
  36. package/dist/component/convex.config.d.ts +3 -0
  37. package/dist/component/convex.config.d.ts.map +1 -0
  38. package/dist/component/convex.config.js +3 -0
  39. package/dist/component/convex.config.js.map +1 -0
  40. package/dist/component/errors.d.ts +3 -0
  41. package/dist/component/errors.d.ts.map +1 -0
  42. package/dist/component/errors.js +5 -0
  43. package/dist/component/errors.js.map +1 -0
  44. package/dist/component/funnels.d.ts +36 -0
  45. package/dist/component/funnels.d.ts.map +1 -0
  46. package/dist/component/funnels.js +117 -0
  47. package/dist/component/funnels.js.map +1 -0
  48. package/dist/component/goals.d.ts +30 -0
  49. package/dist/component/goals.d.ts.map +1 -0
  50. package/dist/component/goals.js +110 -0
  51. package/dist/component/goals.js.map +1 -0
  52. package/dist/component/guards.d.ts +2 -0
  53. package/dist/component/guards.d.ts.map +1 -0
  54. package/dist/component/guards.js +4 -0
  55. package/dist/component/guards.js.map +1 -0
  56. package/dist/component/http.d.ts +3 -0
  57. package/dist/component/http.d.ts.map +1 -0
  58. package/dist/component/http.js +270 -0
  59. package/dist/component/http.js.map +1 -0
  60. package/dist/component/ingest.d.ts +51 -0
  61. package/dist/component/ingest.d.ts.map +1 -0
  62. package/dist/component/ingest.js +991 -0
  63. package/dist/component/ingest.js.map +1 -0
  64. package/dist/component/live.d.ts +9 -0
  65. package/dist/component/live.d.ts.map +1 -0
  66. package/dist/component/live.js +36 -0
  67. package/dist/component/live.js.map +1 -0
  68. package/dist/component/reports.d.ts +330 -0
  69. package/dist/component/reports.d.ts.map +1 -0
  70. package/dist/component/reports.js +595 -0
  71. package/dist/component/reports.js.map +1 -0
  72. package/dist/component/retention.d.ts +10 -0
  73. package/dist/component/retention.d.ts.map +1 -0
  74. package/dist/component/retention.js +107 -0
  75. package/dist/component/retention.js.map +1 -0
  76. package/dist/component/sanitize.d.ts +20 -0
  77. package/dist/component/sanitize.d.ts.map +1 -0
  78. package/dist/component/sanitize.js +269 -0
  79. package/dist/component/sanitize.js.map +1 -0
  80. package/dist/component/schema.d.ts +517 -0
  81. package/dist/component/schema.d.ts.map +1 -0
  82. package/dist/component/schema.js +209 -0
  83. package/dist/component/schema.js.map +1 -0
  84. package/dist/component/sites.d.ts +54 -0
  85. package/dist/component/sites.d.ts.map +1 -0
  86. package/dist/component/sites.js +164 -0
  87. package/dist/component/sites.js.map +1 -0
  88. package/dist/component/validators.d.ts +377 -0
  89. package/dist/component/validators.d.ts.map +1 -0
  90. package/dist/component/validators.js +176 -0
  91. package/dist/component/validators.js.map +1 -0
  92. package/dist/react/index.d.ts +40 -0
  93. package/dist/react/index.d.ts.map +1 -0
  94. package/dist/react/index.js +31 -0
  95. package/dist/react/index.js.map +1 -0
  96. package/dist/tracker/generated.d.ts +5 -0
  97. package/dist/tracker/generated.d.ts.map +1 -0
  98. package/dist/tracker/generated.js +6 -0
  99. package/dist/tracker/generated.js.map +1 -0
  100. package/dist/tracker/tracker.d.ts +27 -0
  101. package/dist/tracker/tracker.d.ts.map +1 -0
  102. package/dist/tracker/tracker.js +108 -0
  103. package/dist/tracker/tracker.js.map +1 -0
  104. package/dist/tracker.min.js +1 -0
  105. package/package.json +121 -0
  106. package/src/component/_generated/api.ts +76 -0
  107. package/src/component/_generated/component.ts +706 -0
  108. package/src/component/_generated/dataModel.ts +60 -0
  109. package/src/component/_generated/server.ts +169 -0
  110. package/src/component/affiliates.ts +119 -0
  111. package/src/component/constants.ts +28 -0
  112. package/src/component/convex.config.ts +3 -0
  113. package/src/component/errors.ts +20 -0
  114. package/src/component/funnels.ts +134 -0
  115. package/src/component/goals.ts +122 -0
  116. package/src/component/guards.ts +3 -0
  117. package/src/component/http.ts +301 -0
  118. package/src/component/ingest.ts +1364 -0
  119. package/src/component/live.ts +36 -0
  120. package/src/component/reports.ts +720 -0
  121. package/src/component/retention.ts +180 -0
  122. package/src/component/sanitize.ts +278 -0
  123. package/src/component/schema.ts +232 -0
  124. package/src/component/sites.ts +188 -0
  125. package/src/component/validators.ts +226 -0
  126. package/src/test.ts +19 -0
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,169 @@
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
+ * Typesafe environment variables.
35
+ *
36
+ * This includes platform-provided env vars and any variables declared in
37
+ * `convex.config.ts`.
38
+ */
39
+ type Env = {
40
+ readonly CONVEX_CLOUD_URL: string;
41
+ readonly CONVEX_SITE_URL: string;
42
+ };
43
+
44
+ /**
45
+ * Define a query in this Convex app's public API.
46
+ *
47
+ * This function will be allowed to read your Convex database and will be accessible from the client.
48
+ *
49
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
50
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
51
+ */
52
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
53
+
54
+ /**
55
+ * Define a query that is only accessible from other Convex functions (but not from the client).
56
+ *
57
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
58
+ *
59
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
60
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
63
+ internalQueryGeneric;
64
+
65
+ /**
66
+ * Define a mutation in this Convex app's public API.
67
+ *
68
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
69
+ *
70
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
71
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
72
+ */
73
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
74
+
75
+ /**
76
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
77
+ *
78
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
79
+ *
80
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
81
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
82
+ */
83
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
84
+ internalMutationGeneric;
85
+
86
+ /**
87
+ * Define an action in this Convex app's public API.
88
+ *
89
+ * An action is a function which can execute any JavaScript code, including non-deterministic
90
+ * code and code with side-effects, like calling third-party services.
91
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
92
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
93
+ *
94
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
95
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
96
+ */
97
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
98
+
99
+ /**
100
+ * Define an action that is only accessible from other Convex functions (but not from the client).
101
+ *
102
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
103
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
104
+ */
105
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
106
+ internalActionGeneric;
107
+
108
+ /**
109
+ * Define an HTTP action.
110
+ *
111
+ * The wrapped function will be used to respond to HTTP requests received
112
+ * by a Convex deployment if the requests matches the path and method where
113
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
114
+ *
115
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
116
+ * and a Fetch API `Request` object as its second.
117
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
118
+ */
119
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
120
+ export const env: Env = (globalThis as unknown as { process: { env: Env } })
121
+ .process.env;
122
+
123
+ /**
124
+ * A set of services for use within Convex query functions.
125
+ *
126
+ * The query context is passed as the first argument to any Convex query
127
+ * function run on the server.
128
+ *
129
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
130
+ */
131
+ export type QueryCtx = GenericQueryCtx<DataModel>;
132
+
133
+ /**
134
+ * A set of services for use within Convex mutation functions.
135
+ *
136
+ * The mutation context is passed as the first argument to any Convex mutation
137
+ * function run on the server.
138
+ *
139
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
140
+ */
141
+ export type MutationCtx = GenericMutationCtx<DataModel>;
142
+
143
+ /**
144
+ * A set of services for use within Convex action functions.
145
+ *
146
+ * The action context is passed as the first argument to any Convex action
147
+ * function run on the server.
148
+ */
149
+ export type ActionCtx = GenericActionCtx<DataModel>;
150
+
151
+ /**
152
+ * An interface to read from the database within Convex query functions.
153
+ *
154
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
155
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
156
+ * building a query.
157
+ */
158
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
159
+
160
+ /**
161
+ * An interface to read from and write to the database within Convex mutation
162
+ * functions.
163
+ *
164
+ * Convex guarantees that all writes within a single mutation are
165
+ * executed atomically, so you never have to worry about partial writes leaving
166
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
167
+ * for the guarantees Convex provides your functions.
168
+ */
169
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,119 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server.js";
3
+ import { MAX_AFFILIATES_PER_SITE } from "./constants.js";
4
+ import { fail } from "./errors.js";
5
+ import { cleanString, sanitizeSlug } from "./sanitize.js";
6
+ import { affiliateFieldsValidator } from "./validators.js";
7
+
8
+ const affiliateDocumentValidator = affiliateFieldsValidator.extend({
9
+ _id: v.id("affiliates"),
10
+ _creationTime: v.number(),
11
+ });
12
+
13
+ export const upsert = mutation({
14
+ args: {
15
+ siteId: v.id("sites"),
16
+ affiliateId: v.optional(v.id("affiliates")),
17
+ slug: v.string(),
18
+ name: v.string(),
19
+ commissionBps: v.number(),
20
+ attributionWindowDays: v.number(),
21
+ active: v.optional(v.boolean()),
22
+ },
23
+ returns: v.id("affiliates"),
24
+ handler: async (ctx, args) => {
25
+ if (!(await ctx.db.get("sites", args.siteId))) fail("NOT_FOUND", "site not found");
26
+ if (!Number.isSafeInteger(args.commissionBps) || args.commissionBps < 0 || args.commissionBps > 10_000) {
27
+ fail("INVALID_ARGUMENT", "commissionBps must be an integer between 0 and 10000");
28
+ }
29
+ if (
30
+ !Number.isSafeInteger(args.attributionWindowDays) ||
31
+ args.attributionWindowDays < 1 ||
32
+ args.attributionWindowDays > 365
33
+ ) {
34
+ fail("INVALID_ARGUMENT", "attributionWindowDays must be an integer between 1 and 365");
35
+ }
36
+ let slug: string;
37
+ try {
38
+ slug = sanitizeSlug(args.slug);
39
+ } catch (error) {
40
+ fail(
41
+ "INVALID_ARGUMENT",
42
+ error instanceof Error ? error.message : "invalid affiliate",
43
+ );
44
+ }
45
+ const name = cleanString(args.name, 120);
46
+ if (!name) fail("INVALID_ARGUMENT", "affiliate name is required");
47
+
48
+ const existingBySlug = await ctx.db
49
+ .query("affiliates")
50
+ .withIndex("by_siteId_and_slug", (range) =>
51
+ range.eq("siteId", args.siteId).eq("slug", slug),
52
+ )
53
+ .unique();
54
+ const affiliateId = args.affiliateId ?? existingBySlug?._id;
55
+ if (args.affiliateId && existingBySlug && existingBySlug._id !== args.affiliateId) {
56
+ fail("CONFLICT", "another affiliate already uses this slug");
57
+ }
58
+ const now = Date.now();
59
+ if (affiliateId) {
60
+ const affiliate = await ctx.db.get("affiliates", affiliateId);
61
+ if (!affiliate || affiliate.siteId !== args.siteId) {
62
+ fail("NOT_FOUND", "affiliate not found");
63
+ }
64
+ await ctx.db.patch("affiliates", affiliateId, {
65
+ slug,
66
+ name,
67
+ commissionBps: args.commissionBps,
68
+ attributionWindowDays: args.attributionWindowDays,
69
+ active: args.active ?? affiliate.active,
70
+ updatedAt: now,
71
+ });
72
+ return affiliateId;
73
+ }
74
+
75
+ const affiliates = await ctx.db
76
+ .query("affiliates")
77
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
78
+ .take(MAX_AFFILIATES_PER_SITE + 1);
79
+ if (affiliates.length >= MAX_AFFILIATES_PER_SITE) {
80
+ fail("LIMIT_EXCEEDED", "affiliate limit reached", {
81
+ limit: MAX_AFFILIATES_PER_SITE,
82
+ });
83
+ }
84
+ return await ctx.db.insert("affiliates", {
85
+ siteId: args.siteId,
86
+ slug,
87
+ name,
88
+ commissionBps: args.commissionBps,
89
+ attributionWindowDays: args.attributionWindowDays,
90
+ active: args.active ?? true,
91
+ createdAt: now,
92
+ updatedAt: now,
93
+ });
94
+ },
95
+ });
96
+
97
+ export const list = query({
98
+ args: { siteId: v.id("sites") },
99
+ returns: v.array(affiliateDocumentValidator),
100
+ handler: async (ctx, args) => {
101
+ return await ctx.db
102
+ .query("affiliates")
103
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
104
+ .take(MAX_AFFILIATES_PER_SITE);
105
+ },
106
+ });
107
+
108
+ export const remove = mutation({
109
+ args: { siteId: v.id("sites"), affiliateId: v.id("affiliates") },
110
+ returns: v.null(),
111
+ handler: async (ctx, args) => {
112
+ const affiliate = await ctx.db.get("affiliates", args.affiliateId);
113
+ if (!affiliate || affiliate.siteId !== args.siteId) {
114
+ fail("NOT_FOUND", "affiliate not found");
115
+ }
116
+ await ctx.db.delete("affiliates", args.affiliateId);
117
+ return null;
118
+ },
119
+ });
@@ -0,0 +1,28 @@
1
+ export const MAX_BATCH_EVENTS = 20;
2
+ export const MAX_BATCH_BYTES = 64 * 1024;
3
+ export const MAX_EVENTS_PER_SESSION_WINDOW = 120;
4
+ export const RATE_LIMIT_WINDOW_MS = 60_000;
5
+ export const MAX_BYTES_PER_SESSION_WINDOW = 256 * 1024;
6
+ export const SITE_INGEST_SHARDS = 8;
7
+ export const MAX_SITE_EVENTS_PER_SHARD_WINDOW = 120;
8
+ export const MAX_SITE_BYTES_PER_SHARD_WINDOW = 512 * 1024;
9
+ export const LIVE_SESSION_TTL_MS = 60_000;
10
+ export const AGGREGATE_SHARDS = 16;
11
+ export const DIMENSION_SLOTS = 16;
12
+ export const MAX_SITE_DOMAINS = 32;
13
+ export const MAX_SITES_PER_OWNER = 100;
14
+ export const MAX_GOALS_PER_SITE = 50;
15
+ export const MAX_FUNNELS_PER_SITE = 20;
16
+ export const MAX_AFFILIATES_PER_SITE = 100;
17
+ export const MAX_FUNNEL_STEPS = 10;
18
+ export const MAX_PROPERTIES = 16;
19
+ export const MAX_REPORT_SITES = 10;
20
+ export const MAX_REPORT_RANGE_DAYS = 366;
21
+ export const MAX_LIVE_VISITORS = 500;
22
+ export const MAX_JOURNEY_EVENTS = 500;
23
+ export const MAX_RETENTION_BATCH = 500;
24
+ export const MAX_OVERVIEW_AGGREGATE_ROWS = 12_000;
25
+
26
+ export const DAY_MS = 86_400_000;
27
+ export const HOUR_MS = 3_600_000;
28
+ export const MAX_MANUAL_PAGINATION_OFFSET = 1_000;
@@ -0,0 +1,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("rastroAnalytics");
@@ -0,0 +1,20 @@
1
+ import { ConvexError } from "convex/values";
2
+
3
+ export type RastroErrorCode =
4
+ | "NOT_FOUND"
5
+ | "INVALID_ARGUMENT"
6
+ | "INVALID_SITE"
7
+ | "ORIGIN_NOT_ALLOWED"
8
+ | "BATCH_TOO_LARGE"
9
+ | "LIMIT_EXCEEDED"
10
+ | "CONFLICT"
11
+ | "CURRENCY_MISMATCH"
12
+ | "RATE_LIMITED";
13
+
14
+ export function fail(
15
+ code: RastroErrorCode,
16
+ message: string,
17
+ details?: Record<string, string | number | boolean | null>,
18
+ ): never {
19
+ throw new ConvexError({ code, message, details: details ?? null });
20
+ }
@@ -0,0 +1,134 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server.js";
3
+ import {
4
+ MAX_FUNNELS_PER_SITE,
5
+ MAX_FUNNEL_STEPS,
6
+ } from "./constants.js";
7
+ import { fail } from "./errors.js";
8
+ import { cleanString, sanitizePath, sanitizeSlug } from "./sanitize.js";
9
+ import {
10
+ funnelFieldsValidator,
11
+ funnelStepValidator,
12
+ } from "./validators.js";
13
+
14
+ const funnelDocumentValidator = funnelFieldsValidator.extend({
15
+ _id: v.id("funnels"),
16
+ _creationTime: v.number(),
17
+ });
18
+
19
+ export const upsert = mutation({
20
+ args: {
21
+ siteId: v.id("sites"),
22
+ funnelId: v.optional(v.id("funnels")),
23
+ key: v.string(),
24
+ name: v.string(),
25
+ steps: v.array(funnelStepValidator),
26
+ conversionWindowMs: v.number(),
27
+ active: v.optional(v.boolean()),
28
+ },
29
+ returns: v.id("funnels"),
30
+ handler: async (ctx, args) => {
31
+ if (!(await ctx.db.get("sites", args.siteId))) fail("NOT_FOUND", "site not found");
32
+ if (args.steps.length < 2 || args.steps.length > MAX_FUNNEL_STEPS) {
33
+ fail("INVALID_ARGUMENT", `funnels require 2-${MAX_FUNNEL_STEPS} steps`);
34
+ }
35
+ if (
36
+ !Number.isSafeInteger(args.conversionWindowMs) ||
37
+ args.conversionWindowMs < 60_000 ||
38
+ args.conversionWindowMs > 90 * 86_400_000
39
+ ) {
40
+ fail("INVALID_ARGUMENT", "conversionWindowMs must be between one minute and 90 days");
41
+ }
42
+ let key: string;
43
+ let steps: Array<{
44
+ type: "pageview" | "custom";
45
+ value: string;
46
+ name: string;
47
+ }>;
48
+ try {
49
+ key = sanitizeSlug(args.key, "key");
50
+ steps = args.steps.map((step) => {
51
+ const stepName = cleanString(step.name, 80);
52
+ const value = step.type === "pageview"
53
+ ? sanitizePath(step.value)
54
+ : cleanString(step.value, 80);
55
+ if (!stepName || !value) {
56
+ throw new Error("funnel steps require name and value");
57
+ }
58
+ return { type: step.type, value, name: stepName };
59
+ });
60
+ } catch (error) {
61
+ fail(
62
+ "INVALID_ARGUMENT",
63
+ error instanceof Error ? error.message : "invalid funnel",
64
+ );
65
+ }
66
+ const name = cleanString(args.name, 120);
67
+ if (!name) fail("INVALID_ARGUMENT", "funnel name is required");
68
+
69
+ const existingByKey = await ctx.db
70
+ .query("funnels")
71
+ .withIndex("by_siteId_and_key", (range) =>
72
+ range.eq("siteId", args.siteId).eq("key", key),
73
+ )
74
+ .unique();
75
+ const funnelId = args.funnelId ?? existingByKey?._id;
76
+ if (args.funnelId && existingByKey && existingByKey._id !== args.funnelId) {
77
+ fail("CONFLICT", "another funnel already uses this key");
78
+ }
79
+ const now = Date.now();
80
+ if (funnelId) {
81
+ const funnel = await ctx.db.get("funnels", funnelId);
82
+ if (!funnel || funnel.siteId !== args.siteId) fail("NOT_FOUND", "funnel not found");
83
+ await ctx.db.patch("funnels", funnelId, {
84
+ key,
85
+ name,
86
+ steps,
87
+ conversionWindowMs: args.conversionWindowMs,
88
+ active: args.active ?? funnel.active,
89
+ updatedAt: now,
90
+ });
91
+ return funnelId;
92
+ }
93
+
94
+ const funnels = await ctx.db
95
+ .query("funnels")
96
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
97
+ .take(MAX_FUNNELS_PER_SITE + 1);
98
+ if (funnels.length >= MAX_FUNNELS_PER_SITE) {
99
+ fail("LIMIT_EXCEEDED", "funnel limit reached", { limit: MAX_FUNNELS_PER_SITE });
100
+ }
101
+ return await ctx.db.insert("funnels", {
102
+ siteId: args.siteId,
103
+ key,
104
+ name,
105
+ steps,
106
+ conversionWindowMs: args.conversionWindowMs,
107
+ active: args.active ?? true,
108
+ createdAt: now,
109
+ updatedAt: now,
110
+ });
111
+ },
112
+ });
113
+
114
+ export const list = query({
115
+ args: { siteId: v.id("sites") },
116
+ returns: v.array(funnelDocumentValidator),
117
+ handler: async (ctx, args) => {
118
+ return await ctx.db
119
+ .query("funnels")
120
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
121
+ .take(MAX_FUNNELS_PER_SITE);
122
+ },
123
+ });
124
+
125
+ export const remove = mutation({
126
+ args: { siteId: v.id("sites"), funnelId: v.id("funnels") },
127
+ returns: v.null(),
128
+ handler: async (ctx, args) => {
129
+ const funnel = await ctx.db.get("funnels", args.funnelId);
130
+ if (!funnel || funnel.siteId !== args.siteId) fail("NOT_FOUND", "funnel not found");
131
+ await ctx.db.delete("funnels", args.funnelId);
132
+ return null;
133
+ },
134
+ });
@@ -0,0 +1,122 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server.js";
3
+ import { MAX_GOALS_PER_SITE } from "./constants.js";
4
+ import { fail } from "./errors.js";
5
+ import {
6
+ cleanString,
7
+ isValidMoney,
8
+ sanitizePath,
9
+ sanitizeSlug,
10
+ } from "./sanitize.js";
11
+ import {
12
+ goalFieldsValidator,
13
+ goalMatchTypeValidator,
14
+ } from "./validators.js";
15
+
16
+ const goalDocumentValidator = goalFieldsValidator.extend({
17
+ _id: v.id("goals"),
18
+ _creationTime: v.number(),
19
+ });
20
+
21
+ export const upsert = mutation({
22
+ args: {
23
+ siteId: v.id("sites"),
24
+ goalId: v.optional(v.id("goals")),
25
+ key: v.string(),
26
+ name: v.string(),
27
+ matchType: goalMatchTypeValidator,
28
+ matchValue: v.string(),
29
+ valueCents: v.optional(v.number()),
30
+ active: v.optional(v.boolean()),
31
+ },
32
+ returns: v.id("goals"),
33
+ handler: async (ctx, args) => {
34
+ if (!(await ctx.db.get("sites", args.siteId))) fail("NOT_FOUND", "site not found");
35
+ let key: string;
36
+ let matchValue: string;
37
+ try {
38
+ key = sanitizeSlug(args.key, "key");
39
+ matchValue = args.matchType === "pageview"
40
+ ? sanitizePath(args.matchValue)
41
+ : cleanString(args.matchValue, 80);
42
+ } catch (error) {
43
+ fail(
44
+ "INVALID_ARGUMENT",
45
+ error instanceof Error ? error.message : "invalid goal",
46
+ );
47
+ }
48
+ const name = cleanString(args.name, 120);
49
+ if (!name) fail("INVALID_ARGUMENT", "goal name is required");
50
+ if (!matchValue) fail("INVALID_ARGUMENT", "goal match value is required");
51
+ if (args.valueCents !== undefined && !isValidMoney(args.valueCents)) {
52
+ fail("INVALID_ARGUMENT", "valueCents must be an integer between 0 and 1000000000");
53
+ }
54
+
55
+ const existingByKey = await ctx.db
56
+ .query("goals")
57
+ .withIndex("by_siteId_and_key", (range) =>
58
+ range.eq("siteId", args.siteId).eq("key", key),
59
+ )
60
+ .unique();
61
+ const goalId = args.goalId ?? existingByKey?._id;
62
+ if (args.goalId && existingByKey && existingByKey._id !== args.goalId) {
63
+ fail("CONFLICT", "another goal already uses this key");
64
+ }
65
+ const now = Date.now();
66
+ if (goalId) {
67
+ const goal = await ctx.db.get("goals", goalId);
68
+ if (!goal || goal.siteId !== args.siteId) fail("NOT_FOUND", "goal not found");
69
+ await ctx.db.patch("goals", goalId, {
70
+ key,
71
+ name,
72
+ matchType: args.matchType,
73
+ matchValue,
74
+ valueCents: args.valueCents,
75
+ active: args.active ?? goal.active,
76
+ updatedAt: now,
77
+ });
78
+ return goalId;
79
+ }
80
+
81
+ const goals = await ctx.db
82
+ .query("goals")
83
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
84
+ .take(MAX_GOALS_PER_SITE + 1);
85
+ if (goals.length >= MAX_GOALS_PER_SITE) {
86
+ fail("LIMIT_EXCEEDED", "goal limit reached", { limit: MAX_GOALS_PER_SITE });
87
+ }
88
+ return await ctx.db.insert("goals", {
89
+ siteId: args.siteId,
90
+ key,
91
+ name,
92
+ matchType: args.matchType,
93
+ matchValue,
94
+ valueCents: args.valueCents,
95
+ active: args.active ?? true,
96
+ createdAt: now,
97
+ updatedAt: now,
98
+ });
99
+ },
100
+ });
101
+
102
+ export const list = query({
103
+ args: { siteId: v.id("sites") },
104
+ returns: v.array(goalDocumentValidator),
105
+ handler: async (ctx, args) => {
106
+ return await ctx.db
107
+ .query("goals")
108
+ .withIndex("by_siteId", (range) => range.eq("siteId", args.siteId))
109
+ .take(MAX_GOALS_PER_SITE);
110
+ },
111
+ });
112
+
113
+ export const remove = mutation({
114
+ args: { siteId: v.id("sites"), goalId: v.id("goals") },
115
+ returns: v.null(),
116
+ handler: async (ctx, args) => {
117
+ const goal = await ctx.db.get("goals", args.goalId);
118
+ if (!goal || goal.siteId !== args.siteId) fail("NOT_FOUND", "goal not found");
119
+ await ctx.db.delete("goals", args.goalId);
120
+ return null;
121
+ },
122
+ });
@@ -0,0 +1,3 @@
1
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }