@vexcms/better-auth 0.1.0-alpha.2 → 0.1.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/convex/getAuth.d.ts +7 -4
- package/dist/convex/getAuth.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/convex/getAuth.d.ts
CHANGED
|
@@ -9,18 +9,21 @@ import type { CollectionSlug, VexApiAuth } from "@vexcms/core";
|
|
|
9
9
|
* `identity.sessionId` (appended to every token by the plugin) → session
|
|
10
10
|
* document → `session.activeOrganizationId` → organization document.
|
|
11
11
|
* Documents are read fresh on every request, so role changes and
|
|
12
|
-
* `identity.sessionId` (appended to every token by the plugin) → session
|
|
13
|
-
* document → `session.activeOrganizationId` → organization document.
|
|
14
|
-
* Documents are read fresh on every request, so role changes and
|
|
15
12
|
* org switches apply immediately — claims are only used as ids, never
|
|
16
13
|
* as authorization data.
|
|
17
14
|
*
|
|
15
|
+
* `orgCollectionSlug` is only required when `resolveOrgs` is true — a
|
|
16
|
+
* project with organizations disabled can omit it entirely. Passing
|
|
17
|
+
* `resolveOrgs: true` without an `orgCollectionSlug` skips org resolution
|
|
18
|
+
* (same as `resolveOrgs: false`) rather than throwing, since the omission
|
|
19
|
+
* is a config mistake, not a request-time error worth failing loudly for.
|
|
20
|
+
*
|
|
18
21
|
* @returns { user, organization }, @see {@link VexApiAuth}
|
|
19
22
|
*
|
|
20
23
|
*/
|
|
21
24
|
export declare function createGetAuth<TCollectionSlug extends CollectionSlug = CollectionSlug>(props: {
|
|
22
25
|
userCollectionSlug: TCollectionSlug;
|
|
23
|
-
orgCollectionSlug
|
|
26
|
+
orgCollectionSlug?: TCollectionSlug;
|
|
24
27
|
sessionCollectionSlug: TCollectionSlug;
|
|
25
28
|
resolveOrgs?: boolean;
|
|
26
29
|
}): <DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>) => Promise<VexApiAuth>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getAuth.d.ts","sourceRoot":"","sources":["../../src/convex/getAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE3F,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/D
|
|
1
|
+
{"version":3,"file":"getAuth.d.ts","sourceRoot":"","sources":["../../src/convex/getAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE3F,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,aAAa,CAAC,eAAe,SAAS,cAAc,GAAG,cAAc,EAAE,KAAK,EAAE;IAC5F,kBAAkB,EAAE,eAAe,CAAC;IACpC,iBAAiB,CAAC,EAAE,eAAe,CAAC;IACpC,qBAAqB,EAAE,eAAe,CAAC;IACvC,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,IACe,SAAS,SAAS,gBAAgB,EAC9C,KAAK,eAAe,CAAC,SAAS,CAAC,GAAG,kBAAkB,CAAC,SAAS,CAAC,KAC9D,OAAO,CAAC,UAAU,CAAC,CA2BvB"}
|
package/dist/index.js
CHANGED
|
@@ -2201,13 +2201,14 @@ function createGetAuth(props) {
|
|
|
2201
2201
|
if (user === null) {
|
|
2202
2202
|
return { user };
|
|
2203
2203
|
}
|
|
2204
|
-
if (!props.resolveOrgs) {
|
|
2204
|
+
if (!props.resolveOrgs || !props.orgCollectionSlug) {
|
|
2205
2205
|
return { user };
|
|
2206
2206
|
}
|
|
2207
|
+
const orgCollectionSlug = props.orgCollectionSlug;
|
|
2207
2208
|
const sessionId = identity.sessionId;
|
|
2208
2209
|
const session = sessionId ? await ctx.db.get(props.sessionCollectionSlug, sessionId) : null;
|
|
2209
2210
|
const orgId = session?.activeOrganizationId;
|
|
2210
|
-
const organization = orgId ? await ctx.db.get(
|
|
2211
|
+
const organization = orgId ? await ctx.db.get(orgCollectionSlug, orgId) ?? void 0 : void 0;
|
|
2211
2212
|
return { user, organization };
|
|
2212
2213
|
};
|
|
2213
2214
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter.ts","../src/convex/adapter.ts","../src/convex/db.ts","../../../node_modules/.pnpm/convex-helpers@0.1.120_@standard-schema+spec@1.1.0_convex@1.44.0_react@19.2.7__hono@4.1_fda37119e0b134c2babc8f4bd1faf097/node_modules/convex-helpers/index.js","../../../node_modules/.pnpm/convex-helpers@0.1.120_@standard-schema+spec@1.1.0_convex@1.44.0_react@19.2.7__hono@4.1_fda37119e0b134c2babc8f4bd1faf097/node_modules/convex-helpers/server/stream.js","../src/convex/utils.ts","../src/convex/getAuth.ts","../src/convex/index.ts"],"sourcesContent":["import type {\n AuthCollectionConfig,\n AuthFieldMeta,\n BaseFieldInput,\n CollectionSlug,\n FieldAdminConfigInput,\n VexAuthAdapter,\n} from \"@vexcms/core\";\nimport {\n array,\n AuthCollectionMeta,\n checkbox,\n date,\n defineCollection,\n number,\n select,\n text,\n} from \"@vexcms/core\";\nimport type { BetterAuthOptions, DBFieldAttribute } from \"better-auth\";\nimport { getAuthTables } from \"better-auth/db\";\n\n/**\n * Options for `betterAuthAdapter()`.\n *\n * Accepts the same `BetterAuthOptions` object you pass to `betterAuth()`\n * on the server. Only schema-affecting properties (modelNames,\n * additionalFields, plugins) are read. Runtime options (database, secret,\n * baseURL) are ignored.\n */\nexport interface BetterAuthAdapterOptions {\n config: BetterAuthOptions;\n}\n\nconst AUTH_COLLECTION_TYPES = {\n user: \"user\",\n session: \"session\",\n account: \"account\",\n verification: \"verification\",\n} as const;\n\n/** Fields on the user table that end-users are allowed to edit. */\nconst EDITABLE_FIELDS = new Set([\n \"name\",\n \"email\",\n \"image\",\n \"role\",\n \"banned\",\n \"banReason\",\n \"banExpires\",\n]);\n\n/** Fields that should be hidden in the admin UI for security. */\nconst HIDDEN_FIELDS = new Set([\n \"hashedPassword\",\n \"password\",\n \"twoFactorSecret\",\n \"twoFactorBackupCodes\",\n \"token\",\n \"secret\",\n \"code\",\n]);\n\n/**\n * Creates a Vex auth adapter from a Better Auth configuration.\n *\n * Introspects Better Auth's full merged schema (base fields + plugin fields\n * + additionalFields) via `getAuthTables()` and converts each table into a\n * standard Vex `CollectionConfig` using Vex field builders.\n *\n * Mappings from Better Auth `DBFieldAttribute` to Vex fields:\n * - `type` → Vex field type (`string`→text, `boolean`→checkbox, `number`→number,\n * `date`/`timestamp`→date, `json`→text fallback, array→select)\n * - `required` → field `required`\n * - `defaultValue` → field `defaultValue`\n * - `unique`/`index` → field `index` (index name: `by_<field>_unique` or `by_<field>`)\n * - `references` → `relationship` field\n * - System fields get `admin.readOnly: true` and `meta.locked: true`\n * - Sensitive fields get `admin.hidden: true`\n *\n * @param props — Adapter options; pass your Better Auth config object wrapped\n * in `{ config: authOptions }`. Optional — when omitted, uses default\n * Better Auth tables with no plugins or additional fields.\n * @returns A `VexAuthAdapter` ready for `defineConfig({ auth: … })`.\n *\n * @example\n * ```ts\n * import { betterAuthAdapter } from \"@vexcms/better-auth\";\n * import { authOptions } from \"~/auth/server\";\n *\n * export default defineConfig({\n * auth: betterAuthAdapter({ config: authOptions }),\n * collections: [posts],\n * });\n * ```\n */\nexport function betterAuthAdapter(\n props?: BetterAuthAdapterOptions,\n): VexAuthAdapter {\n const tables = getAuthTables(props?.config ?? {});\n const collections: AuthCollectionConfig[] = [];\n const authCollections = [\n { type: AUTH_COLLECTION_TYPES.user, slug: props?.config?.user?.modelName },\n {\n type: AUTH_COLLECTION_TYPES.session,\n slug: props?.config?.session?.modelName,\n },\n {\n type: AUTH_COLLECTION_TYPES.account,\n slug: props?.config?.account?.modelName,\n },\n {\n type: AUTH_COLLECTION_TYPES.verification,\n slug: props?.config?.verification?.modelName,\n },\n ] as const;\n\n for (const [tableKey, tableDef] of Object.entries(tables)) {\n const slug = tableDef.modelName ?? tableKey;\n const fields: AuthCollectionConfig[\"fields\"] = {};\n\n addAuthCollectionFields({\n attributes: tableDef.fields,\n slug,\n fields,\n config: props?.config,\n extractId: true,\n });\n\n const authCollectionType = authCollections.find(\n (ac) => ac.slug === slug,\n )?.type;\n if (authCollectionType) {\n switch (authCollectionType) {\n case \"user\": {\n const additionalFields = props?.config?.user?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"session\": {\n const additionalFields = props?.config?.session?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"account\": {\n const additionalFields = props?.config?.account?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"verification\": {\n const additionalFields =\n props?.config?.verification?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n default:\n break;\n }\n }\n\n const isProtected = slug !== \"user\" && slug !== \"users\";\n\n collections.push(\n defineCollection<AuthFieldMeta, AuthCollectionMeta>({\n slug: slug as CollectionSlug,\n fields,\n meta: isProtected ? { protected: true } : undefined,\n }),\n );\n }\n\n const userSlug = tables.user?.modelName ?? \"user\";\n return {\n name: \"better-auth\",\n collections,\n userCollection: userSlug as CollectionSlug,\n };\n}\n\n/**\n * Converts a set of Better Auth field attributes into Vex field definitions\n * and appends them to the given collection `fields` map.\n *\n * Iterates over `attributes`, calls {@link betterAuthAttrToVexField} for each\n * entry, and mutates `props.fields` in place. When `extractId` is `true`,\n * the `id` field is skipped because Convex auto-generates `_id`.\n *\n * @param props — Field extraction options.\n * @param props.attributes — Better Auth `DBFieldAttribute` map to convert.\n * @param props.slug — Collection slug (used for relationship target resolution).\n * @param props.fields — Mutable Vex collection fields object to populate.\n * @param props.config — Better Auth options (for model name / additional fields lookups).\n * @param props.extractId — When `true`, skips the `id` field.\n *\n * @internal\n */\nexport function addAuthCollectionFields(props: {\n attributes?: Record<string, DBFieldAttribute>;\n slug: string;\n fields: AuthCollectionConfig[\"fields\"];\n config?: BetterAuthOptions;\n extractId?: boolean;\n}) {\n if (!props.attributes) return;\n for (const [fieldName, attr] of Object.entries(props.attributes)) {\n if (props.extractId === true && fieldName === \"id\") continue;\n const field = betterAuthAttrToVexField(\n fieldName,\n attr,\n props.slug,\n props?.config,\n );\n if (field) props.fields[fieldName] = field;\n }\n}\n\n/**\n * Maps a single Better Auth `DBFieldAttribute` to a Vex field builder call.\n *\n * Handles all Better Auth scalar types: `string`, `boolean`, `number`, `date`,\n * `timestamp`, `json`, and enum arrays. Maps overlapping properties\n * (`required`, `defaultValue`, `unique`/`index`, `references`) to their\n * Vex equivalents. Sets `admin.readOnly` and `meta.locked` on system\n * fields, and `admin.hidden` on sensitive fields.\n *\n * @param fieldName — The field name from Better Auth.\n * @param attr — The Better Auth field attribute.\n * @param tableSlug — The collection slug (for relationship targets).\n * @param authOptions -- The betterAuth options\n * @returns A Vex field instance, or `null` if the type is unsupported.\n *\n * @internal\n */\nfunction betterAuthAttrToVexField(\n fieldName: string,\n attr: DBFieldAttribute,\n tableSlug: string,\n authOptions?: BetterAuthOptions,\n) {\n // Skip id — Convex auto-generates _id\n if (fieldName === \"id\") return null;\n\n const isUserTable =\n tableSlug === authOptions?.user?.modelName ||\n tableSlug === \"user\" ||\n tableSlug === \"users\";\n const isEditable = isUserTable && EDITABLE_FIELDS.has(fieldName);\n const isHidden = HIDDEN_FIELDS.has(fieldName);\n\n const admin: FieldAdminConfigInput = {};\n if (!isEditable) admin.readOnly = true;\n if (isHidden) admin.hidden = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const baseOptions: { defaultValue: any } & BaseFieldInput<AuthFieldMeta> = {\n defaultValue: undefined,\n };\n if (Object.keys(admin).length > 0) baseOptions.admin = admin;\n if (!isEditable) baseOptions.meta = { locked: true };\n if (attr.required) baseOptions.required = attr.required;\n if (\n attr.defaultValue !== undefined &&\n typeof attr.defaultValue !== \"function\"\n ) {\n baseOptions.defaultValue = attr.defaultValue;\n }\n if (attr.unique || attr.index) {\n baseOptions.index = `by_${fieldName}`;\n }\n\n if (attr.references) {\n return text(baseOptions);\n }\n\n if (Array.isArray(attr.type)) {\n return select({\n options: attr.type.map((v: string) => ({ value: v, label: v })),\n ...baseOptions,\n });\n }\n\n switch (attr.type) {\n case \"string\":\n return text(baseOptions);\n case \"string[]\":\n return array({\n ...baseOptions,\n items: text(baseOptions),\n });\n case \"boolean\":\n return checkbox(baseOptions);\n case \"number\":\n return number(baseOptions);\n case \"number[]\":\n return array({\n ...baseOptions,\n items: number(baseOptions),\n });\n case \"date\":\n return date(baseOptions);\n case \"json\":\n // Fall back to text until a dedicated json field type is wired\n // TODO: create json field\n return text(baseOptions);\n default:\n // Unknown type — skip rather than crash\n return null;\n }\n}\n","import type { Where } from \"better-auth/types\";\nimport type { GenericActionCtx, GenericDataModel } from \"convex/server\";\nimport { anyApi } from \"convex/server\";\nimport {\n createAdapterFactory,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { getAuthTables } from \"better-auth/db\";\n\ntype ConvexCleanedWhere = Where & {\n value: boolean | null | number | number[] | string | string[];\n};\n\nconst parseWhere = (where?: Where[]): ConvexCleanedWhere[] => {\n return (where?.map((where) => {\n if (where.value instanceof Date) {\n return { ...where, value: where.value.getTime() };\n }\n return where;\n }) ?? []) as ConvexCleanedWhere[];\n};\n\n/**\n * Creates the Convex database adapter for Better Auth.\n *\n * @param ctx - The Convex action context\n * @param config - Optional debug log configuration\n * @returns AdapterFactory<BetterAuthOptions>\n */\nexport function convexAdapter<DataModel extends GenericDataModel>(\n ctx: GenericActionCtx<DataModel>,\n config: { debugLogs?: DBAdapterDebugLogOption } = {},\n) {\n return createAdapterFactory({\n adapter: ({ options }) => {\n options.telemetry = { enabled: false };\n const betterAuthSchema = getAuthTables(options);\n const betterAuthSchemaJson = JSON.stringify(betterAuthSchema);\n\n return {\n id: \"convex\",\n options: { isRunMutationCtx: \"runMutation\" in ctx },\n\n // Use anyApi to reference db operations, call via ctx.runMutation/ctx.runQuery\n create: async ({ data, model, select }) => {\n return await ctx.runMutation(anyApi.auth.db.dbCreate, {\n betterAuthSchema: betterAuthSchemaJson,\n data,\n model,\n select,\n });\n },\n\n findOne: async ({ model, select, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbFindOne, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n select,\n where: parseWhere(where),\n });\n },\n\n findMany: async ({ limit, model, sortBy, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbFindMany, {\n betterAuthSchema: betterAuthSchemaJson,\n limit,\n model,\n sortBy,\n where: parseWhere(where),\n });\n },\n\n count: async ({ model, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbCount, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n update: async ({ model, update, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbUpdate, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n update,\n where: parseWhere(where),\n });\n },\n\n updateMany: async ({ model, update, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbUpdateMany, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n update,\n where: parseWhere(where),\n });\n },\n\n delete: async ({ model, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbDelete, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n deleteMany: async ({ model, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbDeleteMany, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n transaction: async () => {\n throw new Error(\"Transactions not supported\");\n },\n };\n },\n config: {\n adapterId: \"convex\",\n adapterName: \"Convex Adapter\",\n customTransformInput: ({ data, fieldAttributes }) =>\n data && fieldAttributes.type === \"date\"\n ? new Date(data).getTime()\n : data,\n customTransformOutput: ({ data, fieldAttributes }) =>\n data && fieldAttributes.type === \"date\"\n ? new Date(data).getTime()\n : data,\n debugLogs: config.debugLogs ?? false,\n disableIdGeneration: true,\n mapKeysTransformInput: { id: \"_id\" },\n mapKeysTransformOutput: { _id: \"id\" },\n supportsArrays: true,\n supportsDates: false,\n supportsJSON: true,\n supportsNumericIds: false,\n transaction: false,\n usePlural: false,\n },\n });\n}\n","/* eslint-disable jsdoc/require-jsdoc */\nimport type { BetterAuthDBSchema } from \"better-auth/db\";\nimport type {\n GenericQueryCtx,\n GenericMutationCtx,\n GenericDataModel,\n SchemaDefinition,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport { v } from \"convex/values\";\n\nimport {\n checkUniqueFields,\n listOne,\n paginate,\n selectFields,\n type WhereClause,\n} from \"./utils\";\n\n// Helper to get Better Auth schema - we'll pass it from the adapter\nconst getBetterAuthSchema = (schemaJson: string): BetterAuthDBSchema => {\n return JSON.parse(schemaJson);\n};\n\ninterface CreateArgs {\n betterAuthSchema: string;\n data: any;\n model: string;\n select?: string[];\n}\n\nexport const create = {\n args: {\n betterAuthSchema: v.string(),\n data: v.any(),\n model: v.string(),\n select: v.optional(v.array(v.string())),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, data, model, select }: CreateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n\n await checkUniqueFields(ctx, schema, authSchema, model, data as any);\n\n const id = await ctx.db.insert(model as any, data as any);\n const doc = await ctx.db.get(id);\n if (!doc) {\n throw new Error(`Failed to create ${model}`);\n }\n\n return selectFields(doc, select);\n },\n};\n\ninterface FindOneArgs {\n betterAuthSchema: string;\n model: string;\n select?: string[];\n where: unknown[];\n}\n\nexport const findOne = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n select: v.optional(v.array(v.string())),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, model, select, where }: FindOneArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const result = await listOne(ctx, schema, authSchema, {\n model,\n select,\n where: where as WhereClause[],\n });\n\n return result;\n },\n};\n\ninterface FindManyArgs {\n betterAuthSchema: string;\n limit?: number;\n model: string;\n sortBy?: { direction: \"asc\" | \"desc\"; field: string };\n where?: unknown[];\n}\n\nexport const findMany = {\n args: {\n betterAuthSchema: v.string(),\n limit: v.optional(v.number()),\n model: v.string(),\n sortBy: v.optional(\n v.object({\n direction: v.union(v.literal(\"asc\"), v.literal(\"desc\")),\n field: v.string(),\n }),\n ),\n where: v.optional(v.array(v.any())),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, limit, model, sortBy, where }: FindManyArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = (where ?? []) as WhereClause[];\n\n // Handle OR connector by running parallel queries\n if (parsedWhere.some((w) => w.connector === \"OR\")) {\n const results = await Promise.all(\n parsedWhere.map(async (w) => {\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: limit ?? 200 },\n sortBy,\n where: [w],\n });\n return result.page;\n }),\n );\n\n // De-duplicate and flatten\n const seen = new Set<string>();\n const uniqueDocs: any[] = [];\n for (const docs of results) {\n for (const doc of docs) {\n const docId = doc._id as string;\n if (!seen.has(docId)) {\n seen.add(docId);\n uniqueDocs.push(doc);\n }\n }\n }\n\n // Apply sorting if needed\n if (sortBy) {\n uniqueDocs.sort((a, b) => {\n const aVal = a[sortBy.field];\n const bVal = b[sortBy.field];\n if (aVal === bVal) {\n return 0;\n }\n const comparison = aVal > bVal ? 1 : -1;\n return sortBy.direction === \"desc\" ? -comparison : comparison;\n });\n }\n\n return uniqueDocs.slice(0, limit);\n }\n\n // Normal case without OR\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: limit ?? 200 },\n sortBy,\n where: parsedWhere,\n });\n\n return result.page;\n },\n};\n\ninterface CountArgs {\n betterAuthSchema: string;\n model: string;\n where?: unknown[];\n}\n\nexport const count = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.optional(v.array(v.any())),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: CountArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = (where ?? []) as WhereClause[];\n\n // Handle OR connector\n if (parsedWhere.some((w) => w.connector === \"OR\")) {\n const results = await Promise.all(\n parsedWhere.map(async (w) => {\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: [w],\n });\n return result.page;\n }),\n );\n\n // De-duplicate and count\n const seen = new Set<string>();\n for (const docs of results) {\n for (const doc of docs) {\n const docId = doc._id as string;\n seen.add(docId);\n }\n }\n return seen.size;\n }\n\n // Normal case\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n return result.page.length;\n },\n};\n\ninterface UpdateArgs {\n betterAuthSchema: string;\n model: string;\n update: any;\n where: unknown[];\n}\n\nexport const update = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n update: v.any(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, update, where }: UpdateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n // Find the document to update\n const doc = await listOne(ctx, schema, authSchema, {\n model,\n where: parsedWhere,\n });\n\n if (!doc) {\n return null;\n }\n\n // Check unique fields before update\n await checkUniqueFields(ctx, schema, authSchema, model, update as any, doc);\n\n await ctx.db.patch(doc._id as GenericId<any>, update as any);\n return await ctx.db.get(doc._id as GenericId<any>);\n },\n};\n\n// Update many operation\nexport const updateMany = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n update: v.any(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, update, where }: UpdateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n // Check unique fields if updating multiple docs\n if (result.page.length > 1) {\n const uniqueFieldKeys = Object.keys(update as any).filter(\n (key) => authSchema[model]?.fields?.[key]?.unique,\n );\n if (uniqueFieldKeys.length > 0) {\n throw new Error(\n `Attempted to set unique fields in multiple documents in ${model} with the same value. Fields: ${uniqueFieldKeys.join(\", \")}`,\n );\n }\n }\n\n // Update each document\n for (const doc of result.page) {\n await checkUniqueFields(\n ctx,\n schema,\n authSchema,\n model,\n update as any,\n doc,\n );\n await ctx.db.patch(doc._id as GenericId<any>, update as any);\n }\n\n return result.page.length;\n },\n};\n\ninterface DeleteArgs {\n betterAuthSchema: string;\n model: string;\n where: unknown[];\n}\n\nexport const deleteOne = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: DeleteArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const doc = await listOne(ctx, schema, authSchema, {\n model,\n where: parsedWhere,\n });\n\n if (!doc) {\n return;\n }\n\n await ctx.db.delete(doc._id as GenericId<any>);\n },\n};\n\n// Delete many operation\nexport const deleteMany = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: DeleteArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n // Delete each document\n for (const doc of result.page) {\n await ctx.db.delete(doc._id as GenericId<any>);\n }\n\n return result.page.length;\n },\n};\n","/**\n * asyncMap returns the results of applying an async function over an list.\n *\n * The list can even be a promise, or an iterable like a Set.\n * @param list - Iterable object of items, e.g. an Array, Set, Object.keys\n * @param asyncTransform\n * @returns\n */\nexport async function asyncMap(list, asyncTransform) {\n const promises = [];\n let index = 0;\n list = await list;\n for (const item of list) {\n promises.push(asyncTransform(item, index));\n index += 1;\n }\n return Promise.all(promises);\n}\n/**\n * Filters out null elements from an array.\n * @param list List of elements that might be null.\n * @returns List of elements with nulls removed.\n */\nexport function pruneNull(list) {\n return list.filter((i) => i !== null);\n}\nexport class NullDocumentError extends Error {\n}\n/**\n * Throws if there is a null element in the array.\n * @param list List of elements that might have a null element.\n * @returns Same list of elements with a refined type.\n */\nexport function nullThrows(doc, message) {\n if (doc === null) {\n throw new NullDocumentError(message ?? \"Unexpected null document.\");\n }\n return doc;\n}\n/**\n * pick helps you pick keys from an object more concisely.\n *\n * e.g. `pick({a: v.string(), b: v.number()}, [\"a\"])` is equivalent to\n * `{a: v.string()}`\n * The alternative could be something like:\n * ```js\n * const obj = { a: v.string(), b: v.number() };\n * // pick does the following\n * const { a } = obj;\n * const onlyA = { a };\n * ```\n *\n * @param obj The object to pick from. Often like { a: v.string() }\n * @param keys The keys to pick from the object.\n * @returns A new object with only the keys you picked and their values.\n */\nexport function pick(obj, keys) {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));\n}\n/**\n * omit helps you omit keys from an object more concisely.\n *\n * e.g. `omit({a: v.string(), b: v.number()}, [\"a\"])` is equivalent to\n * `{b: v.number()}`\n *\n * The alternative could be something like:\n * ```js\n * const obj = { a: v.string(), b: v.number() };\n * // omit does the following\n * const { a, ...rest } = obj;\n * const withoutA = rest;\n * ```\n *\n * @param obj The object to return a copy of without the specified keys.\n * @param keys The keys to omit from the object.\n * @returns A new object with the keys you omitted removed.\n */\nexport function omit(obj, keys) {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));\n}\n/**\n * Removes the _id and _creationTime fields from an object.\n * This enables easily cloning a Convex document like:\n * ```ts\n * const doc = await db.get(id);\n * const clone = withoutSystemFields(doc);\n * await db.insert(table, clone);\n * ```\n * @param obj The object to remove the _id and _creationTime fields from.\n * @returns A new object with the _id and _creationTime fields removed.\n */\nexport function withoutSystemFields(obj) {\n return omit(obj, [\"_id\", \"_creationTime\"]);\n}\n// Type utils:\nconst _error = Symbol();\n/**\n * A utility to validate truthiness at runtime, providing a type guard\n *\n * @example\n * ```ts\n * const x: string | null = getValue();\n * assert(x);\n * // x is now of type string\n * ```\n * You can also provide a function, to avoid doing expensive string templating.\n * @param arg A value to assert the truthiness of.\n * @param message An optional message to throw if the value is not truthy, or a function to generate the message.\n */\nexport function assert(value, message) {\n if (!value) {\n throw new Error(typeof message === \"function\" ? message() : message);\n }\n}\n","import { convexToJson, compareValues, jsonToConvex, getDocumentSize, } from \"convex/values\";\n// From https://docs.convex.dev/production/state/limits#transactions\nconst MAX_DOCUMENT_SCAN_LEN = 32000;\n// Value used to trigger page split suggestions. This is kind of\n// a backstop value to mitigate additional scans over the full\n// original range if documents change later. Making it smaller\n// would result in more splits (equal to the divisor) as the\n// number of documents scanned approaches the max.\nconst SOFT_MAX_SCAN_LEN = MAX_DOCUMENT_SCAN_LEN / 2;\n//\n// Helper functions\n//\nfunction makeExclusive(boundType) {\n if (boundType === \"gt\" || boundType === \"gte\") {\n return \"gt\";\n }\n return \"lt\";\n}\n/** Split a range query between two index keys into a series of range queries\n * that should be executed in sequence. This is necessary because Convex only\n * supports range queries of the form\n * q.eq(\"f1\", v).eq(\"f2\", v).lt(\"f3\", v).gt(\"f3\", v).\n * i.e. all fields must be equal except for the last field, which can have\n * two inequalities.\n *\n * For example, the range from >[1, 2, 3] to <=[1, 3, 2] would be split into\n * the following queries:\n * 1. q.eq(\"f1\", 1).eq(\"f2\", 2).gt(\"f3\", 3)\n * 2. q.eq(\"f1\", 1).gt(\"f2\", 2).lt(\"f2\", 3)\n * 3. q.eq(\"f1\", 1).eq(\"f2\", 3).lte(\"f3\", 2)\n */\nfunction splitRange(indexFields, \n// For descending queries, the resulting queries are reversed.\norder, startBound, endBound, startBoundType, endBoundType) {\n // Three parts to the split:\n // 1. reduce down from startBound to common prefix\n // 2. range with common prefix\n // 3. build back up from common prefix to endBound\n const commonPrefix = [];\n while (startBound.length > 0 &&\n endBound.length > 0 &&\n compareValues(startBound[0], endBound[0]) === 0) {\n const indexField = indexFields[0];\n indexFields = indexFields.slice(1);\n const eqBound = startBound[0];\n startBound = startBound.slice(1);\n endBound = endBound.slice(1);\n commonPrefix.push([\"eq\", indexField, eqBound]);\n }\n const makeCompare = (boundType, key) => {\n const range = commonPrefix.slice();\n let i = 0;\n for (; i < key.length - 1; i++) {\n range.push([\"eq\", indexFields[i], key[i]]);\n }\n if (i < key.length) {\n range.push([boundType, indexFields[i], key[i]]);\n }\n return range;\n };\n // Stage 1.\n const startRanges = [];\n while (startBound.length > 1) {\n startRanges.push(makeCompare(startBoundType, startBound));\n startBoundType = makeExclusive(startBoundType);\n startBound = startBound.slice(0, -1);\n }\n // Stage 3.\n const endRanges = [];\n while (endBound.length > 1) {\n endRanges.push(makeCompare(endBoundType, endBound));\n endBoundType = makeExclusive(endBoundType);\n endBound = endBound.slice(0, -1);\n }\n endRanges.reverse();\n // Stage 2.\n let middleRange;\n if (endBound.length === 0) {\n middleRange = makeCompare(startBoundType, startBound);\n }\n else if (startBound.length === 0) {\n middleRange = makeCompare(endBoundType, endBound);\n }\n else {\n const startValue = startBound[0];\n const endValue = endBound[0];\n middleRange = commonPrefix.slice();\n middleRange.push([startBoundType, indexFields[0], startValue]);\n middleRange.push([endBoundType, indexFields[0], endValue]);\n }\n const ranges = [...startRanges, middleRange, ...endRanges];\n if (order === \"desc\") {\n ranges.reverse();\n }\n return ranges;\n}\nfunction rangeToQuery(range) {\n return (q) => {\n for (const [boundType, field, value] of range) {\n q = q[boundType](field, value);\n }\n return q;\n };\n}\n/**\n * Get the ordered list of fields for a given table's index based on the schema.\n *\n * - For \"by_creation_time\", returns [\"_creationTime\", \"_id\"].\n * - For \"by_id\", returns [\"_id\"].\n * - Otherwise, looks up the named index in the schema and returns its fields\n * followed by [\"_creationTime\", \"_id\"].\n * e.g. for an index defined like `.index(\"abc\", [\"a\", \"b\"])`,\n * returns [\"a\", \"b\", \"_creationTime\", \"_id\"].\n */\nexport function getIndexFields(table, index, schema) {\n const indexDescriptor = String(index ?? \"by_creation_time\");\n if (indexDescriptor === \"by_creation_time\") {\n return [\"_creationTime\", \"_id\"];\n }\n if (indexDescriptor === \"by_id\") {\n return [\"_id\"];\n }\n if (!schema) {\n throw new Error(\"schema is required to infer index fields\");\n }\n const tableInfo = schema.tables[table];\n const indexInfo = tableInfo.indexes.find((index) => index.indexDescriptor === indexDescriptor);\n if (!indexInfo) {\n throw new Error(`Index ${indexDescriptor} not found in table ${table}`);\n }\n const fields = indexInfo.fields.slice();\n fields.push(\"_creationTime\");\n fields.push(\"_id\");\n return fields;\n}\nfunction getIndexKey(doc, indexFields) {\n const key = [];\n for (const field of indexFields) {\n let obj = doc;\n for (const subfield of field.split(\".\")) {\n obj = obj[subfield];\n }\n key.push(obj);\n }\n return key;\n}\n/**\n * A \"stream\" is an async iterable of query results, ordered by an index on a table.\n *\n * Use it as you would use `ctx.db`.\n * If using pagination in a reactive query, see the warnings on the `paginator`\n * function. TL;DR: you need to pass in `endCursor` to prevent holes or overlaps\n * between pages.\n *\n * Once you have a stream, you can use `mergeStreams` or `filterStream` to make\n * more streams. Then use `queryStream` to convert it into an OrderedQuery,\n * so you can call `.paginate()`, `.collect()`, etc.\n */\nexport function stream(db, schema) {\n return new StreamDatabaseReader(db, schema);\n}\n/**\n * A \"QueryStream\" is an async iterable of query results, ordered by indexed fields.\n */\nexport class QueryStream {\n /// Methods for creating new streams as modifications of the current stream.\n /**\n * Create a new stream with a TypeScript filter applied.\n *\n * This is similar to `db.query(tableName).filter(predicate)`, but it's more\n * general because it can call arbitrary TypeScript code, including more\n * database queries.\n *\n * All documents filtered out are still considered \"read\" from the database;\n * they are just excluded from the output stream.\n *\n * In contrast to `filter` from convex-helpers/server/filter, this filterWith\n * is applied *before* any pagination. That means if the filter excludes a lot\n * of documents, the `.paginate()` method will read a lot of documents until\n * it gets as many documents as it wants. If you run into issues with reading\n * too much data, you can pass `maximumRowsRead` to `paginate()`.\n */\n filterWith(predicate) {\n const order = this.getOrder();\n return new FlatMapStream(this, async (doc) => {\n const filtered = (await predicate(doc)) ? doc : null;\n return new SingletonStream(filtered, order, [], [], []);\n }, []);\n }\n /**\n * Create a new stream where each element is the result of applying the mapper\n * function to the elements of the original stream.\n *\n * Similar to how [1, 2, 3].map(x => x * 2) => [2, 4, 6]\n */\n map(mapper) {\n const order = this.getOrder();\n return new FlatMapStream(this, async (doc) => {\n const mapped = await mapper(doc);\n return new SingletonStream(mapped, order, [], [], []);\n }, []);\n }\n /**\n * Similar to flatMap on an array, but iterate over a stream, and the for each\n * element, iterate over the stream created by the mapper function.\n *\n * Ordered by the original stream order, then the mapped stream. Similar to\n * how [\"a\", \"b\"].flatMap(letter => [letter, letter]) => [\"a\", \"a\", \"b\", \"b\"]\n *\n * @param mapper A function that takes a document and returns a new stream.\n * @param mappedIndexFields The index fields of the streams created by mapper.\n * @returns A stream of documents returned by the mapper streams,\n * grouped by the documents in the original stream.\n */\n flatMap(mapper, mappedIndexFields) {\n normalizeIndexFields(mappedIndexFields);\n return new FlatMapStream(this, mapper, mappedIndexFields);\n }\n /**\n * Get the first item from the original stream for each distinct value of the\n * selected index fields.\n *\n * e.g. if the stream has an equality filter on `a`, and index fields `[a, b, c]`,\n * we can do `stream.distinct([\"b\"])` to get a stream of the first item for\n * each distinct value of `b`.\n * Similarly, you could do `stream.distinct([\"a\", \"b\"])` with the same result,\n * or `stream.distinct([\"a\", \"b\", \"c\"])` to get the original stream.\n *\n * This stream efficiently skips past items with the same value for the selected\n * distinct index fields.\n *\n * This can be used to perform a loose index scan.\n */\n distinct(distinctIndexFields) {\n return new DistinctStream(this, distinctIndexFields);\n }\n /// Implementation of OrderedQuery\n filter(_predicate) {\n throw new Error(\"Cannot call .filter() directly on a query stream. Use .filterWith() for filtering or .collect() if you want to convert the stream to an array first.\");\n }\n async paginate(opts) {\n if (opts.numItems === 0) {\n if (opts.cursor === null) {\n throw new Error(\".paginate called with cursor of null and 0 for numItems. \" +\n \"This is not supported, as null is not a valid continueCursor. \" +\n \"Advice: avoid calling paginate entirely in these cases.\");\n }\n return {\n page: [],\n isDone: false,\n continueCursor: opts.cursor,\n };\n }\n const order = this.getOrder();\n let newStartKey = {\n key: [],\n inclusive: true,\n };\n if (opts.cursor !== null) {\n newStartKey = {\n key: deserializeCursor(opts.cursor),\n inclusive: false,\n };\n }\n let newEndKey = {\n key: [],\n inclusive: true,\n };\n const maxRowsToRead = opts.maximumRowsRead;\n let maxRows = opts.numItems;\n if (opts.endCursor) {\n newEndKey = {\n key: deserializeCursor(opts.endCursor),\n inclusive: true,\n };\n // If there's an endCursor, continue until we get there even if it's more\n // than numItems.\n maxRows = undefined;\n }\n const newLowerBound = order === \"asc\" ? newStartKey : newEndKey;\n const newUpperBound = order === \"asc\" ? newEndKey : newStartKey;\n const narrowStream = this.narrow({\n lowerBound: newLowerBound.key,\n lowerBoundInclusive: newLowerBound.inclusive,\n upperBound: newUpperBound.key,\n upperBoundInclusive: newUpperBound.inclusive,\n });\n const page = [];\n const indexKeys = [];\n let hasMore = opts.endCursor && opts.endCursor !== \"[]\";\n let continueCursor = opts.endCursor ?? \"[]\";\n const maxBytesToRead = opts.maximumBytesRead;\n const trackBandwidth = maxBytesToRead !== undefined;\n let totalBytesRead = 0;\n let hitLimit = false;\n for await (const [doc, indexKey, bandwidth] of narrowStream.iterWithKeys(trackBandwidth)) {\n if (doc !== null) {\n page.push(doc);\n }\n indexKeys.push(indexKey);\n totalBytesRead += bandwidth;\n if ((maxBytesToRead !== undefined && totalBytesRead >= maxBytesToRead) ||\n (maxRowsToRead !== undefined && indexKeys.length >= maxRowsToRead)) {\n hitLimit = true;\n }\n if (hitLimit || (maxRows !== undefined && page.length >= maxRows)) {\n hasMore = true;\n continueCursor = serializeCursor(indexKey);\n break;\n }\n }\n let pageStatus = undefined;\n let splitCursor = undefined;\n if (hitLimit) {\n pageStatus = \"SplitRequired\";\n splitCursor = indexKeys[Math.floor((indexKeys.length - 1) / 2)];\n }\n else if (indexKeys.length >= SOFT_MAX_SCAN_LEN ||\n page.length > opts.numItems + 1) {\n pageStatus = \"SplitRecommended\";\n splitCursor = indexKeys[Math.floor((indexKeys.length - 1) / 2)];\n }\n return {\n page,\n isDone: !hasMore,\n continueCursor,\n pageStatus,\n splitCursor: splitCursor ? serializeCursor(splitCursor) : undefined,\n };\n }\n async collect() {\n return await this.take(Infinity);\n }\n async take(n) {\n const results = [];\n for await (const [doc] of this.iterWithKeys()) {\n if (doc === null) {\n continue;\n }\n results.push(doc);\n if (results.length === n) {\n break;\n }\n }\n return results;\n }\n async unique() {\n const docs = await this.take(2);\n if (docs.length === 2) {\n throw new Error(\"Query is not unique\");\n }\n return docs[0] ?? null;\n }\n async first() {\n const docs = await this.take(1);\n return docs[0] ?? null;\n }\n [Symbol.asyncIterator]() {\n const iterator = this.iterWithKeys()[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n return { done: false, value: result.value[0] };\n },\n };\n }\n}\nexport class StreamDatabaseReader {\n db;\n schema;\n // TODO: support system tables\n system;\n constructor(db, schema) {\n this.db = db;\n this.schema = schema;\n this.system = db.system;\n }\n query(tableName) {\n return new StreamQueryInitializer(this, tableName);\n }\n get(_id) {\n throw new Error(\"get() not supported for `paginator`\");\n }\n normalizeId(_tableName, _id) {\n throw new Error(\"normalizeId() not supported for `paginator`.\");\n }\n}\nexport class StreamableQuery extends QueryStream {\n}\nexport class StreamQueryInitializer extends StreamableQuery {\n parent;\n table;\n constructor(parent, table) {\n super();\n this.parent = parent;\n this.table = table;\n }\n fullTableScan() {\n return this.withIndex(\"by_creation_time\");\n }\n withIndex(indexName, indexRange) {\n const indexFields = getIndexFields(this.table, indexName, this.parent.schema);\n const q = new ReflectIndexRange(indexFields);\n if (indexRange) {\n indexRange(q);\n }\n return new StreamQuery(this, indexName, q, indexRange);\n }\n withSearchIndex(_indexName, _searchFilter) {\n throw new Error(\"Cannot paginate withSearchIndex\");\n }\n inner() {\n return this.fullTableScan();\n }\n order(order) {\n return this.inner().order(order);\n }\n reflect() {\n return this.inner().reflect();\n }\n iterWithKeys(trackBandwidth = false) {\n return this.inner().iterWithKeys(trackBandwidth);\n }\n getOrder() {\n return this.inner().getOrder();\n }\n getEqualityIndexFilter() {\n return this.inner().getEqualityIndexFilter();\n }\n getIndexFields() {\n return this.inner().getIndexFields();\n }\n narrow(indexBounds) {\n return this.inner().narrow(indexBounds);\n }\n}\n// Not to be confused with QueryStream or StreamableQuery.\nexport class StreamQuery extends StreamableQuery {\n parent;\n index;\n q;\n indexRange;\n constructor(parent, index, q, indexRange) {\n super();\n this.parent = parent;\n this.index = index;\n this.q = q;\n this.indexRange = indexRange;\n }\n order(order) {\n return new OrderedStreamQuery(this, order);\n }\n inner() {\n return this.order(\"asc\");\n }\n reflect() {\n return this.inner().reflect();\n }\n iterWithKeys(trackBandwidth = false) {\n return this.inner().iterWithKeys(trackBandwidth);\n }\n getOrder() {\n return this.inner().getOrder();\n }\n getEqualityIndexFilter() {\n return this.inner().getEqualityIndexFilter();\n }\n getIndexFields() {\n return this.inner().getIndexFields();\n }\n narrow(indexBounds) {\n return this.inner().narrow(indexBounds);\n }\n}\nexport class OrderedStreamQuery extends StreamableQuery {\n parent;\n order;\n constructor(parent, order) {\n super();\n this.parent = parent;\n this.order = order;\n }\n reflect() {\n return {\n db: this.parent.parent.parent.db,\n schema: this.parent.parent.parent.schema,\n table: this.parent.parent.table,\n index: this.parent.index,\n indexFields: this.parent.q.indexFields,\n order: this.order,\n bounds: {\n lowerBound: this.parent.q.lowerBoundIndexKey ?? [],\n lowerBoundInclusive: this.parent.q.lowerBoundInclusive,\n upperBound: this.parent.q.upperBoundIndexKey ?? [],\n upperBoundInclusive: this.parent.q.upperBoundInclusive,\n },\n indexRange: this.parent.indexRange,\n };\n }\n /**\n * inner() is as if you had used ctx.db to construct the query.\n */\n inner() {\n const { db, table, index, order, indexRange } = this.reflect();\n return db.query(table).withIndex(index, indexRange).order(order);\n }\n iterWithKeys(trackBandwidth = false) {\n const { indexFields } = this.reflect();\n const iterable = this.inner();\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n const doc = result.value;\n const bandwidth = trackBandwidth ? getDocumentSize(doc) : 0;\n return {\n done: false,\n value: [doc, getIndexKey(doc, indexFields), bandwidth],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.order;\n }\n getEqualityIndexFilter() {\n return this.parent.q.equalityIndexFilter;\n }\n getIndexFields() {\n return this.parent.q.indexFields;\n }\n narrow(indexBounds) {\n const { db, table, index, order, bounds, schema } = this.reflect();\n let maxLowerBound = bounds.lowerBound;\n let maxLowerBoundInclusive = bounds.lowerBoundInclusive;\n if (compareKeys({\n value: indexBounds.lowerBound,\n kind: indexBounds.lowerBoundInclusive ? \"predecessor\" : \"successor\",\n }, {\n value: bounds.lowerBound,\n kind: bounds.lowerBoundInclusive ? \"predecessor\" : \"successor\",\n }) > 0) {\n maxLowerBound = indexBounds.lowerBound;\n maxLowerBoundInclusive = indexBounds.lowerBoundInclusive;\n }\n let minUpperBound = bounds.upperBound;\n let minUpperBoundInclusive = bounds.upperBoundInclusive;\n if (compareKeys({\n value: indexBounds.upperBound,\n kind: indexBounds.upperBoundInclusive ? \"successor\" : \"predecessor\",\n }, {\n value: bounds.upperBound,\n kind: bounds.upperBoundInclusive ? \"successor\" : \"predecessor\",\n }) < 0) {\n minUpperBound = indexBounds.upperBound;\n minUpperBoundInclusive = indexBounds.upperBoundInclusive;\n }\n return streamIndexRange(db, schema, table, index, {\n lowerBound: maxLowerBound,\n lowerBoundInclusive: maxLowerBoundInclusive,\n upperBound: minUpperBound,\n upperBoundInclusive: minUpperBoundInclusive,\n }, order);\n }\n}\n/**\n * Create a stream of documents using the given index and bounds.\n */\nexport function streamIndexRange(db, schema, table, index, bounds, order) {\n const indexFields = getIndexFields(table, index, schema);\n const splitBounds = splitRange(indexFields, order, bounds.lowerBound, bounds.upperBound, bounds.lowerBoundInclusive ? \"gte\" : \"gt\", bounds.upperBoundInclusive ? \"lte\" : \"lt\");\n const subQueries = splitBounds.map((splitBound) => stream(db, schema)\n .query(table)\n .withIndex(index, rangeToQuery(splitBound))\n .order(order));\n return new ConcatStreams(...subQueries);\n}\nclass ReflectIndexRange {\n indexFields;\n #hasSuffix = false;\n lowerBoundIndexKey = undefined;\n lowerBoundInclusive = true;\n upperBoundIndexKey = undefined;\n upperBoundInclusive = true;\n equalityIndexFilter = [];\n constructor(indexFields) {\n this.indexFields = indexFields;\n }\n eq(field, value) {\n if (!this.#canLowerBound(field) || !this.#canUpperBound(field)) {\n throw new Error(`Cannot use eq on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.equalityIndexFilter.push(value);\n return this;\n }\n lt(field, value) {\n if (!this.#canUpperBound(field)) {\n throw new Error(`Cannot use lt on field '${field}'`);\n }\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.upperBoundInclusive = false;\n this.#hasSuffix = true;\n return this;\n }\n lte(field, value) {\n if (!this.#canUpperBound(field)) {\n throw new Error(`Cannot use lte on field '${field}'`);\n }\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.#hasSuffix = true;\n return this;\n }\n gt(field, value) {\n if (!this.#canLowerBound(field)) {\n throw new Error(`Cannot use gt on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.lowerBoundInclusive = false;\n this.#hasSuffix = true;\n return this;\n }\n gte(field, value) {\n if (!this.#canLowerBound(field)) {\n throw new Error(`Cannot use gte on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.#hasSuffix = true;\n return this;\n }\n #canLowerBound(field) {\n const currentLowerBoundLength = this.lowerBoundIndexKey?.length ?? 0;\n const currentUpperBoundLength = this.upperBoundIndexKey?.length ?? 0;\n if (currentLowerBoundLength > currentUpperBoundLength) {\n // Already have a lower bound.\n return false;\n }\n if (currentLowerBoundLength === currentUpperBoundLength &&\n this.#hasSuffix) {\n // Already have a lower bound and an upper bound.\n return false;\n }\n return (currentLowerBoundLength < this.indexFields.length &&\n this.indexFields[currentLowerBoundLength] === field);\n }\n #canUpperBound(field) {\n const currentLowerBoundLength = this.lowerBoundIndexKey?.length ?? 0;\n const currentUpperBoundLength = this.upperBoundIndexKey?.length ?? 0;\n if (currentUpperBoundLength > currentLowerBoundLength) {\n // Already have an upper bound.\n return false;\n }\n if (currentLowerBoundLength === currentUpperBoundLength &&\n this.#hasSuffix) {\n // Already have a lower bound and an upper bound.\n return false;\n }\n return (currentUpperBoundLength < this.indexFields.length &&\n this.indexFields[currentUpperBoundLength] === field);\n }\n}\n/**\n * Merge multiple streams, provided in any order, into a single stream.\n *\n * The streams will be merged into a stream of documents ordered by the index keys,\n * i.e. by \"author\" (then by the implicit \"_creationTime\").\n *\n * e.g. ```ts\n * mergedStream([\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user3\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * ], [\"author\"])\n * ```\n *\n * returns a stream of messages for user1, then user2, then user3.\n *\n * You can also use `orderByIndexFields` to change the indexed fields before merging, which changes the order of the merged stream.\n * This only works if the streams are already ordered by `orderByIndexFields`,\n * which happens if each does a .eq(field, value) on all index fields before `orderByIndexFields`.\n *\n * e.g. if the \"by_author\" index is defined as being ordered by [\"author\", \"_creationTime\"],\n * and each query does an equality lookup on \"author\", each individual query before merging is in fact ordered by \"_creationTime\".\n *\n * e.g. ```ts\n * mergedStream([\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user3\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * ], [\"_creationTime\"])\n * ```\n *\n * This returns a stream of messages from all three users, sorted by creation time.\n */\nexport function mergedStream(streams, orderByIndexFields) {\n return new MergedStream(streams, orderByIndexFields);\n}\nexport class MergedStream extends QueryStream {\n #order;\n #streams;\n #equalityIndexFilter;\n #indexFields;\n constructor(streams, orderByIndexFields) {\n super();\n if (streams.length === 0) {\n throw new Error(\"Cannot union empty array of streams\");\n }\n this.#order = allSame(streams.map((stream) => stream.getOrder()), \"Cannot merge streams with different orders\");\n this.#streams = streams.map((stream) => new OrderByStream(stream, orderByIndexFields));\n this.#indexFields = allSame(this.#streams.map((stream) => stream.getIndexFields()), \"Cannot merge streams with different index fields. Consider using .orderBy()\");\n // Calculate common prefix of equality index filters.\n this.#equalityIndexFilter = commonPrefix(this.#streams.map((stream) => stream.getEqualityIndexFilter()));\n }\n iterWithKeys(trackBandwidth = false) {\n const iterables = this.#streams.map((stream) => stream.iterWithKeys(trackBandwidth));\n const comparisonInversion = this.#order === \"asc\" ? 1 : -1;\n return {\n [Symbol.asyncIterator]() {\n const iterators = iterables.map((iterable) => iterable[Symbol.asyncIterator]());\n const results = Array(iterators.length);\n // Track bandwidth from pre-fetched documents not yet yielded\n const pendingBandwidth = Array(iterators.length).fill(0);\n return {\n async next() {\n let bandwidthThisIteration = 0;\n // Fill results from iterators with no value yet.\n await Promise.all(iterators.map(async (iterator, i) => {\n if (!results[i]) {\n const result = await iterator.next();\n results[i] = result;\n // Track bandwidth from pre-fetched documents\n if (trackBandwidth && !result.done && result.value) {\n pendingBandwidth[i] = result.value[2];\n }\n }\n }));\n // Sum all pending bandwidth (pre-fetched docs) for this iteration\n if (trackBandwidth) {\n for (let i = 0; i < pendingBandwidth.length; i++) {\n bandwidthThisIteration += pendingBandwidth[i];\n pendingBandwidth[i] = 0;\n }\n }\n // Find index for the value with the lowest index key.\n let minIndexKeyAndIndex = undefined;\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.done || !result.value) {\n continue;\n }\n const [_, resultIndexKey] = result.value;\n if (minIndexKeyAndIndex === undefined) {\n minIndexKeyAndIndex = [resultIndexKey, i];\n continue;\n }\n const [prevMin] = minIndexKeyAndIndex;\n if (compareKeys({ value: resultIndexKey, kind: \"exact\" }, { value: prevMin, kind: \"exact\" }) *\n comparisonInversion <\n 0) {\n minIndexKeyAndIndex = [resultIndexKey, i];\n }\n }\n if (minIndexKeyAndIndex === undefined) {\n return { done: true, value: undefined };\n }\n const [_, minIndex] = minIndexKeyAndIndex;\n const [doc, indexKey] = results[minIndex].value;\n // indicate that we've used this result\n results[minIndex] = undefined;\n return {\n done: false,\n value: [doc, indexKey, bandwidthThisIteration],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n narrow(indexBounds) {\n return new MergedStream(this.#streams.map((stream) => stream.narrow(indexBounds)), this.#indexFields);\n }\n}\nfunction allSame(values, errorMessage) {\n const first = values[0];\n for (const value of values) {\n if (compareValues(value, first)) {\n throw new Error(errorMessage);\n }\n }\n return first;\n}\nfunction commonPrefix(values) {\n let commonPrefix = values[0];\n for (const value of values) {\n for (let i = 0; i < commonPrefix.length; i++) {\n if (i >= value.length || compareValues(commonPrefix[i], value[i])) {\n commonPrefix = commonPrefix.slice(0, i);\n break;\n }\n }\n }\n return commonPrefix;\n}\n/**\n * Concatenate multiple streams into a single stream.\n * This assumes that the streams correspond to disjoint index ranges,\n * and are provided in the same order as the index ranges.\n *\n * e.g. ```ts\n * new ConcatStreams(\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * )\n * ```\n *\n * is valid, but if the stream arguments were reversed, or the queries were\n * `.order(\"desc\")`, it would be invalid.\n *\n * It's not recommended to use `ConcatStreams` directly, since it has the same\n * behavior as `MergedStream`, but with fewer runtime checks.\n */\nclass ConcatStreams extends QueryStream {\n #order;\n #streams;\n #equalityIndexFilter;\n #indexFields;\n constructor(...streams) {\n super();\n this.#streams = streams;\n if (streams.length === 0) {\n throw new Error(\"Cannot concat empty array of streams\");\n }\n this.#order = allSame(streams.map((stream) => stream.getOrder()), \"Cannot concat streams with different orders. Consider using .orderBy()\");\n this.#indexFields = allSame(streams.map((stream) => stream.getIndexFields()), \"Cannot concat streams with different index fields. Consider using .orderBy()\");\n this.#equalityIndexFilter = commonPrefix(streams.map((stream) => stream.getEqualityIndexFilter()));\n }\n iterWithKeys(trackBandwidth = false) {\n const iterables = this.#streams.map((stream) => stream.iterWithKeys(trackBandwidth));\n const comparisonInversion = this.#order === \"asc\" ? 1 : -1;\n let previousIndexKey = undefined;\n return {\n [Symbol.asyncIterator]() {\n const iterators = iterables.map((iterable) => iterable[Symbol.asyncIterator]());\n return {\n async next() {\n while (iterators.length > 0) {\n const result = await iterators[0].next();\n if (result.done) {\n iterators.shift();\n }\n else {\n const [_, indexKey] = result.value;\n if (previousIndexKey !== undefined &&\n compareKeys({\n value: previousIndexKey,\n kind: \"exact\",\n }, {\n value: indexKey,\n kind: \"exact\",\n }) *\n comparisonInversion >\n 0) {\n throw new Error(`ConcatStreams in wrong order: ${JSON.stringify(previousIndexKey)}, ${JSON.stringify(indexKey)}`);\n }\n previousIndexKey = indexKey;\n return result;\n }\n }\n return { done: true, value: undefined };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n narrow(indexBounds) {\n return new ConcatStreams(...this.#streams.map((stream) => stream.narrow(indexBounds)));\n }\n}\nclass FlatMapStreamIterator {\n #outerStream;\n #outerIterator;\n #currentOuterItem = null;\n #mapper;\n #mappedIndexFields;\n #trackBandwidth;\n constructor(outerStream, mapper, mappedIndexFields, trackBandwidth) {\n this.#outerIterator = outerStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n this.#outerStream = outerStream;\n this.#mapper = mapper;\n this.#mappedIndexFields = mappedIndexFields;\n this.#trackBandwidth = trackBandwidth;\n }\n singletonSkipInnerStream() {\n // If the outer stream is a filtered value, yield a singleton\n // filtered value from the inner stream, with index key of nulls.\n const indexKey = this.#mappedIndexFields.map(() => null);\n return new SingletonStream(null, this.#outerStream.getOrder(), this.#mappedIndexFields, indexKey, indexKey);\n }\n async setCurrentOuterItem(item) {\n const [t, indexKey, bandwidth] = item;\n let innerStream;\n if (t === null) {\n innerStream = this.singletonSkipInnerStream();\n }\n else {\n innerStream = await this.#mapper(t);\n if (!equalIndexFields(innerStream.getIndexFields(), this.#mappedIndexFields)) {\n throw new Error(`FlatMapStream: inner stream has different index fields than expected: ${JSON.stringify(innerStream.getIndexFields())} vs ${JSON.stringify(this.#mappedIndexFields)}`);\n }\n if (innerStream.getOrder() !== this.#outerStream.getOrder()) {\n throw new Error(`FlatMapStream: inner stream has different order than outer stream: ${innerStream.getOrder()} vs ${this.#outerStream.getOrder()}`);\n }\n }\n this.#currentOuterItem = {\n t,\n indexKey,\n innerIterator: innerStream\n .iterWithKeys(this.#trackBandwidth)[Symbol.asyncIterator](),\n count: 0,\n bandwidth,\n };\n }\n async next() {\n if (this.#currentOuterItem === null) {\n const result = await this.#outerIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n await this.setCurrentOuterItem(result.value);\n return await this.next();\n }\n const result = await this.#currentOuterItem.innerIterator.next();\n if (result.done) {\n if (this.#currentOuterItem.count > 0) {\n this.#currentOuterItem = null;\n }\n else {\n // The inner stream was completely empty, so we should inject a null\n // (which will be skipped by everything except the maximumRowsRead count)\n // to account for the cost of the outer stream.\n this.#currentOuterItem.innerIterator = this.singletonSkipInnerStream()\n .iterWithKeys(this.#trackBandwidth)[Symbol.asyncIterator]();\n }\n return await this.next();\n }\n const [u, indexKey, innerBandwidth] = result.value;\n this.#currentOuterItem.count++;\n const fullIndexKey = [...this.#currentOuterItem.indexKey, ...indexKey];\n // On first yield for this outer item, include outer bandwidth\n const bandwidth = (this.#currentOuterItem.count === 1\n ? this.#currentOuterItem.bandwidth\n : 0) + innerBandwidth;\n return { done: false, value: [u, fullIndexKey, bandwidth] };\n }\n}\nclass FlatMapStream extends QueryStream {\n #stream;\n #mapper;\n #mappedIndexFields;\n constructor(stream, mapper, mappedIndexFields) {\n super();\n this.#stream = stream;\n this.#mapper = mapper;\n this.#mappedIndexFields = mappedIndexFields;\n }\n iterWithKeys(trackBandwidth = false) {\n const outerStream = this.#stream;\n const mapper = this.#mapper;\n const mappedIndexFields = this.#mappedIndexFields;\n return {\n [Symbol.asyncIterator]() {\n return new FlatMapStreamIterator(outerStream, mapper, mappedIndexFields, trackBandwidth);\n },\n };\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getEqualityIndexFilter() {\n return this.#stream.getEqualityIndexFilter();\n }\n getIndexFields() {\n return [...this.#stream.getIndexFields(), ...this.#mappedIndexFields];\n }\n narrow(indexBounds) {\n const outerLength = this.#stream.getIndexFields().length;\n const outerLowerBound = indexBounds.lowerBound.slice(0, outerLength);\n const outerUpperBound = indexBounds.upperBound.slice(0, outerLength);\n const innerLowerBound = indexBounds.lowerBound.slice(outerLength);\n const innerUpperBound = indexBounds.upperBound.slice(outerLength);\n const outerIndexBounds = {\n lowerBound: outerLowerBound,\n lowerBoundInclusive: innerLowerBound.length === 0 ? indexBounds.lowerBoundInclusive : true,\n upperBound: outerUpperBound,\n upperBoundInclusive: innerUpperBound.length === 0 ? indexBounds.upperBoundInclusive : true,\n };\n const innerIndexBounds = {\n lowerBound: innerLowerBound,\n lowerBoundInclusive: innerLowerBound.length === 0 ? true : indexBounds.lowerBoundInclusive,\n upperBound: innerUpperBound,\n upperBoundInclusive: innerUpperBound.length === 0 ? true : indexBounds.upperBoundInclusive,\n };\n return new FlatMapStream(this.#stream.narrow(outerIndexBounds), async (t) => {\n const innerStream = await this.#mapper(t);\n return innerStream.narrow(innerIndexBounds);\n }, this.#mappedIndexFields);\n }\n}\nexport class SingletonStream extends QueryStream {\n #value;\n #order;\n #indexFields;\n #indexKey;\n #equalityIndexFilter;\n #bandwidth;\n constructor(value, order = \"asc\", indexFields, indexKey, equalityIndexFilter, bandwidth = 0) {\n super();\n this.#value = value;\n this.#order = order;\n this.#indexFields = indexFields;\n this.#indexKey = indexKey;\n this.#equalityIndexFilter = equalityIndexFilter;\n this.#bandwidth = bandwidth;\n if (indexKey.length !== indexFields.length) {\n throw new Error(`indexKey must have the same length as indexFields: ${JSON.stringify(indexKey)} vs ${JSON.stringify(indexFields)}`);\n }\n }\n iterWithKeys(_trackBandwidth = false) {\n const value = this.#value;\n const indexKey = this.#indexKey;\n const bandwidth = this.#bandwidth;\n return {\n [Symbol.asyncIterator]() {\n let sent = false;\n return {\n async next() {\n if (sent) {\n return { done: true, value: undefined };\n }\n sent = true;\n return {\n done: false,\n value: [value, indexKey, bandwidth],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n narrow(indexBounds) {\n const compareLowerBound = compareKeys({\n value: indexBounds.lowerBound,\n kind: indexBounds.lowerBoundInclusive ? \"exact\" : \"successor\",\n }, {\n value: this.#indexKey,\n kind: \"exact\",\n });\n const compareUpperBound = compareKeys({\n value: this.#indexKey,\n kind: \"exact\",\n }, {\n value: indexBounds.upperBound,\n kind: indexBounds.upperBoundInclusive ? \"exact\" : \"predecessor\",\n });\n // If lowerBound <= this.indexKey <= upperBound, return this.value\n if (compareLowerBound <= 0 && compareUpperBound <= 0) {\n return new SingletonStream(this.#value, this.#order, this.#indexFields, this.#indexKey, this.#equalityIndexFilter);\n }\n return new EmptyStream(this.#order, this.#indexFields);\n }\n}\n/**\n * This is a completely empty stream that yields no values, and in particular\n * does not count towards maximumRowsRead.\n * Compare to SingletonStream(null, ...), which yields no values but does count\n * towards maximumRowsRead.\n */\nexport class EmptyStream extends QueryStream {\n #order;\n #indexFields;\n constructor(order, indexFields) {\n super();\n this.#order = order;\n this.#indexFields = indexFields;\n }\n iterWithKeys(_trackBandwidth = false) {\n return {\n [Symbol.asyncIterator]() {\n return {\n async next() {\n return { done: true, value: undefined };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n getEqualityIndexFilter() {\n return [];\n }\n narrow(_indexBounds) {\n return this;\n }\n}\nfunction normalizeIndexFields(indexFields) {\n // Append _creationTime and _id to the index fields if they're not already there\n if (!indexFields.includes(\"_creationTime\")) {\n // With one exception: if indexFields is [\"_id\"], we don't need to add _creationTime\n if (indexFields.length !== 1 || indexFields[0] !== \"_id\") {\n indexFields.push(\"_creationTime\");\n }\n }\n if (!indexFields.includes(\"_id\")) {\n indexFields.push(\"_id\");\n }\n}\n// Given a stream ordered by `indexFields`, where the first `equalityIndexLength`\n// fields are bounded by equality filters, return a generator of the possible\n// index fields used for ordering.\nfunction* getOrderingIndexFields(stream) {\n const streamEqualityIndexLength = stream.getEqualityIndexFilter().length;\n const streamIndexFields = stream.getIndexFields();\n for (let i = 0; i <= streamEqualityIndexLength; i++) {\n yield streamIndexFields.slice(i);\n }\n}\nclass OrderByStream extends QueryStream {\n #staticFilter;\n #stream;\n #indexFields;\n constructor(stream, indexFields) {\n super();\n this.#stream = stream;\n this.#indexFields = indexFields;\n normalizeIndexFields(this.#indexFields);\n // indexFields must be a suffix of the stream's index fields, and include\n // all of the non-equality index fields.\n const streamIndexFields = stream.getIndexFields();\n const orderingIndexFields = Array.from(getOrderingIndexFields(stream));\n if (!orderingIndexFields.some((orderingIndexFields) => equalIndexFields(orderingIndexFields, indexFields))) {\n throw new Error(`indexFields must be some sequence of fields the stream is ordered by: ${JSON.stringify(indexFields)}, ${JSON.stringify(streamIndexFields)} (${stream.getEqualityIndexFilter().length} equality fields)`);\n }\n this.#staticFilter = stream\n .getEqualityIndexFilter()\n .slice(0, streamIndexFields.length - indexFields.length);\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getEqualityIndexFilter() {\n return this.#stream\n .getEqualityIndexFilter()\n .slice(this.#staticFilter.length);\n }\n getIndexFields() {\n return this.#indexFields;\n }\n iterWithKeys(trackBandwidth = false) {\n const iterable = this.#stream.iterWithKeys(trackBandwidth);\n const staticFilter = this.#staticFilter;\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return result;\n }\n const [doc, indexKey, bandwidth] = result.value;\n return {\n done: false,\n value: [doc, indexKey.slice(staticFilter.length), bandwidth],\n };\n },\n };\n },\n };\n }\n narrow(indexBounds) {\n return new OrderByStream(this.#stream.narrow({\n lowerBound: [...this.#staticFilter, ...indexBounds.lowerBound],\n lowerBoundInclusive: indexBounds.lowerBoundInclusive,\n upperBound: [...this.#staticFilter, ...indexBounds.upperBound],\n upperBoundInclusive: indexBounds.upperBoundInclusive,\n }), this.#indexFields);\n }\n}\nclass DistinctStream extends QueryStream {\n #distinctIndexFieldsLength;\n #stream;\n #distinctIndexFields;\n constructor(stream, distinctIndexFields) {\n super();\n this.#stream = stream;\n this.#distinctIndexFields = distinctIndexFields;\n // distinctIndexFields must be a prefix of the stream's ordering index fields\n let distinctIndexFieldsLength = undefined;\n for (const orderingIndexFields of getOrderingIndexFields(stream)) {\n const prefix = orderingIndexFields.slice(0, distinctIndexFields.length);\n if (equalIndexFields(prefix, distinctIndexFields)) {\n const equalityLength = stream.getIndexFields().length - orderingIndexFields.length;\n distinctIndexFieldsLength = equalityLength + distinctIndexFields.length;\n break;\n }\n }\n if (distinctIndexFieldsLength === undefined) {\n throw new Error(`distinctIndexFields must be a prefix of the stream's ordering index fields: ${JSON.stringify(distinctIndexFields)}, ${JSON.stringify(stream.getIndexFields())} (${stream.getEqualityIndexFilter().length} equality fields)`);\n }\n this.#distinctIndexFieldsLength = distinctIndexFieldsLength;\n }\n iterWithKeys(trackBandwidth = false) {\n const stream = this.#stream;\n const distinctIndexFieldsLength = this.#distinctIndexFieldsLength;\n return {\n [Symbol.asyncIterator]() {\n let currentStream = stream;\n let currentIterator = currentStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await currentIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n const [doc, indexKey, bandwidth] = result.value;\n if (doc === null) {\n // If the original stream has a post-filter `.filterWith`, we will\n // iterate over filtered items -- possibly many with the same set of\n // distinct index fields -- before finding the first item for the set\n // of distinct index fields.\n // So it's recommended to put `.filterWith` after `.distinct`.\n return {\n done: false,\n value: [null, indexKey, bandwidth],\n };\n }\n const distinctIndexKey = indexKey.slice(0, distinctIndexFieldsLength);\n if (stream.getOrder() === \"asc\") {\n currentStream = currentStream.narrow({\n lowerBound: distinctIndexKey,\n lowerBoundInclusive: false,\n upperBound: [],\n upperBoundInclusive: true,\n });\n }\n else {\n currentStream = currentStream.narrow({\n lowerBound: [],\n lowerBoundInclusive: true,\n upperBound: distinctIndexKey,\n upperBoundInclusive: false,\n });\n }\n currentIterator = currentStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n return result;\n },\n };\n },\n };\n }\n narrow(indexBounds) {\n const indexBoundsPrefix = {\n ...indexBounds,\n lowerBound: indexBounds.lowerBound.slice(0, this.#distinctIndexFieldsLength),\n upperBound: indexBounds.upperBound.slice(0, this.#distinctIndexFieldsLength),\n };\n return new DistinctStream(this.#stream.narrow(indexBoundsPrefix), this.#distinctIndexFields);\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getIndexFields() {\n return this.#stream.getIndexFields();\n }\n getEqualityIndexFilter() {\n return this.#stream.getEqualityIndexFilter();\n }\n}\nfunction equalIndexFields(indexFields1, indexFields2) {\n if (indexFields1.length !== indexFields2.length) {\n return false;\n }\n for (let i = 0; i < indexFields1.length; i++) {\n if (indexFields1[i] !== indexFields2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction getValueAtIndex(v, index) {\n if (index >= v.length) {\n return undefined;\n }\n return { kind: \"found\", value: v[index] };\n}\nfunction compareDanglingSuffix(shorterKeyKind, longerKeyKind, shorterKey, longerKey) {\n if (shorterKeyKind === \"exact\" && longerKeyKind === \"exact\") {\n throw new Error(`Exact keys are not the same length: ${JSON.stringify(shorterKey.value)}, ${JSON.stringify(longerKey.value)}`);\n }\n if (shorterKeyKind === \"exact\") {\n throw new Error(`Exact key is shorter than prefix: ${JSON.stringify(shorterKey.value)}, ${JSON.stringify(longerKey.value)}`);\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"successor\") {\n // successor is longer than predecessor, so it is bigger\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"predecessor\") {\n // successor is shorter than predecessor, so it is larger\n return 1;\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"predecessor\") {\n // predecessor of [2, 3] contains [2, 1] while predecessor of [2] doesn't, so longer predecessors are larger\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"successor\") {\n // successor of [2, 3] contains [2, 4] while successor of [2] doesn't, so longer successors are smaller\n return 1;\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"exact\") {\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"exact\") {\n return 1;\n }\n throw new Error(`Unexpected key kinds: ${shorterKeyKind}, ${longerKeyKind}`);\n}\nfunction compareKeys(key1, key2) {\n let i = 0;\n while (i < Math.max(key1.value.length, key2.value.length)) {\n const v1 = getValueAtIndex(key1.value, i);\n const v2 = getValueAtIndex(key2.value, i);\n if (v1 === undefined) {\n return compareDanglingSuffix(key1.kind, key2.kind, key1, key2);\n }\n if (v2 === undefined) {\n return -1 * compareDanglingSuffix(key2.kind, key1.kind, key2, key1);\n }\n const result = compareValues(v1.value, v2.value);\n if (result !== 0) {\n return result;\n }\n // if the prefixes are the same so far, keep going with the comparison\n i++;\n }\n if (key1.kind === key2.kind) {\n return 0;\n }\n // keys are the same length and values\n if (key1.kind === \"exact\") {\n if (key2.kind === \"successor\") {\n return -1;\n }\n else {\n return 1;\n }\n }\n if (key1.kind === \"predecessor\") {\n return -1;\n }\n if (key1.kind === \"successor\") {\n return 1;\n }\n // Note: we're being cautious here, but we aren't checking above that the type\n // of key2.kind is valid...\n throw new Error(`Unexpected key kind: ${key1.kind}`);\n}\nfunction serializeCursor(key) {\n return JSON.stringify(convexToJson(key.map((v) => v === undefined\n ? \"undefined\"\n : typeof v === \"string\" && v.endsWith(\"undefined\")\n ? // in the unlikely case their string was \"undefined\"\n // or \"_undefined\" etc, we escape it.\n \"_\" + v\n : v)));\n}\nfunction deserializeCursor(cursor) {\n return jsonToConvex(JSON.parse(cursor)).map((v) => {\n if (typeof v === \"string\") {\n if (v === \"undefined\") {\n // This is a special case for the undefined value.\n // It's not a valid value in the index, but it's a valid value in the\n // cursor.\n return undefined;\n }\n if (v.endsWith(\"undefined\")) {\n // in the unlikely case their string was \"undefined\" it was changed to\n // \"_undefined\" in the serialization process.\n // NB: if their string was \"_undefined\" it was changed to\n // \"__undefined\" in the serialization process, and so on.\n return v.slice(1);\n }\n }\n return v;\n });\n}\n","/* eslint-disable jsdoc/require-jsdoc */\nimport type { BetterAuthDBSchema } from \"better-auth/db\";\nimport type {\n DocumentByName,\n GenericDataModel,\n GenericQueryCtx,\n PaginationOptions,\n PaginationResult,\n SchemaDefinition,\n TableNamesInDataModel,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport { asyncMap } from \"convex-helpers\";\nimport { mergedStream, stream } from \"convex-helpers/server/stream\";\n\nexport type QueryArgs = {\n limit?: number;\n model: string;\n offset?: number;\n select?: string[];\n sortBy?: {\n direction: \"asc\" | \"desc\";\n field: string;\n };\n where?: WhereClause[];\n};\n\nexport type WhereClause = {\n connector?: \"AND\" | \"OR\";\n field: string;\n operator?:\n | \"contains\"\n | \"ends_with\"\n | \"eq\"\n | \"gt\"\n | \"gte\"\n | \"in\"\n | \"lt\"\n | \"lte\"\n | \"ne\"\n | \"not_in\"\n | \"starts_with\";\n value: boolean | null | number | number[] | string | string[];\n};\n\nexport const isUniqueField = (\n betterAuthSchema: BetterAuthDBSchema,\n model: string,\n field: string,\n): boolean => {\n const fields = betterAuthSchema[model]?.fields;\n if (!fields) {\n return false;\n }\n return Object.entries(fields)\n .filter(([, value]) => value.unique)\n .map(([key]) => key)\n .includes(field);\n};\n\nexport const hasUniqueFields = (\n betterAuthSchema: BetterAuthDBSchema,\n model: string,\n input: Record<string, any>,\n): boolean => {\n for (const field of Object.keys(input)) {\n if (isUniqueField(betterAuthSchema, model, field)) {\n return true;\n }\n }\n return false;\n};\n\nexport const findIndex = (\n schema: SchemaDefinition<any, any>,\n args: QueryArgs,\n) => {\n if (\n (args.where?.length ?? 0) > 1 &&\n args.where?.some((w) => w.connector === \"OR\")\n ) {\n throw new Error(\n `OR connector not supported with multiple where statements in findIndex, split up the where statements before calling findIndex: ${JSON.stringify(args.where)}`,\n );\n }\n const where = args.where?.filter((w) => {\n return (\n (!w.operator ||\n [\"eq\", \"gt\", \"gte\", \"in\", \"lt\", \"lte\", \"not_in\"].includes(\n w.operator,\n )) &&\n w.field !== \"_id\"\n );\n });\n if (!where?.length && !args.sortBy) {\n return;\n }\n const lowerBounds =\n where?.filter((w) => w.operator === \"lt\" || w.operator === \"lte\") ?? [];\n if (lowerBounds.length > 1) {\n throw new Error(\n `cannot have more than one lower bound where clause: ${JSON.stringify(where)}`,\n );\n }\n const upperBounds =\n where?.filter((w) => w.operator === \"gt\" || w.operator === \"gte\") ?? [];\n if (upperBounds.length > 1) {\n throw new Error(\n `cannot have more than one upper bound where clause: ${JSON.stringify(where)}`,\n );\n }\n const lowerBound = lowerBounds[0];\n const upperBound = upperBounds[0];\n if (lowerBound && upperBound && lowerBound.field !== upperBound.field) {\n throw new Error(\n `lower bound and upper bound must have the same field: ${JSON.stringify(where)}`,\n );\n }\n const boundField = lowerBound?.field ?? upperBound?.field;\n if (\n boundField &&\n where?.some(\n (w) => w.field === boundField && w !== lowerBound && w !== upperBound,\n )\n ) {\n throw new Error(\n `too many where clauses on the bound field: ${JSON.stringify(where)}`,\n );\n }\n const indexEqFields =\n where\n ?.filter((w) => !w.operator || w.operator === \"eq\")\n .sort((a, b) => {\n return a.field.localeCompare(b.field);\n })\n .map((w) => [w.field, w.value]) ?? [];\n if (!indexEqFields?.length && !boundField && !args.sortBy) {\n return;\n }\n const table = schema.tables[args.model as keyof typeof schema.tables];\n if (!table) {\n throw new Error(`Table ${args.model} not found`);\n }\n const indexes = table[\" indexes\"]();\n const sortField = args.sortBy?.field;\n\n // We internally use _creationTime in place of Better Auth's createdAt\n const indexFields = indexEqFields\n .map(([field]) => field)\n .concat(\n boundField && boundField !== \"createdAt\"\n ? `${indexEqFields.length ? \"_\" : \"\"}${boundField}`\n : \"\",\n )\n .concat(\n sortField && sortField !== \"createdAt\" && boundField !== sortField\n ? `${indexEqFields.length || boundField ? \"_\" : \"\"}${sortField}`\n : \"\",\n )\n .filter(Boolean);\n if (!indexFields.length && !boundField && !sortField) {\n return;\n }\n // Use the built in _creationTime index if bounding or sorting by createdAt\n // with no other fields\n const index = !indexFields.length\n ? {\n fields: [],\n indexDescriptor: \"by_creation_time\",\n }\n : indexes.find(({ fields }: { fields: string[] }) => {\n const fieldsMatch = indexFields.every(\n (field, idx) => field === fields[idx],\n );\n // If sorting by createdAt, no intermediate fields can be on the index\n // as they may override the createdAt sort order.\n const boundFieldMatch =\n boundField === \"createdAt\" || sortField === \"createdAt\"\n ? indexFields.length === fields.length\n : true;\n return fieldsMatch && boundFieldMatch;\n });\n if (!index) {\n return { indexFields };\n }\n return {\n boundField,\n index: {\n fields: [...index.fields, \"_creationTime\"],\n indexDescriptor: index.indexDescriptor,\n },\n sortField,\n values: {\n eq: indexEqFields.map(([, value]) => value),\n gt: upperBound?.operator === \"gt\" ? upperBound.value : undefined,\n gte: upperBound?.operator === \"gte\" ? upperBound.value : undefined,\n lt: lowerBound?.operator === \"lt\" ? lowerBound.value : undefined,\n lte: lowerBound?.operator === \"lte\" ? lowerBound.value : undefined,\n },\n };\n};\n\nexport const checkUniqueFields = async <\n Schema extends SchemaDefinition<any, any>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: Schema,\n betterAuthSchema: BetterAuthDBSchema,\n table: string,\n input: Record<string, any>,\n doc?: Record<string, any>,\n) => {\n if (!hasUniqueFields(betterAuthSchema, table, input)) {\n return;\n }\n for (const field of Object.keys(input)) {\n if (!isUniqueField(betterAuthSchema, table, field)) {\n continue;\n }\n const { index } =\n findIndex(schema, {\n model: table,\n where: [{ field, operator: \"eq\", value: input[field] }],\n }) ?? {};\n if (!index) {\n throw new Error(`No index found for ${table}.${field}`);\n }\n const existingDoc = await ctx.db\n .query(table as any)\n .withIndex(index.indexDescriptor, (q) => q.eq(field, input[field]))\n .unique();\n if (existingDoc && existingDoc._id !== doc?._id) {\n throw new Error(`${table} ${field} already exists`);\n }\n }\n};\n\nexport const selectFields = <\n T extends TableNamesInDataModel<GenericDataModel>,\n D extends DocumentByName<GenericDataModel, T>,\n>(\n doc: D | null,\n select?: string[],\n): D | null => {\n if (!doc) {\n return null;\n }\n if (!select?.length) {\n return doc;\n }\n return select.reduce((acc, field) => {\n (acc as any)[field] = doc[field];\n return acc;\n }, {} as D);\n};\n\nexport const filterByWhere = <\n T extends TableNamesInDataModel<GenericDataModel>,\n D extends DocumentByName<GenericDataModel, T>,\n>(\n doc: D | null,\n where?: WhereClause[],\n // Optionally filter which where clauses to apply.\n filterWhere?: (w: WhereClause) => any,\n): boolean => {\n if (!doc) {\n return false;\n }\n for (const w of where ?? []) {\n if (filterWhere && !filterWhere(w)) {\n continue;\n }\n const value = doc[w.field as keyof typeof doc] as WhereClause[\"value\"];\n const isLessThan = (val: typeof value, wVal: typeof w.value) => {\n if (!wVal) {\n return false;\n }\n if (!val) {\n return true;\n }\n return val < wVal;\n };\n const isGreaterThan = (val: typeof value, wVal: typeof w.value) => {\n if (!val) {\n return false;\n }\n if (!wVal) {\n return true;\n }\n return val > wVal;\n };\n const filter = (w: WhereClause) => {\n switch (w.operator) {\n case \"contains\": {\n return typeof value === \"string\" && value.includes(w.value as string);\n }\n case \"ends_with\": {\n return typeof value === \"string\" && value.endsWith(w.value as string);\n }\n case \"eq\":\n case undefined: {\n return value === w.value;\n }\n case \"gt\": {\n return isGreaterThan(value, w.value);\n }\n case \"gte\": {\n return value === w.value || isGreaterThan(value, w.value);\n }\n case \"in\": {\n return Array.isArray(w.value) && (w.value as any[]).includes(value);\n }\n case \"lt\": {\n return isLessThan(value, w.value);\n }\n case \"lte\": {\n return value === w.value || isLessThan(value, w.value);\n }\n case \"ne\": {\n return value !== w.value;\n }\n case \"not_in\": {\n return Array.isArray(w.value) && !(w.value as any[]).includes(value);\n }\n case \"starts_with\": {\n return (\n typeof value === \"string\" && value.startsWith(w.value as string)\n );\n }\n }\n };\n if (!filter(w)) {\n return false;\n }\n }\n return true;\n};\n\nconst generateQuery = (\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n args: QueryArgs,\n) => {\n const { boundField, index, indexFields, values } =\n findIndex(schema, args) ?? {};\n const query = stream(ctx.db as any, schema).query(args.model as any);\n const hasValues =\n values?.eq?.length ??\n values?.lt ??\n values?.lte ??\n values?.gt ??\n values?.gte;\n const indexedQuery =\n index && index.indexDescriptor !== \"by_creation_time\"\n ? query.withIndex(\n index.indexDescriptor,\n hasValues\n ? (q: any) => {\n for (const [idx, value] of (values?.eq ?? []).entries()) {\n q = q.eq(index.fields[idx], value);\n }\n if (values?.lt) {\n q = q.lt(boundField, values.lt);\n }\n if (values?.lte) {\n q = q.lte(boundField, values.lte);\n }\n if (values?.gt) {\n q = q.gt(boundField, values.gt);\n }\n if (values?.gte) {\n q = q.gte(boundField, values.gte);\n }\n return q;\n }\n : undefined,\n )\n : query;\n const orderedQuery = args.sortBy\n ? indexedQuery.order(args.sortBy.direction === \"desc\" ? \"desc\" : \"asc\")\n : indexedQuery;\n const filteredQuery = orderedQuery.filterWith(async (doc) => {\n if (!index && indexFields?.length) {\n console.warn(\n `Querying without an index on table \"${args.model}\".\\n` +\n `This can cause performance issues, and may hit the document read limit.\\n` +\n `To fix, add an index that begins with the following fields in order:\\n` +\n `[${indexFields.join(\", \")}]`,\n );\n // No index, handle all where clauses statically.\n return filterByWhere(doc, args.where);\n }\n return filterByWhere(\n doc,\n args.where,\n // Index used for all eq and range clauses, apply remaining clauses\n // incompatible with Convex statically.\n (w) =>\n w.operator &&\n [\"contains\", \"ends_with\", \"ne\", \"not_in\", \"starts_with\"].includes(\n w.operator,\n ),\n );\n });\n return filteredQuery;\n};\n\nexport const paginate = async <\n Doc extends DocumentByName<GenericDataModel, T>,\n T extends TableNamesInDataModel<GenericDataModel>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n betterAuthSchema: BetterAuthDBSchema,\n args: QueryArgs & {\n paginationOpts: PaginationOptions;\n },\n): Promise<PaginationResult<Doc>> => {\n if (args.offset) {\n throw new Error(`offset not supported: ${JSON.stringify(args.offset)}`);\n }\n if (args.where?.some((w) => w.connector === \"OR\") && args.where?.length > 1) {\n throw new Error(\n `OR connector not supported with multiple where statements in paginate, split up the where statements before calling paginate: ${JSON.stringify(args.where)}`,\n );\n }\n if (\n args.where?.some(\n (w) =>\n w.field === \"_id\" &&\n w.operator &&\n ![\"eq\", \"in\", \"not_in\"].includes(w.operator),\n )\n ) {\n throw new Error(\n `_id can only be used with eq, in, or not_in operator: ${JSON.stringify(args.where)}`,\n );\n }\n // If any where clause is \"eq\" (or missing operator) on a unique field,\n // we can only return a single document, so we get it and use any other\n // where clauses as static filters.\n const uniqueWhere = args.where?.find(\n (w) =>\n (!w.operator || w.operator === \"eq\") &&\n (isUniqueField(betterAuthSchema, args.model, w.field) ||\n w.field === \"_id\"),\n );\n if (uniqueWhere) {\n const { index } =\n findIndex(schema, {\n model: args.model,\n where: [uniqueWhere],\n }) ?? {};\n\n let doc;\n if (uniqueWhere.field === \"_id\") {\n doc = await ctx.db.get(uniqueWhere.value as GenericId<T>);\n } else if (index?.indexDescriptor) {\n doc = await ctx.db\n .query(args.model as any)\n .withIndex(index.indexDescriptor, (q) =>\n q.eq(index.fields[0], uniqueWhere.value),\n )\n .unique();\n } else {\n // No index found - fall back to collect() for unique field lookup\n const results = await ctx.db.query(args.model as any).collect();\n doc =\n results.find((d: any) => d[uniqueWhere.field] === uniqueWhere.value) ??\n null;\n }\n\n // Apply all other clauses as static filters to our 0 or 1 result.\n if (filterByWhere(doc, args.where, (w) => w !== uniqueWhere)) {\n return {\n continueCursor: \"\",\n isDone: true,\n page: [selectFields(doc, args.select)].filter(Boolean) as Doc[],\n };\n }\n return {\n continueCursor: \"\",\n isDone: true,\n page: [],\n };\n }\n\n const paginationOpts = {\n ...args.paginationOpts,\n // If maximumRowsRead is not at least 1 higher than numItems, bad cursors\n // and incorrect paging will result (at least with convex-test).\n maximumRowsRead: Math.max((args.paginationOpts.numItems ?? 0) + 1, 200),\n };\n\n // Large queries using \"in\" clause will crash, but these are only currently\n // possible with the organization plugin listing all members with a high\n // limit. For cases like this we need to create proper convex queries in\n // the component as an alternative to using Better Auth api's.\n const inWhere = args.where?.find((w) => w.operator === \"in\");\n if (inWhere) {\n if (!Array.isArray(inWhere.value)) {\n throw new Error(\"in clause value must be an array\");\n }\n // For ids, just use asyncMap + .get()\n if (inWhere.field === \"_id\") {\n const docs = await asyncMap(inWhere.value as any[], async (value) => {\n return ctx.db.get(value as GenericId<T>);\n });\n const filteredDocs = docs\n .flatMap((doc) => (doc ? [doc] : []))\n .filter((doc) => filterByWhere(doc, args.where, (w) => w !== inWhere));\n\n return {\n continueCursor: \"\",\n isDone: true,\n page: filteredDocs.sort((a, b) => {\n if (args.sortBy?.field === \"createdAt\") {\n return args.sortBy.direction === \"asc\"\n ? (a._creationTime as number) - (b._creationTime as number)\n : (b._creationTime as number) - (a._creationTime as number);\n }\n if (args.sortBy) {\n const aValue = a[args.sortBy.field];\n const bValue = b[args.sortBy.field];\n if (aValue === bValue) {\n return 0;\n }\n return args.sortBy.direction === \"asc\"\n ? aValue! > bValue!\n ? 1\n : -1\n : aValue! > bValue!\n ? -1\n : 1;\n }\n return 0;\n }) as Doc[],\n };\n }\n const streams = inWhere.value.map((value) => {\n return generateQuery(ctx, schema, {\n ...args,\n where: args.where?.map((w) => {\n if (w === inWhere) {\n return { ...w, operator: \"eq\" as const, value };\n }\n return w;\n }),\n });\n });\n const result = await mergedStream(\n streams,\n [\n args.sortBy?.field !== \"createdAt\" && args.sortBy?.field,\n \"_creationTime\",\n ].flatMap((f) => (f ? [f] : [])),\n ).paginate(paginationOpts);\n return {\n ...result,\n page: await asyncMap(result.page, (doc) =>\n selectFields(doc, args.select),\n ),\n };\n }\n\n const query = generateQuery(ctx, schema, args);\n const result = await query.paginate(paginationOpts);\n return {\n ...result,\n page: await asyncMap(result.page, (doc) => selectFields(doc, args.select)),\n };\n};\n\nexport const listOne = async <\n Doc extends DocumentByName<GenericDataModel, T>,\n T extends TableNamesInDataModel<GenericDataModel>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n betterAuthSchema: BetterAuthDBSchema,\n args: QueryArgs,\n): Promise<Doc | null> => {\n return (\n await paginate(ctx, schema, betterAuthSchema, {\n ...args,\n paginationOpts: {\n cursor: null,\n numItems: 1,\n },\n })\n ).page[0] as Doc | null;\n};\n","import type { GenericDataModel, GenericMutationCtx, GenericQueryCtx } from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\nimport type { CollectionSlug, VexApiAuth } from \"@vexcms/core\";\n\n/**\n * Builds the `getAuth` resolver for `collectionsApi` from better-auth's\n * conventions — no per-app auth plumbing.\n *\n * Resolution chain, all from the validated JWT the `convex()` better-auth\n * plugin mints: `identity.subject` (user doc id) → user document;\n * `identity.sessionId` (appended to every token by the plugin) → session\n * document → `session.activeOrganizationId` → organization document.\n * Documents are read fresh on every request, so role changes and\n * `identity.sessionId` (appended to every token by the plugin) → session\n * document → `session.activeOrganizationId` → organization document.\n * Documents are read fresh on every request, so role changes and\n * org switches apply immediately — claims are only used as ids, never\n * as authorization data.\n *\n * @returns { user, organization }, @see {@link VexApiAuth}\n *\n */\nexport function createGetAuth<TCollectionSlug extends CollectionSlug = CollectionSlug>(props: {\n userCollectionSlug: TCollectionSlug;\n orgCollectionSlug: TCollectionSlug;\n sessionCollectionSlug: TCollectionSlug;\n resolveOrgs?: boolean;\n}) {\n return async <DataModel extends GenericDataModel>(\n ctx: GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n ): Promise<VexApiAuth> => {\n const identity = await ctx.auth.getUserIdentity();\n if (identity === null) {\n return { user: null }; // unauthenticated → downstream deny (no roles)\n }\n\n const user = await ctx.db.get(\n props.userCollectionSlug,\n identity.subject as GenericId<TCollectionSlug>,\n );\n if (user === null) {\n return { user }; // token for a deleted user → deny\n }\n\n if (!props.resolveOrgs) {\n return { user };\n }\n const sessionId = identity.sessionId as GenericId<TCollectionSlug> | undefined;\n const session = sessionId ? await ctx.db.get(props.sessionCollectionSlug, sessionId) : null;\n const orgId = session?.activeOrganizationId as GenericId<TCollectionSlug> | undefined;\n const organization = orgId\n ? ((await ctx.db.get(props.orgCollectionSlug, orgId)) ?? undefined)\n : undefined;\n\n return { user, organization };\n };\n}\n","import type {\n GenericActionCtx,\n GenericDataModel,\n GenericMutationCtx,\n GenericQueryCtx,\n MutationBuilder,\n QueryBuilder,\n SchemaDefinition,\n} from \"convex/server\";\nimport { convexAdapter } from \"./adapter\";\nimport * as DB from \"./db\";\n\n/**\n * Arguments for authDbApi — same pattern as queryApi/mutationApi in @vexcms/core.\n *\n * The user imports their Convex schema from `convex/schema.ts` and passes it here.\n */\nexport type AuthDbApiOptions<DataModel extends GenericDataModel> = {\n /** The user's Convex schema (from `convex/schema.ts`). */\n schema: SchemaDefinition<any, any>;\n /** The user's `internalMutation` from `convex/_generated/server`. */\n internalMutation: MutationBuilder<DataModel, \"internal\">;\n /** The user's `internalQuery` from `convex/_generated/server`. */\n internalQuery: QueryBuilder<DataModel, \"internal\">;\n};\n\n/**\n * Creates the auth DB operations as proper Convex functions.\n *\n * Use this in www/convex/auth/db.ts to export the db operations:\n * ```ts\n * import { authDbApi } from \"@vexcms/better-auth/convex\"\n * import { internalMutation, internalQuery } from \"../../_generated/server\"\n * import schema from \"../schema\"\n *\n * export const { dbCreate, dbFindOne, dbFindMany, dbCount, dbUpdate, dbUpdateMany, dbDelete, dbDeleteMany } = authDbApi({\n * schema,\n * internalMutation,\n * internalQuery,\n * })\n * ```\n *\n * This follows the exact same pattern as queryApi/mutationApi in @vexcms/core.\n * The returned functions are proper Convex FunctionReferences available as\n * internal.auth.db.dbCreate, etc. in the user's Convex API.\n * @param options - The user's Convex schema plus their `internalMutation`\n * and `internalQuery` builders, used to construct the auth DB functions.\n * @returns An object exposing `dbCreate`, `dbFindOne`, `dbFindMany`,\n * `dbCount`, `dbUpdate`, `dbUpdateMany`, `dbDelete`, and `dbDeleteMany` as\n * internal Convex function references, ready to re-export from the\n * user's Convex API.\n */\nexport function authDbApi<DataModel extends GenericDataModel>(\n options: AuthDbApiOptions<DataModel>,\n) {\n return {\n dbCreate: options.internalMutation({\n ...DB.create,\n handler: async (ctx, args) =>\n await DB.create.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbFindOne: options.internalQuery({\n ...DB.findOne,\n handler: async (ctx, args) =>\n await DB.findOne.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbFindMany: options.internalQuery({\n ...DB.findMany,\n handler: async (ctx, args) =>\n await DB.findMany.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbCount: options.internalQuery({\n ...DB.count,\n handler: async (ctx, args) =>\n await DB.count.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbUpdate: options.internalMutation({\n ...DB.update,\n handler: async (ctx, args) =>\n await DB.update.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbUpdateMany: options.internalMutation({\n ...DB.updateMany,\n handler: async (ctx, args) =>\n await DB.updateMany.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbDelete: options.internalMutation({\n ...DB.deleteOne,\n handler: async (ctx, args) =>\n await DB.deleteOne.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbDeleteMany: options.internalMutation({\n ...DB.deleteMany,\n handler: async (ctx, args) =>\n await DB.deleteMany.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n };\n}\n\n/**\n * Creates the Better Auth Convex adapter.\n *\n * Use this in www/convex/auth/index.ts inside createAuth:\n * ```ts\n * import { createBetterAuthAdapter } from \"@vexcms/better-auth/convex\"\n * import { dbCreate, dbFindOne, ... } from \"./db\"\n *\n * export const createAuth = (ctx) => {\n * return betterAuth({\n * database: createBetterAuthAdapter(ctx, { dbCreate, dbFindOne, ... }),\n * ...authOptions,\n * })\n * }\n * ```\n *\n * The adapter uses anyApi to reference the db operations (anyApi.auth.db.dbCreate etc.)\n * and calls them via ctx.runMutation/ctx.runQuery.\n * @param ctx ActionCtx from better-auth convex library\n * @returns AdapterFactory\n */\nexport function createBetterAuthAdapter<DataModel extends GenericDataModel>(\n ctx: GenericActionCtx<DataModel>,\n) {\n return convexAdapter(ctx);\n}\n\nexport { convexAdapter } from \"./adapter\";\nexport * from \"./types\";\nexport * from \"./getAuth\";\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,qBAAqB;AAc9B,IAAM,wBAAwB;AAAA,EAC5B,MAAM;AAAA,EACN,SAAS;AAAA,EACT,SAAS;AAAA,EACT,cAAc;AAChB;AAGA,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAmCM,SAAS,kBACd,OACgB;A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AA,IAED,UAAU,QAAQ,iBAAiB;AAAA,MACjC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,UAAU;AAAA,QACjB;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,IAED,cAAc,QAAQ,iBAAiB;AAAA,MACrC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,WAAW;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,EACH;AACF;AAuBO,SAAS,wBACd,KACA;AACA,SAAO,cAAc,GAAG;AAC1B;","names":["v","getAuthTables","where","select","update","commonPrefix","index","stream","_","result","orderingIndexFields","v","select","w","result","select","result","update"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter.ts","../src/convex/adapter.ts","../src/convex/db.ts","../../../node_modules/.pnpm/convex-helpers@0.1.120_@standard-schema+spec@1.1.0_convex@1.44.0_react@19.2.7__hono@4.1_fda37119e0b134c2babc8f4bd1faf097/node_modules/convex-helpers/index.js","../../../node_modules/.pnpm/convex-helpers@0.1.120_@standard-schema+spec@1.1.0_convex@1.44.0_react@19.2.7__hono@4.1_fda37119e0b134c2babc8f4bd1faf097/node_modules/convex-helpers/server/stream.js","../src/convex/utils.ts","../src/convex/getAuth.ts","../src/convex/index.ts"],"sourcesContent":["import type {\n AuthCollectionConfig,\n AuthFieldMeta,\n BaseFieldInput,\n CollectionSlug,\n FieldAdminConfigInput,\n VexAuthAdapter,\n} from \"@vexcms/core\";\nimport {\n array,\n AuthCollectionMeta,\n checkbox,\n date,\n defineCollection,\n number,\n select,\n text,\n} from \"@vexcms/core\";\nimport type { BetterAuthOptions, DBFieldAttribute } from \"better-auth\";\nimport { getAuthTables } from \"better-auth/db\";\n\n/**\n * Options for `betterAuthAdapter()`.\n *\n * Accepts the same `BetterAuthOptions` object you pass to `betterAuth()`\n * on the server. Only schema-affecting properties (modelNames,\n * additionalFields, plugins) are read. Runtime options (database, secret,\n * baseURL) are ignored.\n */\nexport interface BetterAuthAdapterOptions {\n config: BetterAuthOptions;\n}\n\nconst AUTH_COLLECTION_TYPES = {\n user: \"user\",\n session: \"session\",\n account: \"account\",\n verification: \"verification\",\n} as const;\n\n/** Fields on the user table that end-users are allowed to edit. */\nconst EDITABLE_FIELDS = new Set([\n \"name\",\n \"email\",\n \"image\",\n \"role\",\n \"banned\",\n \"banReason\",\n \"banExpires\",\n]);\n\n/** Fields that should be hidden in the admin UI for security. */\nconst HIDDEN_FIELDS = new Set([\n \"hashedPassword\",\n \"password\",\n \"twoFactorSecret\",\n \"twoFactorBackupCodes\",\n \"token\",\n \"secret\",\n \"code\",\n]);\n\n/**\n * Creates a Vex auth adapter from a Better Auth configuration.\n *\n * Introspects Better Auth's full merged schema (base fields + plugin fields\n * + additionalFields) via `getAuthTables()` and converts each table into a\n * standard Vex `CollectionConfig` using Vex field builders.\n *\n * Mappings from Better Auth `DBFieldAttribute` to Vex fields:\n * - `type` → Vex field type (`string`→text, `boolean`→checkbox, `number`→number,\n * `date`/`timestamp`→date, `json`→text fallback, array→select)\n * - `required` → field `required`\n * - `defaultValue` → field `defaultValue`\n * - `unique`/`index` → field `index` (index name: `by_<field>_unique` or `by_<field>`)\n * - `references` → `relationship` field\n * - System fields get `admin.readOnly: true` and `meta.locked: true`\n * - Sensitive fields get `admin.hidden: true`\n *\n * @param props — Adapter options; pass your Better Auth config object wrapped\n * in `{ config: authOptions }`. Optional — when omitted, uses default\n * Better Auth tables with no plugins or additional fields.\n * @returns A `VexAuthAdapter` ready for `defineConfig({ auth: … })`.\n *\n * @example\n * ```ts\n * import { betterAuthAdapter } from \"@vexcms/better-auth\";\n * import { authOptions } from \"~/auth/server\";\n *\n * export default defineConfig({\n * auth: betterAuthAdapter({ config: authOptions }),\n * collections: [posts],\n * });\n * ```\n */\nexport function betterAuthAdapter(\n props?: BetterAuthAdapterOptions,\n): VexAuthAdapter {\n const tables = getAuthTables(props?.config ?? {});\n const collections: AuthCollectionConfig[] = [];\n const authCollections = [\n { type: AUTH_COLLECTION_TYPES.user, slug: props?.config?.user?.modelName },\n {\n type: AUTH_COLLECTION_TYPES.session,\n slug: props?.config?.session?.modelName,\n },\n {\n type: AUTH_COLLECTION_TYPES.account,\n slug: props?.config?.account?.modelName,\n },\n {\n type: AUTH_COLLECTION_TYPES.verification,\n slug: props?.config?.verification?.modelName,\n },\n ] as const;\n\n for (const [tableKey, tableDef] of Object.entries(tables)) {\n const slug = tableDef.modelName ?? tableKey;\n const fields: AuthCollectionConfig[\"fields\"] = {};\n\n addAuthCollectionFields({\n attributes: tableDef.fields,\n slug,\n fields,\n config: props?.config,\n extractId: true,\n });\n\n const authCollectionType = authCollections.find(\n (ac) => ac.slug === slug,\n )?.type;\n if (authCollectionType) {\n switch (authCollectionType) {\n case \"user\": {\n const additionalFields = props?.config?.user?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"session\": {\n const additionalFields = props?.config?.session?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"account\": {\n const additionalFields = props?.config?.account?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n case \"verification\": {\n const additionalFields =\n props?.config?.verification?.additionalFields;\n addAuthCollectionFields({\n attributes: additionalFields,\n slug,\n fields,\n config: props?.config,\n });\n break;\n }\n default:\n break;\n }\n }\n\n const isProtected = slug !== \"user\" && slug !== \"users\";\n\n collections.push(\n defineCollection<AuthFieldMeta, AuthCollectionMeta>({\n slug: slug as CollectionSlug,\n fields,\n meta: isProtected ? { protected: true } : undefined,\n }),\n );\n }\n\n const userSlug = tables.user?.modelName ?? \"user\";\n return {\n name: \"better-auth\",\n collections,\n userCollection: userSlug as CollectionSlug,\n };\n}\n\n/**\n * Converts a set of Better Auth field attributes into Vex field definitions\n * and appends them to the given collection `fields` map.\n *\n * Iterates over `attributes`, calls {@link betterAuthAttrToVexField} for each\n * entry, and mutates `props.fields` in place. When `extractId` is `true`,\n * the `id` field is skipped because Convex auto-generates `_id`.\n *\n * @param props — Field extraction options.\n * @param props.attributes — Better Auth `DBFieldAttribute` map to convert.\n * @param props.slug — Collection slug (used for relationship target resolution).\n * @param props.fields — Mutable Vex collection fields object to populate.\n * @param props.config — Better Auth options (for model name / additional fields lookups).\n * @param props.extractId — When `true`, skips the `id` field.\n *\n * @internal\n */\nexport function addAuthCollectionFields(props: {\n attributes?: Record<string, DBFieldAttribute>;\n slug: string;\n fields: AuthCollectionConfig[\"fields\"];\n config?: BetterAuthOptions;\n extractId?: boolean;\n}) {\n if (!props.attributes) return;\n for (const [fieldName, attr] of Object.entries(props.attributes)) {\n if (props.extractId === true && fieldName === \"id\") continue;\n const field = betterAuthAttrToVexField(\n fieldName,\n attr,\n props.slug,\n props?.config,\n );\n if (field) props.fields[fieldName] = field;\n }\n}\n\n/**\n * Maps a single Better Auth `DBFieldAttribute` to a Vex field builder call.\n *\n * Handles all Better Auth scalar types: `string`, `boolean`, `number`, `date`,\n * `timestamp`, `json`, and enum arrays. Maps overlapping properties\n * (`required`, `defaultValue`, `unique`/`index`, `references`) to their\n * Vex equivalents. Sets `admin.readOnly` and `meta.locked` on system\n * fields, and `admin.hidden` on sensitive fields.\n *\n * @param fieldName — The field name from Better Auth.\n * @param attr — The Better Auth field attribute.\n * @param tableSlug — The collection slug (for relationship targets).\n * @param authOptions -- The betterAuth options\n * @returns A Vex field instance, or `null` if the type is unsupported.\n *\n * @internal\n */\nfunction betterAuthAttrToVexField(\n fieldName: string,\n attr: DBFieldAttribute,\n tableSlug: string,\n authOptions?: BetterAuthOptions,\n) {\n // Skip id — Convex auto-generates _id\n if (fieldName === \"id\") return null;\n\n const isUserTable =\n tableSlug === authOptions?.user?.modelName ||\n tableSlug === \"user\" ||\n tableSlug === \"users\";\n const isEditable = isUserTable && EDITABLE_FIELDS.has(fieldName);\n const isHidden = HIDDEN_FIELDS.has(fieldName);\n\n const admin: FieldAdminConfigInput = {};\n if (!isEditable) admin.readOnly = true;\n if (isHidden) admin.hidden = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const baseOptions: { defaultValue: any } & BaseFieldInput<AuthFieldMeta> = {\n defaultValue: undefined,\n };\n if (Object.keys(admin).length > 0) baseOptions.admin = admin;\n if (!isEditable) baseOptions.meta = { locked: true };\n if (attr.required) baseOptions.required = attr.required;\n if (\n attr.defaultValue !== undefined &&\n typeof attr.defaultValue !== \"function\"\n ) {\n baseOptions.defaultValue = attr.defaultValue;\n }\n if (attr.unique || attr.index) {\n baseOptions.index = `by_${fieldName}`;\n }\n\n if (attr.references) {\n return text(baseOptions);\n }\n\n if (Array.isArray(attr.type)) {\n return select({\n options: attr.type.map((v: string) => ({ value: v, label: v })),\n ...baseOptions,\n });\n }\n\n switch (attr.type) {\n case \"string\":\n return text(baseOptions);\n case \"string[]\":\n return array({\n ...baseOptions,\n items: text(baseOptions),\n });\n case \"boolean\":\n return checkbox(baseOptions);\n case \"number\":\n return number(baseOptions);\n case \"number[]\":\n return array({\n ...baseOptions,\n items: number(baseOptions),\n });\n case \"date\":\n return date(baseOptions);\n case \"json\":\n // Fall back to text until a dedicated json field type is wired\n // TODO: create json field\n return text(baseOptions);\n default:\n // Unknown type — skip rather than crash\n return null;\n }\n}\n","import type { Where } from \"better-auth/types\";\nimport type { GenericActionCtx, GenericDataModel } from \"convex/server\";\nimport { anyApi } from \"convex/server\";\nimport {\n createAdapterFactory,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { getAuthTables } from \"better-auth/db\";\n\ntype ConvexCleanedWhere = Where & {\n value: boolean | null | number | number[] | string | string[];\n};\n\nconst parseWhere = (where?: Where[]): ConvexCleanedWhere[] => {\n return (where?.map((where) => {\n if (where.value instanceof Date) {\n return { ...where, value: where.value.getTime() };\n }\n return where;\n }) ?? []) as ConvexCleanedWhere[];\n};\n\n/**\n * Creates the Convex database adapter for Better Auth.\n *\n * @param ctx - The Convex action context\n * @param config - Optional debug log configuration\n * @returns AdapterFactory<BetterAuthOptions>\n */\nexport function convexAdapter<DataModel extends GenericDataModel>(\n ctx: GenericActionCtx<DataModel>,\n config: { debugLogs?: DBAdapterDebugLogOption } = {},\n) {\n return createAdapterFactory({\n adapter: ({ options }) => {\n options.telemetry = { enabled: false };\n const betterAuthSchema = getAuthTables(options);\n const betterAuthSchemaJson = JSON.stringify(betterAuthSchema);\n\n return {\n id: \"convex\",\n options: { isRunMutationCtx: \"runMutation\" in ctx },\n\n // Use anyApi to reference db operations, call via ctx.runMutation/ctx.runQuery\n create: async ({ data, model, select }) => {\n return await ctx.runMutation(anyApi.auth.db.dbCreate, {\n betterAuthSchema: betterAuthSchemaJson,\n data,\n model,\n select,\n });\n },\n\n findOne: async ({ model, select, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbFindOne, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n select,\n where: parseWhere(where),\n });\n },\n\n findMany: async ({ limit, model, sortBy, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbFindMany, {\n betterAuthSchema: betterAuthSchemaJson,\n limit,\n model,\n sortBy,\n where: parseWhere(where),\n });\n },\n\n count: async ({ model, where }) => {\n return await ctx.runQuery(anyApi.auth.db.dbCount, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n update: async ({ model, update, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbUpdate, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n update,\n where: parseWhere(where),\n });\n },\n\n updateMany: async ({ model, update, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbUpdateMany, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n update,\n where: parseWhere(where),\n });\n },\n\n delete: async ({ model, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbDelete, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n deleteMany: async ({ model, where }) => {\n return await ctx.runMutation(anyApi.auth.db.dbDeleteMany, {\n betterAuthSchema: betterAuthSchemaJson,\n model,\n where: parseWhere(where),\n });\n },\n\n transaction: async () => {\n throw new Error(\"Transactions not supported\");\n },\n };\n },\n config: {\n adapterId: \"convex\",\n adapterName: \"Convex Adapter\",\n customTransformInput: ({ data, fieldAttributes }) =>\n data && fieldAttributes.type === \"date\"\n ? new Date(data).getTime()\n : data,\n customTransformOutput: ({ data, fieldAttributes }) =>\n data && fieldAttributes.type === \"date\"\n ? new Date(data).getTime()\n : data,\n debugLogs: config.debugLogs ?? false,\n disableIdGeneration: true,\n mapKeysTransformInput: { id: \"_id\" },\n mapKeysTransformOutput: { _id: \"id\" },\n supportsArrays: true,\n supportsDates: false,\n supportsJSON: true,\n supportsNumericIds: false,\n transaction: false,\n usePlural: false,\n },\n });\n}\n","/* eslint-disable jsdoc/require-jsdoc */\nimport type { BetterAuthDBSchema } from \"better-auth/db\";\nimport type {\n GenericQueryCtx,\n GenericMutationCtx,\n GenericDataModel,\n SchemaDefinition,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport { v } from \"convex/values\";\n\nimport {\n checkUniqueFields,\n listOne,\n paginate,\n selectFields,\n type WhereClause,\n} from \"./utils\";\n\n// Helper to get Better Auth schema - we'll pass it from the adapter\nconst getBetterAuthSchema = (schemaJson: string): BetterAuthDBSchema => {\n return JSON.parse(schemaJson);\n};\n\ninterface CreateArgs {\n betterAuthSchema: string;\n data: any;\n model: string;\n select?: string[];\n}\n\nexport const create = {\n args: {\n betterAuthSchema: v.string(),\n data: v.any(),\n model: v.string(),\n select: v.optional(v.array(v.string())),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, data, model, select }: CreateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n\n await checkUniqueFields(ctx, schema, authSchema, model, data as any);\n\n const id = await ctx.db.insert(model as any, data as any);\n const doc = await ctx.db.get(id);\n if (!doc) {\n throw new Error(`Failed to create ${model}`);\n }\n\n return selectFields(doc, select);\n },\n};\n\ninterface FindOneArgs {\n betterAuthSchema: string;\n model: string;\n select?: string[];\n where: unknown[];\n}\n\nexport const findOne = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n select: v.optional(v.array(v.string())),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, model, select, where }: FindOneArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const result = await listOne(ctx, schema, authSchema, {\n model,\n select,\n where: where as WhereClause[],\n });\n\n return result;\n },\n};\n\ninterface FindManyArgs {\n betterAuthSchema: string;\n limit?: number;\n model: string;\n sortBy?: { direction: \"asc\" | \"desc\"; field: string };\n where?: unknown[];\n}\n\nexport const findMany = {\n args: {\n betterAuthSchema: v.string(),\n limit: v.optional(v.number()),\n model: v.string(),\n sortBy: v.optional(\n v.object({\n direction: v.union(v.literal(\"asc\"), v.literal(\"desc\")),\n field: v.string(),\n }),\n ),\n where: v.optional(v.array(v.any())),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, limit, model, sortBy, where }: FindManyArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = (where ?? []) as WhereClause[];\n\n // Handle OR connector by running parallel queries\n if (parsedWhere.some((w) => w.connector === \"OR\")) {\n const results = await Promise.all(\n parsedWhere.map(async (w) => {\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: limit ?? 200 },\n sortBy,\n where: [w],\n });\n return result.page;\n }),\n );\n\n // De-duplicate and flatten\n const seen = new Set<string>();\n const uniqueDocs: any[] = [];\n for (const docs of results) {\n for (const doc of docs) {\n const docId = doc._id as string;\n if (!seen.has(docId)) {\n seen.add(docId);\n uniqueDocs.push(doc);\n }\n }\n }\n\n // Apply sorting if needed\n if (sortBy) {\n uniqueDocs.sort((a, b) => {\n const aVal = a[sortBy.field];\n const bVal = b[sortBy.field];\n if (aVal === bVal) {\n return 0;\n }\n const comparison = aVal > bVal ? 1 : -1;\n return sortBy.direction === \"desc\" ? -comparison : comparison;\n });\n }\n\n return uniqueDocs.slice(0, limit);\n }\n\n // Normal case without OR\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: limit ?? 200 },\n sortBy,\n where: parsedWhere,\n });\n\n return result.page;\n },\n};\n\ninterface CountArgs {\n betterAuthSchema: string;\n model: string;\n where?: unknown[];\n}\n\nexport const count = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.optional(v.array(v.any())),\n },\n handler: async (\n ctx: GenericQueryCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: CountArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = (where ?? []) as WhereClause[];\n\n // Handle OR connector\n if (parsedWhere.some((w) => w.connector === \"OR\")) {\n const results = await Promise.all(\n parsedWhere.map(async (w) => {\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: [w],\n });\n return result.page;\n }),\n );\n\n // De-duplicate and count\n const seen = new Set<string>();\n for (const docs of results) {\n for (const doc of docs) {\n const docId = doc._id as string;\n seen.add(docId);\n }\n }\n return seen.size;\n }\n\n // Normal case\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n return result.page.length;\n },\n};\n\ninterface UpdateArgs {\n betterAuthSchema: string;\n model: string;\n update: any;\n where: unknown[];\n}\n\nexport const update = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n update: v.any(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, update, where }: UpdateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n // Find the document to update\n const doc = await listOne(ctx, schema, authSchema, {\n model,\n where: parsedWhere,\n });\n\n if (!doc) {\n return null;\n }\n\n // Check unique fields before update\n await checkUniqueFields(ctx, schema, authSchema, model, update as any, doc);\n\n await ctx.db.patch(doc._id as GenericId<any>, update as any);\n return await ctx.db.get(doc._id as GenericId<any>);\n },\n};\n\n// Update many operation\nexport const updateMany = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n update: v.any(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, update, where }: UpdateArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n // Check unique fields if updating multiple docs\n if (result.page.length > 1) {\n const uniqueFieldKeys = Object.keys(update as any).filter(\n (key) => authSchema[model]?.fields?.[key]?.unique,\n );\n if (uniqueFieldKeys.length > 0) {\n throw new Error(\n `Attempted to set unique fields in multiple documents in ${model} with the same value. Fields: ${uniqueFieldKeys.join(\", \")}`,\n );\n }\n }\n\n // Update each document\n for (const doc of result.page) {\n await checkUniqueFields(\n ctx,\n schema,\n authSchema,\n model,\n update as any,\n doc,\n );\n await ctx.db.patch(doc._id as GenericId<any>, update as any);\n }\n\n return result.page.length;\n },\n};\n\ninterface DeleteArgs {\n betterAuthSchema: string;\n model: string;\n where: unknown[];\n}\n\nexport const deleteOne = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: DeleteArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const doc = await listOne(ctx, schema, authSchema, {\n model,\n where: parsedWhere,\n });\n\n if (!doc) {\n return;\n }\n\n await ctx.db.delete(doc._id as GenericId<any>);\n },\n};\n\n// Delete many operation\nexport const deleteMany = {\n args: {\n betterAuthSchema: v.string(),\n model: v.string(),\n where: v.array(v.any()),\n },\n handler: async (\n ctx: GenericMutationCtx<GenericDataModel>,\n { betterAuthSchema, model, where }: DeleteArgs,\n schema: SchemaDefinition<any, any>,\n ) => {\n const authSchema = getBetterAuthSchema(betterAuthSchema);\n const parsedWhere = where as WhereClause[];\n\n const result = await paginate(ctx, schema, authSchema, {\n model,\n paginationOpts: { cursor: null, numItems: 200 },\n where: parsedWhere,\n });\n\n // Delete each document\n for (const doc of result.page) {\n await ctx.db.delete(doc._id as GenericId<any>);\n }\n\n return result.page.length;\n },\n};\n","/**\n * asyncMap returns the results of applying an async function over an list.\n *\n * The list can even be a promise, or an iterable like a Set.\n * @param list - Iterable object of items, e.g. an Array, Set, Object.keys\n * @param asyncTransform\n * @returns\n */\nexport async function asyncMap(list, asyncTransform) {\n const promises = [];\n let index = 0;\n list = await list;\n for (const item of list) {\n promises.push(asyncTransform(item, index));\n index += 1;\n }\n return Promise.all(promises);\n}\n/**\n * Filters out null elements from an array.\n * @param list List of elements that might be null.\n * @returns List of elements with nulls removed.\n */\nexport function pruneNull(list) {\n return list.filter((i) => i !== null);\n}\nexport class NullDocumentError extends Error {\n}\n/**\n * Throws if there is a null element in the array.\n * @param list List of elements that might have a null element.\n * @returns Same list of elements with a refined type.\n */\nexport function nullThrows(doc, message) {\n if (doc === null) {\n throw new NullDocumentError(message ?? \"Unexpected null document.\");\n }\n return doc;\n}\n/**\n * pick helps you pick keys from an object more concisely.\n *\n * e.g. `pick({a: v.string(), b: v.number()}, [\"a\"])` is equivalent to\n * `{a: v.string()}`\n * The alternative could be something like:\n * ```js\n * const obj = { a: v.string(), b: v.number() };\n * // pick does the following\n * const { a } = obj;\n * const onlyA = { a };\n * ```\n *\n * @param obj The object to pick from. Often like { a: v.string() }\n * @param keys The keys to pick from the object.\n * @returns A new object with only the keys you picked and their values.\n */\nexport function pick(obj, keys) {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));\n}\n/**\n * omit helps you omit keys from an object more concisely.\n *\n * e.g. `omit({a: v.string(), b: v.number()}, [\"a\"])` is equivalent to\n * `{b: v.number()}`\n *\n * The alternative could be something like:\n * ```js\n * const obj = { a: v.string(), b: v.number() };\n * // omit does the following\n * const { a, ...rest } = obj;\n * const withoutA = rest;\n * ```\n *\n * @param obj The object to return a copy of without the specified keys.\n * @param keys The keys to omit from the object.\n * @returns A new object with the keys you omitted removed.\n */\nexport function omit(obj, keys) {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));\n}\n/**\n * Removes the _id and _creationTime fields from an object.\n * This enables easily cloning a Convex document like:\n * ```ts\n * const doc = await db.get(id);\n * const clone = withoutSystemFields(doc);\n * await db.insert(table, clone);\n * ```\n * @param obj The object to remove the _id and _creationTime fields from.\n * @returns A new object with the _id and _creationTime fields removed.\n */\nexport function withoutSystemFields(obj) {\n return omit(obj, [\"_id\", \"_creationTime\"]);\n}\n// Type utils:\nconst _error = Symbol();\n/**\n * A utility to validate truthiness at runtime, providing a type guard\n *\n * @example\n * ```ts\n * const x: string | null = getValue();\n * assert(x);\n * // x is now of type string\n * ```\n * You can also provide a function, to avoid doing expensive string templating.\n * @param arg A value to assert the truthiness of.\n * @param message An optional message to throw if the value is not truthy, or a function to generate the message.\n */\nexport function assert(value, message) {\n if (!value) {\n throw new Error(typeof message === \"function\" ? message() : message);\n }\n}\n","import { convexToJson, compareValues, jsonToConvex, getDocumentSize, } from \"convex/values\";\n// From https://docs.convex.dev/production/state/limits#transactions\nconst MAX_DOCUMENT_SCAN_LEN = 32000;\n// Value used to trigger page split suggestions. This is kind of\n// a backstop value to mitigate additional scans over the full\n// original range if documents change later. Making it smaller\n// would result in more splits (equal to the divisor) as the\n// number of documents scanned approaches the max.\nconst SOFT_MAX_SCAN_LEN = MAX_DOCUMENT_SCAN_LEN / 2;\n//\n// Helper functions\n//\nfunction makeExclusive(boundType) {\n if (boundType === \"gt\" || boundType === \"gte\") {\n return \"gt\";\n }\n return \"lt\";\n}\n/** Split a range query between two index keys into a series of range queries\n * that should be executed in sequence. This is necessary because Convex only\n * supports range queries of the form\n * q.eq(\"f1\", v).eq(\"f2\", v).lt(\"f3\", v).gt(\"f3\", v).\n * i.e. all fields must be equal except for the last field, which can have\n * two inequalities.\n *\n * For example, the range from >[1, 2, 3] to <=[1, 3, 2] would be split into\n * the following queries:\n * 1. q.eq(\"f1\", 1).eq(\"f2\", 2).gt(\"f3\", 3)\n * 2. q.eq(\"f1\", 1).gt(\"f2\", 2).lt(\"f2\", 3)\n * 3. q.eq(\"f1\", 1).eq(\"f2\", 3).lte(\"f3\", 2)\n */\nfunction splitRange(indexFields, \n// For descending queries, the resulting queries are reversed.\norder, startBound, endBound, startBoundType, endBoundType) {\n // Three parts to the split:\n // 1. reduce down from startBound to common prefix\n // 2. range with common prefix\n // 3. build back up from common prefix to endBound\n const commonPrefix = [];\n while (startBound.length > 0 &&\n endBound.length > 0 &&\n compareValues(startBound[0], endBound[0]) === 0) {\n const indexField = indexFields[0];\n indexFields = indexFields.slice(1);\n const eqBound = startBound[0];\n startBound = startBound.slice(1);\n endBound = endBound.slice(1);\n commonPrefix.push([\"eq\", indexField, eqBound]);\n }\n const makeCompare = (boundType, key) => {\n const range = commonPrefix.slice();\n let i = 0;\n for (; i < key.length - 1; i++) {\n range.push([\"eq\", indexFields[i], key[i]]);\n }\n if (i < key.length) {\n range.push([boundType, indexFields[i], key[i]]);\n }\n return range;\n };\n // Stage 1.\n const startRanges = [];\n while (startBound.length > 1) {\n startRanges.push(makeCompare(startBoundType, startBound));\n startBoundType = makeExclusive(startBoundType);\n startBound = startBound.slice(0, -1);\n }\n // Stage 3.\n const endRanges = [];\n while (endBound.length > 1) {\n endRanges.push(makeCompare(endBoundType, endBound));\n endBoundType = makeExclusive(endBoundType);\n endBound = endBound.slice(0, -1);\n }\n endRanges.reverse();\n // Stage 2.\n let middleRange;\n if (endBound.length === 0) {\n middleRange = makeCompare(startBoundType, startBound);\n }\n else if (startBound.length === 0) {\n middleRange = makeCompare(endBoundType, endBound);\n }\n else {\n const startValue = startBound[0];\n const endValue = endBound[0];\n middleRange = commonPrefix.slice();\n middleRange.push([startBoundType, indexFields[0], startValue]);\n middleRange.push([endBoundType, indexFields[0], endValue]);\n }\n const ranges = [...startRanges, middleRange, ...endRanges];\n if (order === \"desc\") {\n ranges.reverse();\n }\n return ranges;\n}\nfunction rangeToQuery(range) {\n return (q) => {\n for (const [boundType, field, value] of range) {\n q = q[boundType](field, value);\n }\n return q;\n };\n}\n/**\n * Get the ordered list of fields for a given table's index based on the schema.\n *\n * - For \"by_creation_time\", returns [\"_creationTime\", \"_id\"].\n * - For \"by_id\", returns [\"_id\"].\n * - Otherwise, looks up the named index in the schema and returns its fields\n * followed by [\"_creationTime\", \"_id\"].\n * e.g. for an index defined like `.index(\"abc\", [\"a\", \"b\"])`,\n * returns [\"a\", \"b\", \"_creationTime\", \"_id\"].\n */\nexport function getIndexFields(table, index, schema) {\n const indexDescriptor = String(index ?? \"by_creation_time\");\n if (indexDescriptor === \"by_creation_time\") {\n return [\"_creationTime\", \"_id\"];\n }\n if (indexDescriptor === \"by_id\") {\n return [\"_id\"];\n }\n if (!schema) {\n throw new Error(\"schema is required to infer index fields\");\n }\n const tableInfo = schema.tables[table];\n const indexInfo = tableInfo.indexes.find((index) => index.indexDescriptor === indexDescriptor);\n if (!indexInfo) {\n throw new Error(`Index ${indexDescriptor} not found in table ${table}`);\n }\n const fields = indexInfo.fields.slice();\n fields.push(\"_creationTime\");\n fields.push(\"_id\");\n return fields;\n}\nfunction getIndexKey(doc, indexFields) {\n const key = [];\n for (const field of indexFields) {\n let obj = doc;\n for (const subfield of field.split(\".\")) {\n obj = obj[subfield];\n }\n key.push(obj);\n }\n return key;\n}\n/**\n * A \"stream\" is an async iterable of query results, ordered by an index on a table.\n *\n * Use it as you would use `ctx.db`.\n * If using pagination in a reactive query, see the warnings on the `paginator`\n * function. TL;DR: you need to pass in `endCursor` to prevent holes or overlaps\n * between pages.\n *\n * Once you have a stream, you can use `mergeStreams` or `filterStream` to make\n * more streams. Then use `queryStream` to convert it into an OrderedQuery,\n * so you can call `.paginate()`, `.collect()`, etc.\n */\nexport function stream(db, schema) {\n return new StreamDatabaseReader(db, schema);\n}\n/**\n * A \"QueryStream\" is an async iterable of query results, ordered by indexed fields.\n */\nexport class QueryStream {\n /// Methods for creating new streams as modifications of the current stream.\n /**\n * Create a new stream with a TypeScript filter applied.\n *\n * This is similar to `db.query(tableName).filter(predicate)`, but it's more\n * general because it can call arbitrary TypeScript code, including more\n * database queries.\n *\n * All documents filtered out are still considered \"read\" from the database;\n * they are just excluded from the output stream.\n *\n * In contrast to `filter` from convex-helpers/server/filter, this filterWith\n * is applied *before* any pagination. That means if the filter excludes a lot\n * of documents, the `.paginate()` method will read a lot of documents until\n * it gets as many documents as it wants. If you run into issues with reading\n * too much data, you can pass `maximumRowsRead` to `paginate()`.\n */\n filterWith(predicate) {\n const order = this.getOrder();\n return new FlatMapStream(this, async (doc) => {\n const filtered = (await predicate(doc)) ? doc : null;\n return new SingletonStream(filtered, order, [], [], []);\n }, []);\n }\n /**\n * Create a new stream where each element is the result of applying the mapper\n * function to the elements of the original stream.\n *\n * Similar to how [1, 2, 3].map(x => x * 2) => [2, 4, 6]\n */\n map(mapper) {\n const order = this.getOrder();\n return new FlatMapStream(this, async (doc) => {\n const mapped = await mapper(doc);\n return new SingletonStream(mapped, order, [], [], []);\n }, []);\n }\n /**\n * Similar to flatMap on an array, but iterate over a stream, and the for each\n * element, iterate over the stream created by the mapper function.\n *\n * Ordered by the original stream order, then the mapped stream. Similar to\n * how [\"a\", \"b\"].flatMap(letter => [letter, letter]) => [\"a\", \"a\", \"b\", \"b\"]\n *\n * @param mapper A function that takes a document and returns a new stream.\n * @param mappedIndexFields The index fields of the streams created by mapper.\n * @returns A stream of documents returned by the mapper streams,\n * grouped by the documents in the original stream.\n */\n flatMap(mapper, mappedIndexFields) {\n normalizeIndexFields(mappedIndexFields);\n return new FlatMapStream(this, mapper, mappedIndexFields);\n }\n /**\n * Get the first item from the original stream for each distinct value of the\n * selected index fields.\n *\n * e.g. if the stream has an equality filter on `a`, and index fields `[a, b, c]`,\n * we can do `stream.distinct([\"b\"])` to get a stream of the first item for\n * each distinct value of `b`.\n * Similarly, you could do `stream.distinct([\"a\", \"b\"])` with the same result,\n * or `stream.distinct([\"a\", \"b\", \"c\"])` to get the original stream.\n *\n * This stream efficiently skips past items with the same value for the selected\n * distinct index fields.\n *\n * This can be used to perform a loose index scan.\n */\n distinct(distinctIndexFields) {\n return new DistinctStream(this, distinctIndexFields);\n }\n /// Implementation of OrderedQuery\n filter(_predicate) {\n throw new Error(\"Cannot call .filter() directly on a query stream. Use .filterWith() for filtering or .collect() if you want to convert the stream to an array first.\");\n }\n async paginate(opts) {\n if (opts.numItems === 0) {\n if (opts.cursor === null) {\n throw new Error(\".paginate called with cursor of null and 0 for numItems. \" +\n \"This is not supported, as null is not a valid continueCursor. \" +\n \"Advice: avoid calling paginate entirely in these cases.\");\n }\n return {\n page: [],\n isDone: false,\n continueCursor: opts.cursor,\n };\n }\n const order = this.getOrder();\n let newStartKey = {\n key: [],\n inclusive: true,\n };\n if (opts.cursor !== null) {\n newStartKey = {\n key: deserializeCursor(opts.cursor),\n inclusive: false,\n };\n }\n let newEndKey = {\n key: [],\n inclusive: true,\n };\n const maxRowsToRead = opts.maximumRowsRead;\n let maxRows = opts.numItems;\n if (opts.endCursor) {\n newEndKey = {\n key: deserializeCursor(opts.endCursor),\n inclusive: true,\n };\n // If there's an endCursor, continue until we get there even if it's more\n // than numItems.\n maxRows = undefined;\n }\n const newLowerBound = order === \"asc\" ? newStartKey : newEndKey;\n const newUpperBound = order === \"asc\" ? newEndKey : newStartKey;\n const narrowStream = this.narrow({\n lowerBound: newLowerBound.key,\n lowerBoundInclusive: newLowerBound.inclusive,\n upperBound: newUpperBound.key,\n upperBoundInclusive: newUpperBound.inclusive,\n });\n const page = [];\n const indexKeys = [];\n let hasMore = opts.endCursor && opts.endCursor !== \"[]\";\n let continueCursor = opts.endCursor ?? \"[]\";\n const maxBytesToRead = opts.maximumBytesRead;\n const trackBandwidth = maxBytesToRead !== undefined;\n let totalBytesRead = 0;\n let hitLimit = false;\n for await (const [doc, indexKey, bandwidth] of narrowStream.iterWithKeys(trackBandwidth)) {\n if (doc !== null) {\n page.push(doc);\n }\n indexKeys.push(indexKey);\n totalBytesRead += bandwidth;\n if ((maxBytesToRead !== undefined && totalBytesRead >= maxBytesToRead) ||\n (maxRowsToRead !== undefined && indexKeys.length >= maxRowsToRead)) {\n hitLimit = true;\n }\n if (hitLimit || (maxRows !== undefined && page.length >= maxRows)) {\n hasMore = true;\n continueCursor = serializeCursor(indexKey);\n break;\n }\n }\n let pageStatus = undefined;\n let splitCursor = undefined;\n if (hitLimit) {\n pageStatus = \"SplitRequired\";\n splitCursor = indexKeys[Math.floor((indexKeys.length - 1) / 2)];\n }\n else if (indexKeys.length >= SOFT_MAX_SCAN_LEN ||\n page.length > opts.numItems + 1) {\n pageStatus = \"SplitRecommended\";\n splitCursor = indexKeys[Math.floor((indexKeys.length - 1) / 2)];\n }\n return {\n page,\n isDone: !hasMore,\n continueCursor,\n pageStatus,\n splitCursor: splitCursor ? serializeCursor(splitCursor) : undefined,\n };\n }\n async collect() {\n return await this.take(Infinity);\n }\n async take(n) {\n const results = [];\n for await (const [doc] of this.iterWithKeys()) {\n if (doc === null) {\n continue;\n }\n results.push(doc);\n if (results.length === n) {\n break;\n }\n }\n return results;\n }\n async unique() {\n const docs = await this.take(2);\n if (docs.length === 2) {\n throw new Error(\"Query is not unique\");\n }\n return docs[0] ?? null;\n }\n async first() {\n const docs = await this.take(1);\n return docs[0] ?? null;\n }\n [Symbol.asyncIterator]() {\n const iterator = this.iterWithKeys()[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n return { done: false, value: result.value[0] };\n },\n };\n }\n}\nexport class StreamDatabaseReader {\n db;\n schema;\n // TODO: support system tables\n system;\n constructor(db, schema) {\n this.db = db;\n this.schema = schema;\n this.system = db.system;\n }\n query(tableName) {\n return new StreamQueryInitializer(this, tableName);\n }\n get(_id) {\n throw new Error(\"get() not supported for `paginator`\");\n }\n normalizeId(_tableName, _id) {\n throw new Error(\"normalizeId() not supported for `paginator`.\");\n }\n}\nexport class StreamableQuery extends QueryStream {\n}\nexport class StreamQueryInitializer extends StreamableQuery {\n parent;\n table;\n constructor(parent, table) {\n super();\n this.parent = parent;\n this.table = table;\n }\n fullTableScan() {\n return this.withIndex(\"by_creation_time\");\n }\n withIndex(indexName, indexRange) {\n const indexFields = getIndexFields(this.table, indexName, this.parent.schema);\n const q = new ReflectIndexRange(indexFields);\n if (indexRange) {\n indexRange(q);\n }\n return new StreamQuery(this, indexName, q, indexRange);\n }\n withSearchIndex(_indexName, _searchFilter) {\n throw new Error(\"Cannot paginate withSearchIndex\");\n }\n inner() {\n return this.fullTableScan();\n }\n order(order) {\n return this.inner().order(order);\n }\n reflect() {\n return this.inner().reflect();\n }\n iterWithKeys(trackBandwidth = false) {\n return this.inner().iterWithKeys(trackBandwidth);\n }\n getOrder() {\n return this.inner().getOrder();\n }\n getEqualityIndexFilter() {\n return this.inner().getEqualityIndexFilter();\n }\n getIndexFields() {\n return this.inner().getIndexFields();\n }\n narrow(indexBounds) {\n return this.inner().narrow(indexBounds);\n }\n}\n// Not to be confused with QueryStream or StreamableQuery.\nexport class StreamQuery extends StreamableQuery {\n parent;\n index;\n q;\n indexRange;\n constructor(parent, index, q, indexRange) {\n super();\n this.parent = parent;\n this.index = index;\n this.q = q;\n this.indexRange = indexRange;\n }\n order(order) {\n return new OrderedStreamQuery(this, order);\n }\n inner() {\n return this.order(\"asc\");\n }\n reflect() {\n return this.inner().reflect();\n }\n iterWithKeys(trackBandwidth = false) {\n return this.inner().iterWithKeys(trackBandwidth);\n }\n getOrder() {\n return this.inner().getOrder();\n }\n getEqualityIndexFilter() {\n return this.inner().getEqualityIndexFilter();\n }\n getIndexFields() {\n return this.inner().getIndexFields();\n }\n narrow(indexBounds) {\n return this.inner().narrow(indexBounds);\n }\n}\nexport class OrderedStreamQuery extends StreamableQuery {\n parent;\n order;\n constructor(parent, order) {\n super();\n this.parent = parent;\n this.order = order;\n }\n reflect() {\n return {\n db: this.parent.parent.parent.db,\n schema: this.parent.parent.parent.schema,\n table: this.parent.parent.table,\n index: this.parent.index,\n indexFields: this.parent.q.indexFields,\n order: this.order,\n bounds: {\n lowerBound: this.parent.q.lowerBoundIndexKey ?? [],\n lowerBoundInclusive: this.parent.q.lowerBoundInclusive,\n upperBound: this.parent.q.upperBoundIndexKey ?? [],\n upperBoundInclusive: this.parent.q.upperBoundInclusive,\n },\n indexRange: this.parent.indexRange,\n };\n }\n /**\n * inner() is as if you had used ctx.db to construct the query.\n */\n inner() {\n const { db, table, index, order, indexRange } = this.reflect();\n return db.query(table).withIndex(index, indexRange).order(order);\n }\n iterWithKeys(trackBandwidth = false) {\n const { indexFields } = this.reflect();\n const iterable = this.inner();\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n const doc = result.value;\n const bandwidth = trackBandwidth ? getDocumentSize(doc) : 0;\n return {\n done: false,\n value: [doc, getIndexKey(doc, indexFields), bandwidth],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.order;\n }\n getEqualityIndexFilter() {\n return this.parent.q.equalityIndexFilter;\n }\n getIndexFields() {\n return this.parent.q.indexFields;\n }\n narrow(indexBounds) {\n const { db, table, index, order, bounds, schema } = this.reflect();\n let maxLowerBound = bounds.lowerBound;\n let maxLowerBoundInclusive = bounds.lowerBoundInclusive;\n if (compareKeys({\n value: indexBounds.lowerBound,\n kind: indexBounds.lowerBoundInclusive ? \"predecessor\" : \"successor\",\n }, {\n value: bounds.lowerBound,\n kind: bounds.lowerBoundInclusive ? \"predecessor\" : \"successor\",\n }) > 0) {\n maxLowerBound = indexBounds.lowerBound;\n maxLowerBoundInclusive = indexBounds.lowerBoundInclusive;\n }\n let minUpperBound = bounds.upperBound;\n let minUpperBoundInclusive = bounds.upperBoundInclusive;\n if (compareKeys({\n value: indexBounds.upperBound,\n kind: indexBounds.upperBoundInclusive ? \"successor\" : \"predecessor\",\n }, {\n value: bounds.upperBound,\n kind: bounds.upperBoundInclusive ? \"successor\" : \"predecessor\",\n }) < 0) {\n minUpperBound = indexBounds.upperBound;\n minUpperBoundInclusive = indexBounds.upperBoundInclusive;\n }\n return streamIndexRange(db, schema, table, index, {\n lowerBound: maxLowerBound,\n lowerBoundInclusive: maxLowerBoundInclusive,\n upperBound: minUpperBound,\n upperBoundInclusive: minUpperBoundInclusive,\n }, order);\n }\n}\n/**\n * Create a stream of documents using the given index and bounds.\n */\nexport function streamIndexRange(db, schema, table, index, bounds, order) {\n const indexFields = getIndexFields(table, index, schema);\n const splitBounds = splitRange(indexFields, order, bounds.lowerBound, bounds.upperBound, bounds.lowerBoundInclusive ? \"gte\" : \"gt\", bounds.upperBoundInclusive ? \"lte\" : \"lt\");\n const subQueries = splitBounds.map((splitBound) => stream(db, schema)\n .query(table)\n .withIndex(index, rangeToQuery(splitBound))\n .order(order));\n return new ConcatStreams(...subQueries);\n}\nclass ReflectIndexRange {\n indexFields;\n #hasSuffix = false;\n lowerBoundIndexKey = undefined;\n lowerBoundInclusive = true;\n upperBoundIndexKey = undefined;\n upperBoundInclusive = true;\n equalityIndexFilter = [];\n constructor(indexFields) {\n this.indexFields = indexFields;\n }\n eq(field, value) {\n if (!this.#canLowerBound(field) || !this.#canUpperBound(field)) {\n throw new Error(`Cannot use eq on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.equalityIndexFilter.push(value);\n return this;\n }\n lt(field, value) {\n if (!this.#canUpperBound(field)) {\n throw new Error(`Cannot use lt on field '${field}'`);\n }\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.upperBoundInclusive = false;\n this.#hasSuffix = true;\n return this;\n }\n lte(field, value) {\n if (!this.#canUpperBound(field)) {\n throw new Error(`Cannot use lte on field '${field}'`);\n }\n this.upperBoundIndexKey = this.upperBoundIndexKey ?? [];\n this.upperBoundIndexKey.push(value);\n this.#hasSuffix = true;\n return this;\n }\n gt(field, value) {\n if (!this.#canLowerBound(field)) {\n throw new Error(`Cannot use gt on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.lowerBoundInclusive = false;\n this.#hasSuffix = true;\n return this;\n }\n gte(field, value) {\n if (!this.#canLowerBound(field)) {\n throw new Error(`Cannot use gte on field '${field}'`);\n }\n this.lowerBoundIndexKey = this.lowerBoundIndexKey ?? [];\n this.lowerBoundIndexKey.push(value);\n this.#hasSuffix = true;\n return this;\n }\n #canLowerBound(field) {\n const currentLowerBoundLength = this.lowerBoundIndexKey?.length ?? 0;\n const currentUpperBoundLength = this.upperBoundIndexKey?.length ?? 0;\n if (currentLowerBoundLength > currentUpperBoundLength) {\n // Already have a lower bound.\n return false;\n }\n if (currentLowerBoundLength === currentUpperBoundLength &&\n this.#hasSuffix) {\n // Already have a lower bound and an upper bound.\n return false;\n }\n return (currentLowerBoundLength < this.indexFields.length &&\n this.indexFields[currentLowerBoundLength] === field);\n }\n #canUpperBound(field) {\n const currentLowerBoundLength = this.lowerBoundIndexKey?.length ?? 0;\n const currentUpperBoundLength = this.upperBoundIndexKey?.length ?? 0;\n if (currentUpperBoundLength > currentLowerBoundLength) {\n // Already have an upper bound.\n return false;\n }\n if (currentLowerBoundLength === currentUpperBoundLength &&\n this.#hasSuffix) {\n // Already have a lower bound and an upper bound.\n return false;\n }\n return (currentUpperBoundLength < this.indexFields.length &&\n this.indexFields[currentUpperBoundLength] === field);\n }\n}\n/**\n * Merge multiple streams, provided in any order, into a single stream.\n *\n * The streams will be merged into a stream of documents ordered by the index keys,\n * i.e. by \"author\" (then by the implicit \"_creationTime\").\n *\n * e.g. ```ts\n * mergedStream([\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user3\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * ], [\"author\"])\n * ```\n *\n * returns a stream of messages for user1, then user2, then user3.\n *\n * You can also use `orderByIndexFields` to change the indexed fields before merging, which changes the order of the merged stream.\n * This only works if the streams are already ordered by `orderByIndexFields`,\n * which happens if each does a .eq(field, value) on all index fields before `orderByIndexFields`.\n *\n * e.g. if the \"by_author\" index is defined as being ordered by [\"author\", \"_creationTime\"],\n * and each query does an equality lookup on \"author\", each individual query before merging is in fact ordered by \"_creationTime\".\n *\n * e.g. ```ts\n * mergedStream([\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user3\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * ], [\"_creationTime\"])\n * ```\n *\n * This returns a stream of messages from all three users, sorted by creation time.\n */\nexport function mergedStream(streams, orderByIndexFields) {\n return new MergedStream(streams, orderByIndexFields);\n}\nexport class MergedStream extends QueryStream {\n #order;\n #streams;\n #equalityIndexFilter;\n #indexFields;\n constructor(streams, orderByIndexFields) {\n super();\n if (streams.length === 0) {\n throw new Error(\"Cannot union empty array of streams\");\n }\n this.#order = allSame(streams.map((stream) => stream.getOrder()), \"Cannot merge streams with different orders\");\n this.#streams = streams.map((stream) => new OrderByStream(stream, orderByIndexFields));\n this.#indexFields = allSame(this.#streams.map((stream) => stream.getIndexFields()), \"Cannot merge streams with different index fields. Consider using .orderBy()\");\n // Calculate common prefix of equality index filters.\n this.#equalityIndexFilter = commonPrefix(this.#streams.map((stream) => stream.getEqualityIndexFilter()));\n }\n iterWithKeys(trackBandwidth = false) {\n const iterables = this.#streams.map((stream) => stream.iterWithKeys(trackBandwidth));\n const comparisonInversion = this.#order === \"asc\" ? 1 : -1;\n return {\n [Symbol.asyncIterator]() {\n const iterators = iterables.map((iterable) => iterable[Symbol.asyncIterator]());\n const results = Array(iterators.length);\n // Track bandwidth from pre-fetched documents not yet yielded\n const pendingBandwidth = Array(iterators.length).fill(0);\n return {\n async next() {\n let bandwidthThisIteration = 0;\n // Fill results from iterators with no value yet.\n await Promise.all(iterators.map(async (iterator, i) => {\n if (!results[i]) {\n const result = await iterator.next();\n results[i] = result;\n // Track bandwidth from pre-fetched documents\n if (trackBandwidth && !result.done && result.value) {\n pendingBandwidth[i] = result.value[2];\n }\n }\n }));\n // Sum all pending bandwidth (pre-fetched docs) for this iteration\n if (trackBandwidth) {\n for (let i = 0; i < pendingBandwidth.length; i++) {\n bandwidthThisIteration += pendingBandwidth[i];\n pendingBandwidth[i] = 0;\n }\n }\n // Find index for the value with the lowest index key.\n let minIndexKeyAndIndex = undefined;\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.done || !result.value) {\n continue;\n }\n const [_, resultIndexKey] = result.value;\n if (minIndexKeyAndIndex === undefined) {\n minIndexKeyAndIndex = [resultIndexKey, i];\n continue;\n }\n const [prevMin] = minIndexKeyAndIndex;\n if (compareKeys({ value: resultIndexKey, kind: \"exact\" }, { value: prevMin, kind: \"exact\" }) *\n comparisonInversion <\n 0) {\n minIndexKeyAndIndex = [resultIndexKey, i];\n }\n }\n if (minIndexKeyAndIndex === undefined) {\n return { done: true, value: undefined };\n }\n const [_, minIndex] = minIndexKeyAndIndex;\n const [doc, indexKey] = results[minIndex].value;\n // indicate that we've used this result\n results[minIndex] = undefined;\n return {\n done: false,\n value: [doc, indexKey, bandwidthThisIteration],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n narrow(indexBounds) {\n return new MergedStream(this.#streams.map((stream) => stream.narrow(indexBounds)), this.#indexFields);\n }\n}\nfunction allSame(values, errorMessage) {\n const first = values[0];\n for (const value of values) {\n if (compareValues(value, first)) {\n throw new Error(errorMessage);\n }\n }\n return first;\n}\nfunction commonPrefix(values) {\n let commonPrefix = values[0];\n for (const value of values) {\n for (let i = 0; i < commonPrefix.length; i++) {\n if (i >= value.length || compareValues(commonPrefix[i], value[i])) {\n commonPrefix = commonPrefix.slice(0, i);\n break;\n }\n }\n }\n return commonPrefix;\n}\n/**\n * Concatenate multiple streams into a single stream.\n * This assumes that the streams correspond to disjoint index ranges,\n * and are provided in the same order as the index ranges.\n *\n * e.g. ```ts\n * new ConcatStreams(\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user1\")),\n * stream(db, schema).query(\"messages\").withIndex(\"by_author\", q => q.eq(\"author\", \"user2\")),\n * )\n * ```\n *\n * is valid, but if the stream arguments were reversed, or the queries were\n * `.order(\"desc\")`, it would be invalid.\n *\n * It's not recommended to use `ConcatStreams` directly, since it has the same\n * behavior as `MergedStream`, but with fewer runtime checks.\n */\nclass ConcatStreams extends QueryStream {\n #order;\n #streams;\n #equalityIndexFilter;\n #indexFields;\n constructor(...streams) {\n super();\n this.#streams = streams;\n if (streams.length === 0) {\n throw new Error(\"Cannot concat empty array of streams\");\n }\n this.#order = allSame(streams.map((stream) => stream.getOrder()), \"Cannot concat streams with different orders. Consider using .orderBy()\");\n this.#indexFields = allSame(streams.map((stream) => stream.getIndexFields()), \"Cannot concat streams with different index fields. Consider using .orderBy()\");\n this.#equalityIndexFilter = commonPrefix(streams.map((stream) => stream.getEqualityIndexFilter()));\n }\n iterWithKeys(trackBandwidth = false) {\n const iterables = this.#streams.map((stream) => stream.iterWithKeys(trackBandwidth));\n const comparisonInversion = this.#order === \"asc\" ? 1 : -1;\n let previousIndexKey = undefined;\n return {\n [Symbol.asyncIterator]() {\n const iterators = iterables.map((iterable) => iterable[Symbol.asyncIterator]());\n return {\n async next() {\n while (iterators.length > 0) {\n const result = await iterators[0].next();\n if (result.done) {\n iterators.shift();\n }\n else {\n const [_, indexKey] = result.value;\n if (previousIndexKey !== undefined &&\n compareKeys({\n value: previousIndexKey,\n kind: \"exact\",\n }, {\n value: indexKey,\n kind: \"exact\",\n }) *\n comparisonInversion >\n 0) {\n throw new Error(`ConcatStreams in wrong order: ${JSON.stringify(previousIndexKey)}, ${JSON.stringify(indexKey)}`);\n }\n previousIndexKey = indexKey;\n return result;\n }\n }\n return { done: true, value: undefined };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n narrow(indexBounds) {\n return new ConcatStreams(...this.#streams.map((stream) => stream.narrow(indexBounds)));\n }\n}\nclass FlatMapStreamIterator {\n #outerStream;\n #outerIterator;\n #currentOuterItem = null;\n #mapper;\n #mappedIndexFields;\n #trackBandwidth;\n constructor(outerStream, mapper, mappedIndexFields, trackBandwidth) {\n this.#outerIterator = outerStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n this.#outerStream = outerStream;\n this.#mapper = mapper;\n this.#mappedIndexFields = mappedIndexFields;\n this.#trackBandwidth = trackBandwidth;\n }\n singletonSkipInnerStream() {\n // If the outer stream is a filtered value, yield a singleton\n // filtered value from the inner stream, with index key of nulls.\n const indexKey = this.#mappedIndexFields.map(() => null);\n return new SingletonStream(null, this.#outerStream.getOrder(), this.#mappedIndexFields, indexKey, indexKey);\n }\n async setCurrentOuterItem(item) {\n const [t, indexKey, bandwidth] = item;\n let innerStream;\n if (t === null) {\n innerStream = this.singletonSkipInnerStream();\n }\n else {\n innerStream = await this.#mapper(t);\n if (!equalIndexFields(innerStream.getIndexFields(), this.#mappedIndexFields)) {\n throw new Error(`FlatMapStream: inner stream has different index fields than expected: ${JSON.stringify(innerStream.getIndexFields())} vs ${JSON.stringify(this.#mappedIndexFields)}`);\n }\n if (innerStream.getOrder() !== this.#outerStream.getOrder()) {\n throw new Error(`FlatMapStream: inner stream has different order than outer stream: ${innerStream.getOrder()} vs ${this.#outerStream.getOrder()}`);\n }\n }\n this.#currentOuterItem = {\n t,\n indexKey,\n innerIterator: innerStream\n .iterWithKeys(this.#trackBandwidth)[Symbol.asyncIterator](),\n count: 0,\n bandwidth,\n };\n }\n async next() {\n if (this.#currentOuterItem === null) {\n const result = await this.#outerIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n await this.setCurrentOuterItem(result.value);\n return await this.next();\n }\n const result = await this.#currentOuterItem.innerIterator.next();\n if (result.done) {\n if (this.#currentOuterItem.count > 0) {\n this.#currentOuterItem = null;\n }\n else {\n // The inner stream was completely empty, so we should inject a null\n // (which will be skipped by everything except the maximumRowsRead count)\n // to account for the cost of the outer stream.\n this.#currentOuterItem.innerIterator = this.singletonSkipInnerStream()\n .iterWithKeys(this.#trackBandwidth)[Symbol.asyncIterator]();\n }\n return await this.next();\n }\n const [u, indexKey, innerBandwidth] = result.value;\n this.#currentOuterItem.count++;\n const fullIndexKey = [...this.#currentOuterItem.indexKey, ...indexKey];\n // On first yield for this outer item, include outer bandwidth\n const bandwidth = (this.#currentOuterItem.count === 1\n ? this.#currentOuterItem.bandwidth\n : 0) + innerBandwidth;\n return { done: false, value: [u, fullIndexKey, bandwidth] };\n }\n}\nclass FlatMapStream extends QueryStream {\n #stream;\n #mapper;\n #mappedIndexFields;\n constructor(stream, mapper, mappedIndexFields) {\n super();\n this.#stream = stream;\n this.#mapper = mapper;\n this.#mappedIndexFields = mappedIndexFields;\n }\n iterWithKeys(trackBandwidth = false) {\n const outerStream = this.#stream;\n const mapper = this.#mapper;\n const mappedIndexFields = this.#mappedIndexFields;\n return {\n [Symbol.asyncIterator]() {\n return new FlatMapStreamIterator(outerStream, mapper, mappedIndexFields, trackBandwidth);\n },\n };\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getEqualityIndexFilter() {\n return this.#stream.getEqualityIndexFilter();\n }\n getIndexFields() {\n return [...this.#stream.getIndexFields(), ...this.#mappedIndexFields];\n }\n narrow(indexBounds) {\n const outerLength = this.#stream.getIndexFields().length;\n const outerLowerBound = indexBounds.lowerBound.slice(0, outerLength);\n const outerUpperBound = indexBounds.upperBound.slice(0, outerLength);\n const innerLowerBound = indexBounds.lowerBound.slice(outerLength);\n const innerUpperBound = indexBounds.upperBound.slice(outerLength);\n const outerIndexBounds = {\n lowerBound: outerLowerBound,\n lowerBoundInclusive: innerLowerBound.length === 0 ? indexBounds.lowerBoundInclusive : true,\n upperBound: outerUpperBound,\n upperBoundInclusive: innerUpperBound.length === 0 ? indexBounds.upperBoundInclusive : true,\n };\n const innerIndexBounds = {\n lowerBound: innerLowerBound,\n lowerBoundInclusive: innerLowerBound.length === 0 ? true : indexBounds.lowerBoundInclusive,\n upperBound: innerUpperBound,\n upperBoundInclusive: innerUpperBound.length === 0 ? true : indexBounds.upperBoundInclusive,\n };\n return new FlatMapStream(this.#stream.narrow(outerIndexBounds), async (t) => {\n const innerStream = await this.#mapper(t);\n return innerStream.narrow(innerIndexBounds);\n }, this.#mappedIndexFields);\n }\n}\nexport class SingletonStream extends QueryStream {\n #value;\n #order;\n #indexFields;\n #indexKey;\n #equalityIndexFilter;\n #bandwidth;\n constructor(value, order = \"asc\", indexFields, indexKey, equalityIndexFilter, bandwidth = 0) {\n super();\n this.#value = value;\n this.#order = order;\n this.#indexFields = indexFields;\n this.#indexKey = indexKey;\n this.#equalityIndexFilter = equalityIndexFilter;\n this.#bandwidth = bandwidth;\n if (indexKey.length !== indexFields.length) {\n throw new Error(`indexKey must have the same length as indexFields: ${JSON.stringify(indexKey)} vs ${JSON.stringify(indexFields)}`);\n }\n }\n iterWithKeys(_trackBandwidth = false) {\n const value = this.#value;\n const indexKey = this.#indexKey;\n const bandwidth = this.#bandwidth;\n return {\n [Symbol.asyncIterator]() {\n let sent = false;\n return {\n async next() {\n if (sent) {\n return { done: true, value: undefined };\n }\n sent = true;\n return {\n done: false,\n value: [value, indexKey, bandwidth],\n };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n getEqualityIndexFilter() {\n return this.#equalityIndexFilter;\n }\n narrow(indexBounds) {\n const compareLowerBound = compareKeys({\n value: indexBounds.lowerBound,\n kind: indexBounds.lowerBoundInclusive ? \"exact\" : \"successor\",\n }, {\n value: this.#indexKey,\n kind: \"exact\",\n });\n const compareUpperBound = compareKeys({\n value: this.#indexKey,\n kind: \"exact\",\n }, {\n value: indexBounds.upperBound,\n kind: indexBounds.upperBoundInclusive ? \"exact\" : \"predecessor\",\n });\n // If lowerBound <= this.indexKey <= upperBound, return this.value\n if (compareLowerBound <= 0 && compareUpperBound <= 0) {\n return new SingletonStream(this.#value, this.#order, this.#indexFields, this.#indexKey, this.#equalityIndexFilter);\n }\n return new EmptyStream(this.#order, this.#indexFields);\n }\n}\n/**\n * This is a completely empty stream that yields no values, and in particular\n * does not count towards maximumRowsRead.\n * Compare to SingletonStream(null, ...), which yields no values but does count\n * towards maximumRowsRead.\n */\nexport class EmptyStream extends QueryStream {\n #order;\n #indexFields;\n constructor(order, indexFields) {\n super();\n this.#order = order;\n this.#indexFields = indexFields;\n }\n iterWithKeys(_trackBandwidth = false) {\n return {\n [Symbol.asyncIterator]() {\n return {\n async next() {\n return { done: true, value: undefined };\n },\n };\n },\n };\n }\n getOrder() {\n return this.#order;\n }\n getIndexFields() {\n return this.#indexFields;\n }\n getEqualityIndexFilter() {\n return [];\n }\n narrow(_indexBounds) {\n return this;\n }\n}\nfunction normalizeIndexFields(indexFields) {\n // Append _creationTime and _id to the index fields if they're not already there\n if (!indexFields.includes(\"_creationTime\")) {\n // With one exception: if indexFields is [\"_id\"], we don't need to add _creationTime\n if (indexFields.length !== 1 || indexFields[0] !== \"_id\") {\n indexFields.push(\"_creationTime\");\n }\n }\n if (!indexFields.includes(\"_id\")) {\n indexFields.push(\"_id\");\n }\n}\n// Given a stream ordered by `indexFields`, where the first `equalityIndexLength`\n// fields are bounded by equality filters, return a generator of the possible\n// index fields used for ordering.\nfunction* getOrderingIndexFields(stream) {\n const streamEqualityIndexLength = stream.getEqualityIndexFilter().length;\n const streamIndexFields = stream.getIndexFields();\n for (let i = 0; i <= streamEqualityIndexLength; i++) {\n yield streamIndexFields.slice(i);\n }\n}\nclass OrderByStream extends QueryStream {\n #staticFilter;\n #stream;\n #indexFields;\n constructor(stream, indexFields) {\n super();\n this.#stream = stream;\n this.#indexFields = indexFields;\n normalizeIndexFields(this.#indexFields);\n // indexFields must be a suffix of the stream's index fields, and include\n // all of the non-equality index fields.\n const streamIndexFields = stream.getIndexFields();\n const orderingIndexFields = Array.from(getOrderingIndexFields(stream));\n if (!orderingIndexFields.some((orderingIndexFields) => equalIndexFields(orderingIndexFields, indexFields))) {\n throw new Error(`indexFields must be some sequence of fields the stream is ordered by: ${JSON.stringify(indexFields)}, ${JSON.stringify(streamIndexFields)} (${stream.getEqualityIndexFilter().length} equality fields)`);\n }\n this.#staticFilter = stream\n .getEqualityIndexFilter()\n .slice(0, streamIndexFields.length - indexFields.length);\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getEqualityIndexFilter() {\n return this.#stream\n .getEqualityIndexFilter()\n .slice(this.#staticFilter.length);\n }\n getIndexFields() {\n return this.#indexFields;\n }\n iterWithKeys(trackBandwidth = false) {\n const iterable = this.#stream.iterWithKeys(trackBandwidth);\n const staticFilter = this.#staticFilter;\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await iterator.next();\n if (result.done) {\n return result;\n }\n const [doc, indexKey, bandwidth] = result.value;\n return {\n done: false,\n value: [doc, indexKey.slice(staticFilter.length), bandwidth],\n };\n },\n };\n },\n };\n }\n narrow(indexBounds) {\n return new OrderByStream(this.#stream.narrow({\n lowerBound: [...this.#staticFilter, ...indexBounds.lowerBound],\n lowerBoundInclusive: indexBounds.lowerBoundInclusive,\n upperBound: [...this.#staticFilter, ...indexBounds.upperBound],\n upperBoundInclusive: indexBounds.upperBoundInclusive,\n }), this.#indexFields);\n }\n}\nclass DistinctStream extends QueryStream {\n #distinctIndexFieldsLength;\n #stream;\n #distinctIndexFields;\n constructor(stream, distinctIndexFields) {\n super();\n this.#stream = stream;\n this.#distinctIndexFields = distinctIndexFields;\n // distinctIndexFields must be a prefix of the stream's ordering index fields\n let distinctIndexFieldsLength = undefined;\n for (const orderingIndexFields of getOrderingIndexFields(stream)) {\n const prefix = orderingIndexFields.slice(0, distinctIndexFields.length);\n if (equalIndexFields(prefix, distinctIndexFields)) {\n const equalityLength = stream.getIndexFields().length - orderingIndexFields.length;\n distinctIndexFieldsLength = equalityLength + distinctIndexFields.length;\n break;\n }\n }\n if (distinctIndexFieldsLength === undefined) {\n throw new Error(`distinctIndexFields must be a prefix of the stream's ordering index fields: ${JSON.stringify(distinctIndexFields)}, ${JSON.stringify(stream.getIndexFields())} (${stream.getEqualityIndexFilter().length} equality fields)`);\n }\n this.#distinctIndexFieldsLength = distinctIndexFieldsLength;\n }\n iterWithKeys(trackBandwidth = false) {\n const stream = this.#stream;\n const distinctIndexFieldsLength = this.#distinctIndexFieldsLength;\n return {\n [Symbol.asyncIterator]() {\n let currentStream = stream;\n let currentIterator = currentStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n return {\n async next() {\n const result = await currentIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n const [doc, indexKey, bandwidth] = result.value;\n if (doc === null) {\n // If the original stream has a post-filter `.filterWith`, we will\n // iterate over filtered items -- possibly many with the same set of\n // distinct index fields -- before finding the first item for the set\n // of distinct index fields.\n // So it's recommended to put `.filterWith` after `.distinct`.\n return {\n done: false,\n value: [null, indexKey, bandwidth],\n };\n }\n const distinctIndexKey = indexKey.slice(0, distinctIndexFieldsLength);\n if (stream.getOrder() === \"asc\") {\n currentStream = currentStream.narrow({\n lowerBound: distinctIndexKey,\n lowerBoundInclusive: false,\n upperBound: [],\n upperBoundInclusive: true,\n });\n }\n else {\n currentStream = currentStream.narrow({\n lowerBound: [],\n lowerBoundInclusive: true,\n upperBound: distinctIndexKey,\n upperBoundInclusive: false,\n });\n }\n currentIterator = currentStream\n .iterWithKeys(trackBandwidth)[Symbol.asyncIterator]();\n return result;\n },\n };\n },\n };\n }\n narrow(indexBounds) {\n const indexBoundsPrefix = {\n ...indexBounds,\n lowerBound: indexBounds.lowerBound.slice(0, this.#distinctIndexFieldsLength),\n upperBound: indexBounds.upperBound.slice(0, this.#distinctIndexFieldsLength),\n };\n return new DistinctStream(this.#stream.narrow(indexBoundsPrefix), this.#distinctIndexFields);\n }\n getOrder() {\n return this.#stream.getOrder();\n }\n getIndexFields() {\n return this.#stream.getIndexFields();\n }\n getEqualityIndexFilter() {\n return this.#stream.getEqualityIndexFilter();\n }\n}\nfunction equalIndexFields(indexFields1, indexFields2) {\n if (indexFields1.length !== indexFields2.length) {\n return false;\n }\n for (let i = 0; i < indexFields1.length; i++) {\n if (indexFields1[i] !== indexFields2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction getValueAtIndex(v, index) {\n if (index >= v.length) {\n return undefined;\n }\n return { kind: \"found\", value: v[index] };\n}\nfunction compareDanglingSuffix(shorterKeyKind, longerKeyKind, shorterKey, longerKey) {\n if (shorterKeyKind === \"exact\" && longerKeyKind === \"exact\") {\n throw new Error(`Exact keys are not the same length: ${JSON.stringify(shorterKey.value)}, ${JSON.stringify(longerKey.value)}`);\n }\n if (shorterKeyKind === \"exact\") {\n throw new Error(`Exact key is shorter than prefix: ${JSON.stringify(shorterKey.value)}, ${JSON.stringify(longerKey.value)}`);\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"successor\") {\n // successor is longer than predecessor, so it is bigger\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"predecessor\") {\n // successor is shorter than predecessor, so it is larger\n return 1;\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"predecessor\") {\n // predecessor of [2, 3] contains [2, 1] while predecessor of [2] doesn't, so longer predecessors are larger\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"successor\") {\n // successor of [2, 3] contains [2, 4] while successor of [2] doesn't, so longer successors are smaller\n return 1;\n }\n if (shorterKeyKind === \"predecessor\" && longerKeyKind === \"exact\") {\n return -1;\n }\n if (shorterKeyKind === \"successor\" && longerKeyKind === \"exact\") {\n return 1;\n }\n throw new Error(`Unexpected key kinds: ${shorterKeyKind}, ${longerKeyKind}`);\n}\nfunction compareKeys(key1, key2) {\n let i = 0;\n while (i < Math.max(key1.value.length, key2.value.length)) {\n const v1 = getValueAtIndex(key1.value, i);\n const v2 = getValueAtIndex(key2.value, i);\n if (v1 === undefined) {\n return compareDanglingSuffix(key1.kind, key2.kind, key1, key2);\n }\n if (v2 === undefined) {\n return -1 * compareDanglingSuffix(key2.kind, key1.kind, key2, key1);\n }\n const result = compareValues(v1.value, v2.value);\n if (result !== 0) {\n return result;\n }\n // if the prefixes are the same so far, keep going with the comparison\n i++;\n }\n if (key1.kind === key2.kind) {\n return 0;\n }\n // keys are the same length and values\n if (key1.kind === \"exact\") {\n if (key2.kind === \"successor\") {\n return -1;\n }\n else {\n return 1;\n }\n }\n if (key1.kind === \"predecessor\") {\n return -1;\n }\n if (key1.kind === \"successor\") {\n return 1;\n }\n // Note: we're being cautious here, but we aren't checking above that the type\n // of key2.kind is valid...\n throw new Error(`Unexpected key kind: ${key1.kind}`);\n}\nfunction serializeCursor(key) {\n return JSON.stringify(convexToJson(key.map((v) => v === undefined\n ? \"undefined\"\n : typeof v === \"string\" && v.endsWith(\"undefined\")\n ? // in the unlikely case their string was \"undefined\"\n // or \"_undefined\" etc, we escape it.\n \"_\" + v\n : v)));\n}\nfunction deserializeCursor(cursor) {\n return jsonToConvex(JSON.parse(cursor)).map((v) => {\n if (typeof v === \"string\") {\n if (v === \"undefined\") {\n // This is a special case for the undefined value.\n // It's not a valid value in the index, but it's a valid value in the\n // cursor.\n return undefined;\n }\n if (v.endsWith(\"undefined\")) {\n // in the unlikely case their string was \"undefined\" it was changed to\n // \"_undefined\" in the serialization process.\n // NB: if their string was \"_undefined\" it was changed to\n // \"__undefined\" in the serialization process, and so on.\n return v.slice(1);\n }\n }\n return v;\n });\n}\n","/* eslint-disable jsdoc/require-jsdoc */\nimport type { BetterAuthDBSchema } from \"better-auth/db\";\nimport type {\n DocumentByName,\n GenericDataModel,\n GenericQueryCtx,\n PaginationOptions,\n PaginationResult,\n SchemaDefinition,\n TableNamesInDataModel,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\n\nimport { asyncMap } from \"convex-helpers\";\nimport { mergedStream, stream } from \"convex-helpers/server/stream\";\n\nexport type QueryArgs = {\n limit?: number;\n model: string;\n offset?: number;\n select?: string[];\n sortBy?: {\n direction: \"asc\" | \"desc\";\n field: string;\n };\n where?: WhereClause[];\n};\n\nexport type WhereClause = {\n connector?: \"AND\" | \"OR\";\n field: string;\n operator?:\n | \"contains\"\n | \"ends_with\"\n | \"eq\"\n | \"gt\"\n | \"gte\"\n | \"in\"\n | \"lt\"\n | \"lte\"\n | \"ne\"\n | \"not_in\"\n | \"starts_with\";\n value: boolean | null | number | number[] | string | string[];\n};\n\nexport const isUniqueField = (\n betterAuthSchema: BetterAuthDBSchema,\n model: string,\n field: string,\n): boolean => {\n const fields = betterAuthSchema[model]?.fields;\n if (!fields) {\n return false;\n }\n return Object.entries(fields)\n .filter(([, value]) => value.unique)\n .map(([key]) => key)\n .includes(field);\n};\n\nexport const hasUniqueFields = (\n betterAuthSchema: BetterAuthDBSchema,\n model: string,\n input: Record<string, any>,\n): boolean => {\n for (const field of Object.keys(input)) {\n if (isUniqueField(betterAuthSchema, model, field)) {\n return true;\n }\n }\n return false;\n};\n\nexport const findIndex = (\n schema: SchemaDefinition<any, any>,\n args: QueryArgs,\n) => {\n if (\n (args.where?.length ?? 0) > 1 &&\n args.where?.some((w) => w.connector === \"OR\")\n ) {\n throw new Error(\n `OR connector not supported with multiple where statements in findIndex, split up the where statements before calling findIndex: ${JSON.stringify(args.where)}`,\n );\n }\n const where = args.where?.filter((w) => {\n return (\n (!w.operator ||\n [\"eq\", \"gt\", \"gte\", \"in\", \"lt\", \"lte\", \"not_in\"].includes(\n w.operator,\n )) &&\n w.field !== \"_id\"\n );\n });\n if (!where?.length && !args.sortBy) {\n return;\n }\n const lowerBounds =\n where?.filter((w) => w.operator === \"lt\" || w.operator === \"lte\") ?? [];\n if (lowerBounds.length > 1) {\n throw new Error(\n `cannot have more than one lower bound where clause: ${JSON.stringify(where)}`,\n );\n }\n const upperBounds =\n where?.filter((w) => w.operator === \"gt\" || w.operator === \"gte\") ?? [];\n if (upperBounds.length > 1) {\n throw new Error(\n `cannot have more than one upper bound where clause: ${JSON.stringify(where)}`,\n );\n }\n const lowerBound = lowerBounds[0];\n const upperBound = upperBounds[0];\n if (lowerBound && upperBound && lowerBound.field !== upperBound.field) {\n throw new Error(\n `lower bound and upper bound must have the same field: ${JSON.stringify(where)}`,\n );\n }\n const boundField = lowerBound?.field ?? upperBound?.field;\n if (\n boundField &&\n where?.some(\n (w) => w.field === boundField && w !== lowerBound && w !== upperBound,\n )\n ) {\n throw new Error(\n `too many where clauses on the bound field: ${JSON.stringify(where)}`,\n );\n }\n const indexEqFields =\n where\n ?.filter((w) => !w.operator || w.operator === \"eq\")\n .sort((a, b) => {\n return a.field.localeCompare(b.field);\n })\n .map((w) => [w.field, w.value]) ?? [];\n if (!indexEqFields?.length && !boundField && !args.sortBy) {\n return;\n }\n const table = schema.tables[args.model as keyof typeof schema.tables];\n if (!table) {\n throw new Error(`Table ${args.model} not found`);\n }\n const indexes = table[\" indexes\"]();\n const sortField = args.sortBy?.field;\n\n // We internally use _creationTime in place of Better Auth's createdAt\n const indexFields = indexEqFields\n .map(([field]) => field)\n .concat(\n boundField && boundField !== \"createdAt\"\n ? `${indexEqFields.length ? \"_\" : \"\"}${boundField}`\n : \"\",\n )\n .concat(\n sortField && sortField !== \"createdAt\" && boundField !== sortField\n ? `${indexEqFields.length || boundField ? \"_\" : \"\"}${sortField}`\n : \"\",\n )\n .filter(Boolean);\n if (!indexFields.length && !boundField && !sortField) {\n return;\n }\n // Use the built in _creationTime index if bounding or sorting by createdAt\n // with no other fields\n const index = !indexFields.length\n ? {\n fields: [],\n indexDescriptor: \"by_creation_time\",\n }\n : indexes.find(({ fields }: { fields: string[] }) => {\n const fieldsMatch = indexFields.every(\n (field, idx) => field === fields[idx],\n );\n // If sorting by createdAt, no intermediate fields can be on the index\n // as they may override the createdAt sort order.\n const boundFieldMatch =\n boundField === \"createdAt\" || sortField === \"createdAt\"\n ? indexFields.length === fields.length\n : true;\n return fieldsMatch && boundFieldMatch;\n });\n if (!index) {\n return { indexFields };\n }\n return {\n boundField,\n index: {\n fields: [...index.fields, \"_creationTime\"],\n indexDescriptor: index.indexDescriptor,\n },\n sortField,\n values: {\n eq: indexEqFields.map(([, value]) => value),\n gt: upperBound?.operator === \"gt\" ? upperBound.value : undefined,\n gte: upperBound?.operator === \"gte\" ? upperBound.value : undefined,\n lt: lowerBound?.operator === \"lt\" ? lowerBound.value : undefined,\n lte: lowerBound?.operator === \"lte\" ? lowerBound.value : undefined,\n },\n };\n};\n\nexport const checkUniqueFields = async <\n Schema extends SchemaDefinition<any, any>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: Schema,\n betterAuthSchema: BetterAuthDBSchema,\n table: string,\n input: Record<string, any>,\n doc?: Record<string, any>,\n) => {\n if (!hasUniqueFields(betterAuthSchema, table, input)) {\n return;\n }\n for (const field of Object.keys(input)) {\n if (!isUniqueField(betterAuthSchema, table, field)) {\n continue;\n }\n const { index } =\n findIndex(schema, {\n model: table,\n where: [{ field, operator: \"eq\", value: input[field] }],\n }) ?? {};\n if (!index) {\n throw new Error(`No index found for ${table}.${field}`);\n }\n const existingDoc = await ctx.db\n .query(table as any)\n .withIndex(index.indexDescriptor, (q) => q.eq(field, input[field]))\n .unique();\n if (existingDoc && existingDoc._id !== doc?._id) {\n throw new Error(`${table} ${field} already exists`);\n }\n }\n};\n\nexport const selectFields = <\n T extends TableNamesInDataModel<GenericDataModel>,\n D extends DocumentByName<GenericDataModel, T>,\n>(\n doc: D | null,\n select?: string[],\n): D | null => {\n if (!doc) {\n return null;\n }\n if (!select?.length) {\n return doc;\n }\n return select.reduce((acc, field) => {\n (acc as any)[field] = doc[field];\n return acc;\n }, {} as D);\n};\n\nexport const filterByWhere = <\n T extends TableNamesInDataModel<GenericDataModel>,\n D extends DocumentByName<GenericDataModel, T>,\n>(\n doc: D | null,\n where?: WhereClause[],\n // Optionally filter which where clauses to apply.\n filterWhere?: (w: WhereClause) => any,\n): boolean => {\n if (!doc) {\n return false;\n }\n for (const w of where ?? []) {\n if (filterWhere && !filterWhere(w)) {\n continue;\n }\n const value = doc[w.field as keyof typeof doc] as WhereClause[\"value\"];\n const isLessThan = (val: typeof value, wVal: typeof w.value) => {\n if (!wVal) {\n return false;\n }\n if (!val) {\n return true;\n }\n return val < wVal;\n };\n const isGreaterThan = (val: typeof value, wVal: typeof w.value) => {\n if (!val) {\n return false;\n }\n if (!wVal) {\n return true;\n }\n return val > wVal;\n };\n const filter = (w: WhereClause) => {\n switch (w.operator) {\n case \"contains\": {\n return typeof value === \"string\" && value.includes(w.value as string);\n }\n case \"ends_with\": {\n return typeof value === \"string\" && value.endsWith(w.value as string);\n }\n case \"eq\":\n case undefined: {\n return value === w.value;\n }\n case \"gt\": {\n return isGreaterThan(value, w.value);\n }\n case \"gte\": {\n return value === w.value || isGreaterThan(value, w.value);\n }\n case \"in\": {\n return Array.isArray(w.value) && (w.value as any[]).includes(value);\n }\n case \"lt\": {\n return isLessThan(value, w.value);\n }\n case \"lte\": {\n return value === w.value || isLessThan(value, w.value);\n }\n case \"ne\": {\n return value !== w.value;\n }\n case \"not_in\": {\n return Array.isArray(w.value) && !(w.value as any[]).includes(value);\n }\n case \"starts_with\": {\n return (\n typeof value === \"string\" && value.startsWith(w.value as string)\n );\n }\n }\n };\n if (!filter(w)) {\n return false;\n }\n }\n return true;\n};\n\nconst generateQuery = (\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n args: QueryArgs,\n) => {\n const { boundField, index, indexFields, values } =\n findIndex(schema, args) ?? {};\n const query = stream(ctx.db as any, schema).query(args.model as any);\n const hasValues =\n values?.eq?.length ??\n values?.lt ??\n values?.lte ??\n values?.gt ??\n values?.gte;\n const indexedQuery =\n index && index.indexDescriptor !== \"by_creation_time\"\n ? query.withIndex(\n index.indexDescriptor,\n hasValues\n ? (q: any) => {\n for (const [idx, value] of (values?.eq ?? []).entries()) {\n q = q.eq(index.fields[idx], value);\n }\n if (values?.lt) {\n q = q.lt(boundField, values.lt);\n }\n if (values?.lte) {\n q = q.lte(boundField, values.lte);\n }\n if (values?.gt) {\n q = q.gt(boundField, values.gt);\n }\n if (values?.gte) {\n q = q.gte(boundField, values.gte);\n }\n return q;\n }\n : undefined,\n )\n : query;\n const orderedQuery = args.sortBy\n ? indexedQuery.order(args.sortBy.direction === \"desc\" ? \"desc\" : \"asc\")\n : indexedQuery;\n const filteredQuery = orderedQuery.filterWith(async (doc) => {\n if (!index && indexFields?.length) {\n console.warn(\n `Querying without an index on table \"${args.model}\".\\n` +\n `This can cause performance issues, and may hit the document read limit.\\n` +\n `To fix, add an index that begins with the following fields in order:\\n` +\n `[${indexFields.join(\", \")}]`,\n );\n // No index, handle all where clauses statically.\n return filterByWhere(doc, args.where);\n }\n return filterByWhere(\n doc,\n args.where,\n // Index used for all eq and range clauses, apply remaining clauses\n // incompatible with Convex statically.\n (w) =>\n w.operator &&\n [\"contains\", \"ends_with\", \"ne\", \"not_in\", \"starts_with\"].includes(\n w.operator,\n ),\n );\n });\n return filteredQuery;\n};\n\nexport const paginate = async <\n Doc extends DocumentByName<GenericDataModel, T>,\n T extends TableNamesInDataModel<GenericDataModel>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n betterAuthSchema: BetterAuthDBSchema,\n args: QueryArgs & {\n paginationOpts: PaginationOptions;\n },\n): Promise<PaginationResult<Doc>> => {\n if (args.offset) {\n throw new Error(`offset not supported: ${JSON.stringify(args.offset)}`);\n }\n if (args.where?.some((w) => w.connector === \"OR\") && args.where?.length > 1) {\n throw new Error(\n `OR connector not supported with multiple where statements in paginate, split up the where statements before calling paginate: ${JSON.stringify(args.where)}`,\n );\n }\n if (\n args.where?.some(\n (w) =>\n w.field === \"_id\" &&\n w.operator &&\n ![\"eq\", \"in\", \"not_in\"].includes(w.operator),\n )\n ) {\n throw new Error(\n `_id can only be used with eq, in, or not_in operator: ${JSON.stringify(args.where)}`,\n );\n }\n // If any where clause is \"eq\" (or missing operator) on a unique field,\n // we can only return a single document, so we get it and use any other\n // where clauses as static filters.\n const uniqueWhere = args.where?.find(\n (w) =>\n (!w.operator || w.operator === \"eq\") &&\n (isUniqueField(betterAuthSchema, args.model, w.field) ||\n w.field === \"_id\"),\n );\n if (uniqueWhere) {\n const { index } =\n findIndex(schema, {\n model: args.model,\n where: [uniqueWhere],\n }) ?? {};\n\n let doc;\n if (uniqueWhere.field === \"_id\") {\n doc = await ctx.db.get(uniqueWhere.value as GenericId<T>);\n } else if (index?.indexDescriptor) {\n doc = await ctx.db\n .query(args.model as any)\n .withIndex(index.indexDescriptor, (q) =>\n q.eq(index.fields[0], uniqueWhere.value),\n )\n .unique();\n } else {\n // No index found - fall back to collect() for unique field lookup\n const results = await ctx.db.query(args.model as any).collect();\n doc =\n results.find((d: any) => d[uniqueWhere.field] === uniqueWhere.value) ??\n null;\n }\n\n // Apply all other clauses as static filters to our 0 or 1 result.\n if (filterByWhere(doc, args.where, (w) => w !== uniqueWhere)) {\n return {\n continueCursor: \"\",\n isDone: true,\n page: [selectFields(doc, args.select)].filter(Boolean) as Doc[],\n };\n }\n return {\n continueCursor: \"\",\n isDone: true,\n page: [],\n };\n }\n\n const paginationOpts = {\n ...args.paginationOpts,\n // If maximumRowsRead is not at least 1 higher than numItems, bad cursors\n // and incorrect paging will result (at least with convex-test).\n maximumRowsRead: Math.max((args.paginationOpts.numItems ?? 0) + 1, 200),\n };\n\n // Large queries using \"in\" clause will crash, but these are only currently\n // possible with the organization plugin listing all members with a high\n // limit. For cases like this we need to create proper convex queries in\n // the component as an alternative to using Better Auth api's.\n const inWhere = args.where?.find((w) => w.operator === \"in\");\n if (inWhere) {\n if (!Array.isArray(inWhere.value)) {\n throw new Error(\"in clause value must be an array\");\n }\n // For ids, just use asyncMap + .get()\n if (inWhere.field === \"_id\") {\n const docs = await asyncMap(inWhere.value as any[], async (value) => {\n return ctx.db.get(value as GenericId<T>);\n });\n const filteredDocs = docs\n .flatMap((doc) => (doc ? [doc] : []))\n .filter((doc) => filterByWhere(doc, args.where, (w) => w !== inWhere));\n\n return {\n continueCursor: \"\",\n isDone: true,\n page: filteredDocs.sort((a, b) => {\n if (args.sortBy?.field === \"createdAt\") {\n return args.sortBy.direction === \"asc\"\n ? (a._creationTime as number) - (b._creationTime as number)\n : (b._creationTime as number) - (a._creationTime as number);\n }\n if (args.sortBy) {\n const aValue = a[args.sortBy.field];\n const bValue = b[args.sortBy.field];\n if (aValue === bValue) {\n return 0;\n }\n return args.sortBy.direction === \"asc\"\n ? aValue! > bValue!\n ? 1\n : -1\n : aValue! > bValue!\n ? -1\n : 1;\n }\n return 0;\n }) as Doc[],\n };\n }\n const streams = inWhere.value.map((value) => {\n return generateQuery(ctx, schema, {\n ...args,\n where: args.where?.map((w) => {\n if (w === inWhere) {\n return { ...w, operator: \"eq\" as const, value };\n }\n return w;\n }),\n });\n });\n const result = await mergedStream(\n streams,\n [\n args.sortBy?.field !== \"createdAt\" && args.sortBy?.field,\n \"_creationTime\",\n ].flatMap((f) => (f ? [f] : [])),\n ).paginate(paginationOpts);\n return {\n ...result,\n page: await asyncMap(result.page, (doc) =>\n selectFields(doc, args.select),\n ),\n };\n }\n\n const query = generateQuery(ctx, schema, args);\n const result = await query.paginate(paginationOpts);\n return {\n ...result,\n page: await asyncMap(result.page, (doc) => selectFields(doc, args.select)),\n };\n};\n\nexport const listOne = async <\n Doc extends DocumentByName<GenericDataModel, T>,\n T extends TableNamesInDataModel<GenericDataModel>,\n>(\n ctx: GenericQueryCtx<GenericDataModel>,\n schema: SchemaDefinition<any, any>,\n betterAuthSchema: BetterAuthDBSchema,\n args: QueryArgs,\n): Promise<Doc | null> => {\n return (\n await paginate(ctx, schema, betterAuthSchema, {\n ...args,\n paginationOpts: {\n cursor: null,\n numItems: 1,\n },\n })\n ).page[0] as Doc | null;\n};\n","import type { GenericDataModel, GenericMutationCtx, GenericQueryCtx } from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\nimport type { CollectionSlug, VexApiAuth } from \"@vexcms/core\";\n\n/**\n * Builds the `getAuth` resolver for `collectionsApi` from better-auth's\n * conventions — no per-app auth plumbing.\n *\n * Resolution chain, all from the validated JWT the `convex()` better-auth\n * plugin mints: `identity.subject` (user doc id) → user document;\n * `identity.sessionId` (appended to every token by the plugin) → session\n * document → `session.activeOrganizationId` → organization document.\n * Documents are read fresh on every request, so role changes and\n * org switches apply immediately — claims are only used as ids, never\n * as authorization data.\n *\n * `orgCollectionSlug` is only required when `resolveOrgs` is true — a\n * project with organizations disabled can omit it entirely. Passing\n * `resolveOrgs: true` without an `orgCollectionSlug` skips org resolution\n * (same as `resolveOrgs: false`) rather than throwing, since the omission\n * is a config mistake, not a request-time error worth failing loudly for.\n *\n * @returns { user, organization }, @see {@link VexApiAuth}\n *\n */\nexport function createGetAuth<TCollectionSlug extends CollectionSlug = CollectionSlug>(props: {\n userCollectionSlug: TCollectionSlug;\n orgCollectionSlug?: TCollectionSlug;\n sessionCollectionSlug: TCollectionSlug;\n resolveOrgs?: boolean;\n}) {\n return async <DataModel extends GenericDataModel>(\n ctx: GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n ): Promise<VexApiAuth> => {\n const identity = await ctx.auth.getUserIdentity();\n if (identity === null) {\n return { user: null }; // unauthenticated → downstream deny (no roles)\n }\n\n const user = await ctx.db.get(\n props.userCollectionSlug,\n identity.subject as GenericId<TCollectionSlug>,\n );\n if (user === null) {\n return { user }; // token for a deleted user → deny\n }\n\n if (!props.resolveOrgs || !props.orgCollectionSlug) {\n return { user };\n }\n const orgCollectionSlug = props.orgCollectionSlug;\n const sessionId = identity.sessionId as GenericId<TCollectionSlug> | undefined;\n const session = sessionId ? await ctx.db.get(props.sessionCollectionSlug, sessionId) : null;\n const orgId = session?.activeOrganizationId as GenericId<TCollectionSlug> | undefined;\n const organization = orgId\n ? ((await ctx.db.get(orgCollectionSlug, orgId)) ?? undefined)\n : undefined;\n\n return { user, organization };\n };\n}\n","import type {\n GenericActionCtx,\n GenericDataModel,\n GenericMutationCtx,\n GenericQueryCtx,\n MutationBuilder,\n QueryBuilder,\n SchemaDefinition,\n} from \"convex/server\";\nimport { convexAdapter } from \"./adapter\";\nimport * as DB from \"./db\";\n\n/**\n * Arguments for authDbApi — same pattern as queryApi/mutationApi in @vexcms/core.\n *\n * The user imports their Convex schema from `convex/schema.ts` and passes it here.\n */\nexport type AuthDbApiOptions<DataModel extends GenericDataModel> = {\n /** The user's Convex schema (from `convex/schema.ts`). */\n schema: SchemaDefinition<any, any>;\n /** The user's `internalMutation` from `convex/_generated/server`. */\n internalMutation: MutationBuilder<DataModel, \"internal\">;\n /** The user's `internalQuery` from `convex/_generated/server`. */\n internalQuery: QueryBuilder<DataModel, \"internal\">;\n};\n\n/**\n * Creates the auth DB operations as proper Convex functions.\n *\n * Use this in www/convex/auth/db.ts to export the db operations:\n * ```ts\n * import { authDbApi } from \"@vexcms/better-auth/convex\"\n * import { internalMutation, internalQuery } from \"../../_generated/server\"\n * import schema from \"../schema\"\n *\n * export const { dbCreate, dbFindOne, dbFindMany, dbCount, dbUpdate, dbUpdateMany, dbDelete, dbDeleteMany } = authDbApi({\n * schema,\n * internalMutation,\n * internalQuery,\n * })\n * ```\n *\n * This follows the exact same pattern as queryApi/mutationApi in @vexcms/core.\n * The returned functions are proper Convex FunctionReferences available as\n * internal.auth.db.dbCreate, etc. in the user's Convex API.\n * @param options - The user's Convex schema plus their `internalMutation`\n * and `internalQuery` builders, used to construct the auth DB functions.\n * @returns An object exposing `dbCreate`, `dbFindOne`, `dbFindMany`,\n * `dbCount`, `dbUpdate`, `dbUpdateMany`, `dbDelete`, and `dbDeleteMany` as\n * internal Convex function references, ready to re-export from the\n * user's Convex API.\n */\nexport function authDbApi<DataModel extends GenericDataModel>(\n options: AuthDbApiOptions<DataModel>,\n) {\n return {\n dbCreate: options.internalMutation({\n ...DB.create,\n handler: async (ctx, args) =>\n await DB.create.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbFindOne: options.internalQuery({\n ...DB.findOne,\n handler: async (ctx, args) =>\n await DB.findOne.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbFindMany: options.internalQuery({\n ...DB.findMany,\n handler: async (ctx, args) =>\n await DB.findMany.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbCount: options.internalQuery({\n ...DB.count,\n handler: async (ctx, args) =>\n await DB.count.handler(\n ctx as unknown as GenericQueryCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbUpdate: options.internalMutation({\n ...DB.update,\n handler: async (ctx, args) =>\n await DB.update.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbUpdateMany: options.internalMutation({\n ...DB.updateMany,\n handler: async (ctx, args) =>\n await DB.updateMany.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbDelete: options.internalMutation({\n ...DB.deleteOne,\n handler: async (ctx, args) =>\n await DB.deleteOne.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n\n dbDeleteMany: options.internalMutation({\n ...DB.deleteMany,\n handler: async (ctx, args) =>\n await DB.deleteMany.handler(\n ctx as unknown as GenericMutationCtx<GenericDataModel>,\n args,\n options.schema,\n ),\n }),\n };\n}\n\n/**\n * Creates the Better Auth Convex adapter.\n *\n * Use this in www/convex/auth/index.ts inside createAuth:\n * ```ts\n * import { createBetterAuthAdapter } from \"@vexcms/better-auth/convex\"\n * import { dbCreate, dbFindOne, ... } from \"./db\"\n *\n * export const createAuth = (ctx) => {\n * return betterAuth({\n * database: createBetterAuthAdapter(ctx, { dbCreate, dbFindOne, ... }),\n * ...authOptions,\n * })\n * }\n * ```\n *\n * The adapter uses anyApi to reference the db operations (anyApi.auth.db.dbCreate etc.)\n * and calls them via ctx.runMutation/ctx.runQuery.\n * @param ctx ActionCtx from better-auth convex library\n * @returns AdapterFactory\n */\nexport function createBetterAuthAdapter<DataModel extends GenericDataModel>(\n ctx: GenericActionCtx<DataModel>,\n) {\n return convexAdapter(ctx);\n}\n\nexport { convexAdapter } from \"./adapter\";\nexport * from \"./types\";\nexport * from \"./getAuth\";\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,qBAAqB;AAc9B,IAAM,wBAAwB;AAAA,EAC5B,MAAM;AAAA,EACN,SAAS;AAAA,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ACJ,CAAC;AAAA,IAED,UAAU,QAAQ,iBAAiB;AAAA,MACjC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,OAAO;AAAA,QACd;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,IAED,cAAc,QAAQ,iBAAiB;AAAA,MACrC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,WAAW;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,IAED,UAAU,QAAQ,iBAAiB;AAAA,MACjC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,UAAU;AAAA,QACjB;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,IAED,cAAc,QAAQ,iBAAiB;AAAA,MACrC,GAAM;AAAA,MACN,SAAS,OAAO,KAAK,SACnB,MAAS,WAAW;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,EACH;AACF;AAuBO,SAAS,wBACd,KACA;AACA,SAAO,cAAc,GAAG;AAC1B;","names":["v","getAuthTables","where","select","update","commonPrefix","index","stream","_","result","orderingIndexFields","v","select","w","result","select","result","update"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vexcms/better-auth",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
4
|
"description": "better-auth adapter for VexCMS on Convex",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cms",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"better-auth": ">=1.6.23 <1.7.0",
|
|
37
37
|
"convex": ">=1.44.0 <2",
|
|
38
|
-
"@vexcms/core": "^0.1.0-alpha.
|
|
38
|
+
"@vexcms/core": "^0.1.0-alpha.3"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/node": "20.19.43",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"tsup": "8.5.1",
|
|
48
48
|
"typescript": "6.0.3",
|
|
49
49
|
"vitest": "4.1.10",
|
|
50
|
-
"@vexcms/core": "0.1.0-alpha.
|
|
50
|
+
"@vexcms/core": "0.1.0-alpha.3",
|
|
51
51
|
"@vexcms/tsconfig": "0.0.0"
|
|
52
52
|
},
|
|
53
53
|
"publishConfig": {
|