LLM Reference

LLM Reference: Admin Module

This is a dense reference for LLMs working with Vextro’s admin module. It documents every argument to createVextroAdminModule, default behaviors, and the complete list of exported query and mutation functions.

createVextroAdminModule(args)

Factory function that creates the complete Vextro admin API for a Convex backend. Returns all queries and mutations needed to power the admin UI. The return value is a flat object of named Convex functions that you destructure and re-export from your convex/admin.ts file.

import { query, mutation } from "./_generated/server";
import { components } from "./_generated/api";
import { createVextroAdminModule } from "vextro/convex/admin";

const admin = createVextroAdminModule({
  query,
  mutation,
  components,
  geospatialComponent: components.geospatial, // Required if using f.point() with spatial indexing
  collectionDefinitions,
});

export const { listCollections, getShellData, seedAdminMetadata, /* ... */ } = admin;

Arguments

Core (required)

PropertyTypeRequiredDescription
queryQueryBuilder<DataModel, "public">YesConvex query builder from _generated/server. Used to create all read functions.
mutationMutationBuilder<DataModel, "public">YesConvex mutation builder from _generated/server. Used to create all write functions.
componentsVextroAdminComponentRefs<TableName>YesComponent references from _generated/api. Provides access to Vextro’s internal component functions.

Definitions

PropertyTypeRequiredDescription
collectionDefinitionsArray<CollectionDefinition<TableName>>NoCollection definitions produced by buildAdminDefinitions(). When provided, Vextro computes a fingerprint for automatic metadata seeding.
globalDefinitionsArray<GlobalDefinition>NoGlobal definitions for singleton documents (e.g., site settings).
isTableName(name: string) => name is TableNameNoType guard for runtime table name validation. Default: treats all strings as valid table names.

Auth / Access

PropertyTypeRequiredDescription
getCurrentUser(ctx) => Promise<User | null>NoResolves the current authenticated user. Used for audit logging, presence, and user context. Default: looks up the users table via a by_tokenIdentifier index. Override if your user table or index differs.
requireAdminRead(ctx) => Promise<void>NoAuth guard for all admin read operations (queries). Throw to deny access. Default: requires ctx.auth.getUserIdentity() to be non-null.
requireAdminWrite(ctx) => Promise<void>NoAuth guard for all admin write operations (mutations). Throw to deny access. Default: same as requireAdminRead (checks for authenticated identity).
getUserRoles(ctx) => Promise<string[]>NoReturns role slugs for the current user. Used for collection-level and field-level permission checks. When not provided, a default implementation queries the RBAC tables (userRoles join to roles).
rbacFailOpenbooleanNoControls behavior when getUserRoles throws. false (default): re-throws the error, denying access (fail-closed). true: returns null, allowing access as if RBAC is not configured. Security warning: setting to true means role resolution errors silently bypass all collection-level RBAC.
accessControlAccessControlDefinitionsNoCode-defined roles, permissions, and default role-to-permission assignments. Automatically synced to the database when access control pages load. Definitions are additive — manual assignments in the admin UI are preserved. See the AccessControlDefinitions type below.
requireAccessControlRead(ctx) => Promise<void>NoSeparate auth guard for access control read operations (roles/permissions/users list pages). Falls back to requireAdminRead when not provided.
requireAccessControlWrite(ctx) => Promise<void>NoSeparate auth guard for access control write operations (role/user mutations). Falls back to requireAdminWrite when not provided.

Scopes

PropertyTypeRequiredDescription
getUserScopes(ctx, scopeType: string) => Promise<string[] | null>NoReturns scope IDs the current user can access for a given scope type. Return null to indicate unrestricted (admin-level) access.
canAccessScope(ctx, scopeType: string, scopeValue: string) => Promise<boolean>NoValidates that a user can access a specific scope value. Used for write operations.
listScopeOptions(ctx, scopeType: string) => Promise<Array<{ id: string; label: string }>>NoReturns scope options for the scope selector UI dropdown.

Scheduling

PropertyTypeRequiredDescription
scheduleCacheInvalidation(ctx, args: CacheInvalidationArgs) => Promise<void>NoCallback invoked after document changes to trigger cache invalidation. Typically schedules a ctx.scheduler.runAfter(0, ...) call to a cache invalidation action.
scheduleWebhookDelivery(ctx, args: WebhookDeliveryArgs) => Promise<void>NoCallback to schedule webhook delivery as an action. The host app provides an action that performs the HTTP call.

User Management

PropertyTypeRequiredDescription
userProfileFieldsstring[]NoFields that users can update on their own profile via updateUserProfile. Default: ["displayName", "avatarUrl"].
onUserStatusChange(ctx, { userId, previousStatus, newStatus }) => Promise<void>NoCalled when a user’s status changes (e.g., via updateUserStatus). Use to invalidate sessions when a user is deactivated, send notifications, or trigger other side effects. Vextro does not invalidate sessions automatically since session storage varies by auth provider.

Other

PropertyTypeRequiredDescription
blockDeletionStrategy"preserve" | "delete-exclusive"NoStrategy for handling blocks when a parent document is deleted. "preserve" (default): blocks remain, only usedIn entries are cleaned up. "delete-exclusive": blocks used only by the deleted document are also deleted.
geospatialComponentanyNoComponent reference for @convex-dev/geospatial. Required when any collection has a point field with spatialIndex: true (default). Pass components.geospatial from _generated/api. See point field setup.
richText{ toolbar?: RichTextToolbar }NoProject-level rich text editor defaults. Merged with field-level config (field-level wins per key).
getSampleDoc(ctx, definition) => Promise<Record<string, Value> | undefined>NoReturns a sample document for a collection. Default: reads the first document from the collection’s table via ctx.db.query(tableName).take(1). Override if you maintain a static sample map or want to skip the DB query.
getCollectionDefinitions(ctx) => Promise<Array<CollectionDefinition<string>>>NoDynamic collection definitions loader. Called from mutations to get the current definitions at runtime.

AccessControlDefinitions

type AccessControlDefinitions = {
  permissions: Array<{ slug: string; description?: string }>;
  roles: Array<{
    slug: string;
    name: string;
    description?: string;
    permissions: string[];  // Permission slugs this role should have by default
  }>;
  tables?: {
    permissions?: string;      // Default: "permissions"
    roles?: string;            // Default: "roles"
    rolePermissions?: string;  // Default: "rolePermissions"
    userRoles?: string;        // Default: "userRoles"
    users?: string;            // Default: "users"
    userScopes?: string;       // Default: "userScopes"
  };
};

Complete Production Example

// convex/admin.ts
import { query, mutation } from "./_generated/server";
import { api, components } from "./_generated/api";
import {
  createVextroAdminModule,
  buildAdminDefinitions,
} from "vextro/convex/admin";
import { posts, pages, media, categories } from "./collections";
import { siteSettings } from "./globals";
import { hero, cta, testimonial } from "./blocks";

const collectionDefinitions = buildAdminDefinitions({
  collections: [posts, pages, media, categories],
  blocks: [hero, cta, testimonial],
});

const admin = createVextroAdminModule({
  // Core (required)
  query,
  mutation,
  components,

  // Definitions
  collectionDefinitions,
  globalDefinitions: [siteSettings],

  // Auth guards
  getCurrentUser: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) return null;
    return await ctx.db
      .query("users")
      .withIndex("by_clerkId", (q) => q.eq("clerkId", identity.subject))
      .unique();
  },
  requireAdminRead: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Not authenticated");
  },
  requireAdminWrite: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Not authenticated");
    // Additional role check for write operations
    const user = await ctx.db
      .query("users")
      .withIndex("by_clerkId", (q) => q.eq("clerkId", identity.subject))
      .unique();
    if (!user || user.status === "inactive") {
      throw new Error("Write access denied");
    }
  },

  // RBAC
  accessControl: {
    permissions: [
      { slug: "cms:read", description: "View CMS content" },
      { slug: "cms:write", description: "Create and edit content" },
      { slug: "cms:admin", description: "Full CMS admin access" },
    ],
    roles: [
      {
        slug: "admin",
        name: "Administrator",
        description: "Full system access",
        permissions: ["cms:read", "cms:write", "cms:admin"],
      },
      {
        slug: "editor",
        name: "Editor",
        description: "Content editing access",
        permissions: ["cms:read", "cms:write"],
      },
    ],
    tables: {
      roles: "roles",
      permissions: "permissions",
      userRoles: "userRoles",
      rolePermissions: "rolePermissions",
      users: "users",
      userScopes: "userScopes",
    },
  },

  // Scheduling
  scheduleCacheInvalidation: async (ctx, args) => {
    await ctx.scheduler.runAfter(0, api.admin.invalidateVextroCache, args);
  },

  // Block deletion
  blockDeletionStrategy: "delete-exclusive",

  // User management
  userProfileFields: ["displayName", "avatarUrl", "bio"],
  onUserStatusChange: async (ctx, { userId, previousStatus, newStatus }) => {
    if (newStatus === "inactive") {
      // App-specific session cleanup
    }
  },
});

export const {
  listCollections,
  getCollectionBySlug,
  listGlobals,
  getShellData,
  isDefinitionsStale,
  getGlobalBySlug,
  listFieldsForCollection,
  listFieldsForGlobal,
  listRelationshipsForCollection,
  listRelationshipOptions,
  paginateRelationshipOptions,
  getSchemaDiagnostics,
  getDashboardData,
  listDocumentsForCollection,
  getCollectionPageData,
  paginateDocuments,
  getCollectionPageDataPaginated,
  getDocumentEditPageData,
  getGlobalEditPageData,
  getUserListConfig,
  getDocumentForCollection,
  getGlobalDocument,
  listVersionsForDocument,
  getVersion,
  listSavedViews,
  getFileRecord,
  listOrphanedFiles,
  getBlockUsageDetails,
  getExclusiveBlocksForDocument,
  getOrphanBlockStats,
  listOrphanedBlocks,
  globalSearch,
  listAuditLog,
  getDocumentAuditLog,
  listWebhooks,
  getWebhook,
  listWebhookDeliveries,
  getDocumentPresence,
  getCollectionPresence,
  listNotifications,
  getUnreadNotificationCount,
  listTemplatesForCollection,
  getTemplate,
  listScopeOptions,
  getUserScopeAccess,
  getDocumentAncestors,
  getDocumentTree,
  listRoles,
  getRoleBySlug,
  getRoleById,
  getUsersForRole,
  listRolesWithCounts,
  listPermissions,
  getCollectionAccess,
  me,
  getUserById,
  listUsers,
  listUsersWithRoles,
  getUserRolesForUser,
  listUserScopes,
  createCollection,
  updateCollection,
  seedAdminMetadata,
  syncAccessControl,
  setUserListConfig,
  deleteUserListConfig,
  createDocumentForCollection,
  updateDocumentForCollection,
  deleteDocumentForCollection,
  duplicateDocumentForCollection,
  updateGlobalDocument,
  restoreFieldsFromVersion,
  bulkUpdateStatus,
  bulkDeleteDocuments,
  bulkUpdateTags,
  bulkCreateDocuments,
  createSavedView,
  updateSavedView,
  deleteSavedView,
  confirmFileUpload,
  deleteFileUpload,
  updateFileFocalAndCrop,
  updateFileProcessingStatus,
  deleteOrphanedFiles,
  deleteOrphanedBlocks,
  createWebhook,
  updateWebhook,
  deleteWebhook,
  testWebhook,
  replayWebhookDelivery,
  presenceHeartbeat,
  presenceFieldUpdate,
  presenceClear,
  presenceClearAll,
  markNotificationAsRead,
  markAllNotificationsAsRead,
  deleteNotification,
  createTemplate,
  updateTemplate,
  deleteTemplate,
  createRole,
  updateRole,
  deleteRole,
  addPermissionToRole,
  removePermissionFromRole,
  updateUserProfile,
  updateUserStatus,
  assignRoleToUser,
  removeRoleFromUser,
  assignUserScope,
  removeUserScope,
} = admin;

Admin API Function Reference

The admin module returns 114 named Convex functions (61 queries + 53 mutations). These are defined in the canonical VEXTRO_ADMIN_FUNCTION_NAMES list in exports.ts.

Queries — Shell & Navigation

FunctionDescription
listCollectionsList all collection definitions, optionally filtered by collectionType and archive status. Respects RBAC — only returns collections the current user can read.
getCollectionBySlugGet a single collection definition by its slug.
listGlobalsList all global definitions, optionally including archived globals.
getShellDataGet admin shell layout data from the active materialized metadata slot (adminMetadataCollectionView). Hot path uses slot routing only (no per-read fingerprint checks).
isDefinitionsStaleCheck if the stored metadata fingerprint matches the current definitions fingerprint.
getDashboardDataGet dashboard summary data including document counts and recent activity.
getSchemaDiagnosticsGet schema diagnostic data: field counts, archived fields, relationships, and fingerprint comparison.
getMetadataMigrationPreflightRun Phase 4 migration preflight checks (block graph cycle detection, depth threshold, canonical sharding byte guardrails, and block-count guardrails) before cutover.

Metadata migration preflight report

getMetadataMigrationPreflight returns a contract-shaped report that mirrors the sharding logic used during cutover:

FieldMeaning
estimatedEntityRowsEstimated count of canonical entity rows.
estimatedRelationshipRowsEstimated relationship-view rows.
estimatedBlockPickerRowsEstimated block-picker rows.
totalBlockTypesTotal discovered block types across collections.
maxObservedDepthDeepest authored metadata depth seen before encoding.
maxProjectedEditorRowDepthDeepest projected editor-row depth after encoding.
encodingAppliedCountNumber of deep metadata branches encoded into compact storage.
topDepthEntitiesUp to five collections or globals with the highest projected depth.
depthHeadroomRemaining margin against the MAX_EDITOR_FIELD_VIEW_DEPTH ceiling.
projectedCanonicalPartitionBytesMaxLargest projected canonical shard size in bytes.
projectedCanonicalTotalBytesCombined projected canonical payload size in bytes.
projectedCanonicalPartitionCountNumber of projected canonical shards.
cycleErrorsBlock graph cycle diagnostics collected during preflight.
hardErrorsBlocking guardrail failures that stop activation.

Current sharding thresholds:

  • EDITOR_FIELD_STORAGE_DEPTH_BUDGET = 10
  • EDITOR_FIELD_STORAGE_DEPTH_HARD_THRESHOLD = 14
  • EDITOR_FIELD_STORAGE_CERTIFIED_PERSISTED_DEPTH = 13
  • MAX_EDITOR_FIELD_VIEW_DEPTH = 16
  • PREVIEW_CANONICAL_PARTITION_HARD_THRESHOLD = 750_000
  • PREVIEW_CANONICAL_TOTAL_HARD_THRESHOLD = 2_500_000

Canonical block metadata is compacted to typeKeys references before it is measured, and expanded blocks.types definitions are only used to derive those keys.

Queries — Collections & Documents

FunctionDescription
listDocumentsForCollectionList all documents for a collection, optionally filtered by status and scope.
getCollectionPageDataGet collection list page data: documents, fields, relationships, and collection metadata in a single query.
paginateDocumentsPaginate documents for a collection with cursor-based pagination.
getCollectionPageDataPaginatedCombined paginated collection page data: paginated documents plus fields and collection metadata.
getDocumentEditPageDataGet all data needed for the document edit page: document, fields, relationships, versions, presence, and related documents.
getDocumentForCollectionGet a single document by collection slug and document ID. Applies field-level afterRead hooks.
getUserListConfigGet user-specific list view configuration (column order, sort, filters) for a collection.

Queries — Globals

FunctionDescription
getGlobalBySlugGet a single global definition by its slug.
getGlobalEditPageDataGet all data needed for the global edit page: document, fields, and global metadata.
getGlobalDocumentGet the current document for a global by its slug. Applies field-level afterRead hooks.

Queries — Fields & Relationships

FunctionDescription
listFieldsForCollectionList all fields for a collection by collection ID. Annotates fields with RBAC visibility for the current user.
listFieldsForGlobalList all fields for a global by global ID. Annotates fields with RBAC visibility for the current user.
listRelationshipsForCollectionList all relationship definitions for a collection.
listRelationshipOptionsLoad options for a relationship field by querying the relationship target table using precomputed relationship metadata (adminMetadataRelationshipView) on editor hot paths.
paginateRelationshipOptionsPaginate relationship options with cursor-based pagination. Uses relationship-view-driven targeting on hot paths and supports search/scope/sort.

Queries — Versions

FunctionDescription
listVersionsForDocumentList all version snapshots for a document, ordered by creation time.
getVersionGet a single version snapshot by ID.

Queries — Files & Uploads

FunctionDescription
getFileRecordGet a file record by ID from the Vextro file registry.
listOrphanedFilesList file records that are no longer referenced by any document.

Queries — Blocks

FunctionDescription
getBlockUsageDetailsGet detailed usage information for blocks: which documents reference each block and whether blocks are shared or exclusive.
getExclusiveBlocksForDocumentGet blocks that are exclusively owned by a specific document (not shared with other documents).
getOrphanBlockStatsGet statistics on orphaned blocks: counts by block type and total orphan count.
listOrphanedBlocksList block records that are no longer referenced by any document.
FunctionDescription
globalSearchSearch across all collections for documents matching a query string. Returns results grouped by collection.

Queries — Audit Log

FunctionDescription
listAuditLogList audit log entries with optional filtering by collection, action, or user.
getDocumentAuditLogGet audit log entries for a specific document.

Queries — Webhooks

FunctionDescription
listWebhooksList all configured webhook endpoints.
getWebhookGet a single webhook configuration by ID.
listWebhookDeliveriesList delivery attempts for a webhook, including status codes, response bodies, and retry information.

Queries — Presence

FunctionDescription
getDocumentPresenceGet real-time presence data for a document: which users are viewing or editing it, including field-level focus and dirty state.
getCollectionPresenceGet presence data for all documents in a collection: which documents have active editors.

Queries — Notifications

FunctionDescription
listNotificationsList notifications for the current user.
getUnreadNotificationCountGet the count of unread notifications for the current user.

Queries — Templates

FunctionDescription
listTemplatesForCollectionList saved templates for a collection.
getTemplateGet a single template by ID.

Queries — Scopes

FunctionDescription
listScopeOptionsList available scope options for the scope selector UI. Delegates to the listScopeOptions callback.
getUserScopeAccessGet the current user’s scope access for a scope type: which scope values they can access.
listUserScopesList all scope assignments for a specific user.

Queries — Hierarchy

FunctionDescription
getDocumentAncestorsGet the ancestor chain for a document in a hierarchical collection (parent, grandparent, etc.).
getDocumentTreeGet the full document tree for a hierarchical collection, structured as nested nodes.

Queries — Access Control (Roles & Permissions)

FunctionDescription
listRolesList all roles with their permission assignments.
getRoleBySlugGet a role by its slug, including assigned permissions.
getRoleByIdGet a role by its ID, including assigned permissions.
getUsersForRoleList all users assigned to a specific role.
listRolesWithCountsList all roles with user count and permission count.
listPermissionsList all permission definitions.
getCollectionAccessReturns RBAC access flags (canRead, canCreate, canUpdate, canDelete) for a specific collection and the current user’s roles.

Queries — Saved Views

FunctionDescription
listSavedViewsList all saved views (filter + sort + column configs) for a collection.

Queries — Users

FunctionDescription
meGet the current authenticated user’s profile.
getUserByIdGet a user by their ID.
listUsersList all users with optional filtering and pagination.
listUsersWithRolesList all users with their assigned roles.
getUserRolesForUserGet all role assignments for a specific user.

Mutations — Collections & Metadata

FunctionDescription
createCollectionCreate a new collection metadata record in the admin tables.
updateCollectionUpdate a collection metadata record.
seedAdminMetadataRun the staged metadata seed pipeline (lock -> materialize -> verify -> activate -> audit). Writes active/inactive slot materialized views and flips activeSlot only after verification passes.
runMetadataMigrationCutoverExecute one-way migration cutover flow: preflight -> lock/canonical -> legacy summary snapshot -> materialize -> verify -> activate -> audit. Snapshot is observability-focused (counts + sync metadata), not a full row-level backup artifact. Returns the activated slot and snapshot summary.
rollbackMetadataSlotRoll back metadata atomically by flipping activeSlot back to the previous (or specified) slot when that slot has materialized view rows.
syncAccessControlSync code-defined roles and permissions to the database. Additive: preserves manual assignments made in the admin UI.

Mutations — Documents

FunctionDescription
createDocumentForCollectionCreate a new document in a collection. Runs beforeValidate, beforeChange, field-level hooks, creates a version snapshot, logs audit entry, triggers webhooks, and syncs block usage.
updateDocumentForCollectionUpdate an existing document. Runs full hook pipeline, creates version snapshot, handles status transitions, and triggers webhooks.
deleteDocumentForCollectionDelete a document. Runs beforeDelete/afterDelete hooks, cleans up block references (per blockDeletionStrategy), logs audit entry, and triggers webhooks.
duplicateDocumentForCollectionDuplicate a document including its blocks. Creates new block records for exclusive blocks and shares references for shared blocks.
restoreFieldsFromVersionRestore specific fields from a version snapshot to the current document.
bulkUpdateStatusUpdate the status of multiple documents in a single operation.
bulkDeleteDocumentsDelete multiple documents in a single operation. Runs delete hooks for each.
bulkUpdateTagsAdd or remove tags from multiple documents in a single operation.
bulkCreateDocumentsCreate multiple documents in a single operation (used by import).

Mutations — Globals

FunctionDescription
updateGlobalDocumentCreate or update a global’s document. Runs global hooks, creates version snapshot, and logs audit entry.

Mutations — User List Config

FunctionDescription
setUserListConfigSave user-specific list view configuration for a collection (column order, sort, filters).
deleteUserListConfigReset user-specific list view configuration to defaults.

Mutations — Saved Views

FunctionDescription
createSavedViewCreate a named saved view (filter + sort + column config) for a collection.
updateSavedViewUpdate an existing saved view.
deleteSavedViewDelete a saved view.

Mutations — Files & Uploads

FunctionDescription
confirmFileUploadConfirm a file upload and create the file record in the Vextro file registry.
deleteFileUploadDelete a file record and its associated storage entry.
updateFileFocalAndCropUpdate the focal point and crop settings for an image file.
updateFileProcessingStatusUpdate the processing status of a file (e.g., after image variant generation).
deleteOrphanedFilesBatch delete orphaned file records and their storage entries.

Mutations — Blocks

FunctionDescription
deleteOrphanedBlocksBatch delete orphaned block records that are no longer referenced by any document.

Mutations — Webhooks

FunctionDescription
createWebhookCreate a new webhook endpoint configuration.
updateWebhookUpdate an existing webhook configuration.
deleteWebhookDelete a webhook configuration.
testWebhookSend a test payload to a webhook endpoint.
replayWebhookDeliveryReplay a failed webhook delivery attempt.

Mutations — Presence

FunctionDescription
presenceHeartbeatUpdate the current user’s presence heartbeat for a document, keeping their presence indicator active.
presenceFieldUpdateUpdates field-level presence data (focused field and dirty fields) for the current user on a specific document. Used by the admin UI for real-time field-level presence indicators.
presenceClearClear the current user’s presence from a specific document.
presenceClearAllClear all presence records for the current user across all documents.

Mutations — Notifications

FunctionDescription
markNotificationAsReadMark a single notification as read.
markAllNotificationsAsReadMark all notifications for the current user as read.
deleteNotificationDelete a notification.

Mutations — Templates

FunctionDescription
createTemplateCreate a new document template for a collection.
updateTemplateUpdate an existing template.
deleteTemplateDelete a template.

Mutations — Access Control (Roles & Permissions)

FunctionDescription
createRoleCreate a new role.
updateRoleUpdate a role’s name, slug, or description.
deleteRoleDelete a role and all associated user-role and role-permission assignments.
addPermissionToRoleAssign a permission to a role.
removePermissionFromRoleRemove a permission from a role.

Mutations — Users

FunctionDescription
updateUserProfileUpdate the current user’s profile fields (limited to userProfileFields).
updateUserStatusUpdate a user’s status (e.g., active/inactive). Triggers the onUserStatusChange callback.
assignRoleToUserAssign a role to a user.
removeRoleFromUserRemove a role assignment from a user.

Mutations — Scopes

FunctionDescription
assignUserScopeGrant a user access to a specific scope value.
removeUserScopeRemove a user’s access to a specific scope value.
Previous
Collections, Globals & Blocks