import { GLOBAL_REFERENCED_MODELS, TENANT_SCOPED_MODELS, type GlobalReferencedModel, type TenantScopedModel, } from "./models.js"; export interface TenantDerivedModel { /** Prisma model name (PascalCase as written in the schema). */ readonly model: string; /** Schema file the model lives in, for diagnostics. */ readonly schema: string; /** * To-one relation paths that reach a model with a tenantId column. * Multiple paths default to OR; `tenantPathMode` can require all of them. */ readonly tenantPaths: ReadonlyArray; readonly tenantPathMode?: "any" | "all"; /** Nullable relations must be absent or resolve back to the same tenant. */ readonly optionalTenantPaths?: ReadonlyArray<{ readonly foreignKey: string; readonly path: readonly string[]; }>; /** Required relations whose owner may be tenant-specific or global. */ readonly tenantOrGlobalPaths?: ReadonlyArray; /** Nullable variant of tenantOrGlobalPaths. */ readonly optionalTenantOrGlobalPaths?: ReadonlyArray<{ readonly foreignKey: string; readonly path: readonly string[]; }>; /** Models that must already exist when this model is restored. */ readonly dependsOn: readonly string[]; /** * Direct tenant models that reference this derived model. This is rare, * but it matters for FK-safe restore/delete ordering. */ readonly restoreBefore?: readonly string[]; /** Cursor metadata for models whose stable unique key is not `id`. */ readonly cursor?: { readonly fields: readonly string[]; readonly compoundField: string; }; } /** * Tenant-owned models whose scope is inherited exclusively through an FK. * * The declaration order is parents-first. `TENANT_LIFECYCLE_MODELS` combines * this registry with direct tenant models and applies the explicit dependency * edges below, so snapshot/restore and hard-delete share one safe ordering. */ export const TENANT_DERIVED_MODELS: readonly TenantDerivedModel[] = [ // analytics.prisma { model: "AnalyticsUniqueVisitor", schema: "analytics.prisma", tenantPaths: [["portal"], ["portalUser"]], optionalTenantPaths: [ { foreignKey: "portalId", path: ["portal"] }, { foreignKey: "portalUserId", path: ["portalUser"] }, ], dependsOn: ["Portal", "PortalUser"], }, { model: "AnalyticsPageView", schema: "analytics.prisma", tenantPaths: [["uniqueVisitor", "portal"], ["uniqueVisitor", "portalUser"]], optionalTenantPaths: [ { foreignKey: "portalId", path: ["portal"] }, { foreignKey: "portalUserId", path: ["portalUser"] }, ], dependsOn: ["AnalyticsUniqueVisitor", "Portal", "PortalUser"], }, { model: "AnalyticsEvent", schema: "analytics.prisma", tenantPaths: [["uniqueVisitor", "portal"], ["uniqueVisitor", "portalUser"]], optionalTenantPaths: [ { foreignKey: "portalId", path: ["portal"] }, { foreignKey: "portalUserId", path: ["portalUser"] }, ], dependsOn: ["AnalyticsUniqueVisitor", "FeatureFlag", "Portal", "PortalUser"], }, // core.prisma { model: "EventWebhookAttempt", schema: "core.prisma", tenantPaths: [["event"]], dependsOn: ["Event"], }, // email.prisma { model: "Email", schema: "email.prisma", tenantPaths: [["tenantInboundAddress"]], dependsOn: ["TenantInboundAddress"], }, { model: "EmailRead", schema: "email.prisma", tenantPaths: [["email", "tenantInboundAddress"]], dependsOn: ["Email"], }, { model: "EmailCc", schema: "email.prisma", tenantPaths: [["email", "tenantInboundAddress"]], dependsOn: ["Email"], }, { model: "EmailAttachment", schema: "email.prisma", tenantPaths: [["email", "tenantInboundAddress"]], dependsOn: ["Email"], }, { model: "OutboundEmailOpen", schema: "email.prisma", tenantPaths: [["outboundEmail"]], dependsOn: ["OutboundEmail"], }, { model: "OutboundEmailClick", schema: "email.prisma", tenantPaths: [["outboundEmail"]], dependsOn: ["OutboundEmail"], }, // emailSequences.prisma { model: "EmailSequenceStepDelivery", schema: "emailSequences.prisma", tenantPaths: [["run"]], dependsOn: ["EmailSequenceRun"], }, // featureFlags.prisma { model: "FeatureFlagFilter", schema: "featureFlags.prisma", tenantPaths: [["featureFlag"]], dependsOn: ["FeatureFlag"], }, { model: "FeatureFlagAudit", schema: "featureFlags.prisma", tenantPaths: [["flag"]], dependsOn: ["FeatureFlag"], }, // knowledgeBase.prisma. Category/article FKs default to RESTRICT, so the // explicit order is required for both restore and reverse-order deletion. { model: "KnowledgeBaseCategory", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBase"]], dependsOn: ["KnowledgeBase"], }, { model: "KnowledgeBaseCategorySection", schema: "knowledgeBase.prisma", tenantPaths: [["category", "knowledgeBase"]], dependsOn: ["KnowledgeBaseCategory"], }, { model: "KnowledgeBaseArticle", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBase"]], optionalTenantPaths: [ { foreignKey: "categoryId", path: ["category", "knowledgeBase"] }, { foreignKey: "sectionId", path: ["section", "category", "knowledgeBase"] }, ], dependsOn: ["KnowledgeBase", "KnowledgeBaseCategory", "KnowledgeBaseCategorySection"], }, { model: "KnowledgeBaseRelatedArticle", schema: "knowledgeBase.prisma", tenantPaths: [["article", "knowledgeBase"], ["relatedArticle", "knowledgeBase"]], tenantPathMode: "all", dependsOn: ["KnowledgeBaseArticle"], }, { model: "KnowledgeBaseViews", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBase"]], dependsOn: ["KnowledgeBase"], }, { model: "KnowledgeBaseArticleViews", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBaseArticle", "knowledgeBase"]], dependsOn: ["KnowledgeBaseArticle"], cursor: { fields: ["knowledgeBaseArticleId", "userAnalyticsId"], compoundField: "knowledgeBaseArticleId_userAnalyticsId", }, }, { model: "KnowledgeBaseArticleUpvotes", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBaseArticle", "knowledgeBase"]], dependsOn: ["KnowledgeBaseArticle"], cursor: { fields: ["knowledgeBaseArticleId", "userAnalyticsId"], compoundField: "knowledgeBaseArticleId_userAnalyticsId", }, }, { model: "KnowledgeBaseArticleDownvotes", schema: "knowledgeBase.prisma", tenantPaths: [["knowledgeBaseArticle", "knowledgeBase"]], dependsOn: ["KnowledgeBaseArticle"], cursor: { fields: ["knowledgeBaseArticleId", "userAnalyticsId"], compoundField: "knowledgeBaseArticleId_userAnalyticsId", }, }, // onboarding.prisma { model: "OnboardingSessionAction", schema: "onboarding.prisma", tenantPaths: [["onboardingSession"]], dependsOn: ["OnboardingSession"], }, { model: "OnboardingSessionFilterMatch", schema: "onboarding.prisma", tenantPaths: [["onboardingSession"]], dependsOn: ["OnboardingSession"], }, { model: "OnboardingSessionStep", schema: "onboarding.prisma", tenantPaths: [["onboardingSession"]], dependsOn: ["OnboardingSession"], }, // permissions.prisma { model: "RolePermission", schema: "permissions.prisma", tenantPaths: [["role"]], dependsOn: ["Role"], }, { model: "GroupUser", schema: "permissions.prisma", tenantPaths: [["group"]], dependsOn: ["Group"], }, // plugins.prisma { model: "PluginUserConfig", schema: "plugins.prisma", tenantPaths: [["plugin"]], dependsOn: ["Plugin"], }, // portals.prisma { model: "PortalPage", schema: "portals.prisma", tenantPaths: [["portal"]], dependsOn: ["Portal"] }, // subscriptions.prisma { model: "TenantSubscriptionProduct", schema: "subscriptions.prisma", tenantPaths: [["tenantSubscription"]], dependsOn: ["TenantSubscription"], // TenantProductAcquisition optionally links the granted product. Restore // the derived entitlement row first whenever that link is populated. restoreBefore: ["TenantProductAcquisition"], }, { model: "TenantSubscriptionProductPrice", schema: "subscriptions.prisma", tenantPaths: [["tenantSubscriptionProduct", "tenantSubscription"]], dependsOn: ["TenantSubscriptionProduct"], }, // workflows.prisma { model: "WorkflowBlock", schema: "workflows.prisma", tenantPaths: [["workflow"]], dependsOn: ["Workflow"], // WorkflowExecution.waitingBlockId uses the default RESTRICT action. restoreBefore: ["WorkflowExecution"], }, { model: "WorkflowBlockConditionGroup", schema: "workflows.prisma", tenantPaths: [["workflowBlock", "workflow"]], dependsOn: ["WorkflowBlock"], }, { model: "WorkflowBlockCondition", schema: "workflows.prisma", tenantPaths: [["workflowBlockConditionGroup", "workflowBlock", "workflow"]], dependsOn: ["WorkflowBlockConditionGroup"], }, { model: "WorkflowBlockToBlock", schema: "workflows.prisma", tenantPaths: [["fromBlock", "workflow"], ["toBlock", "workflow"]], tenantPathMode: "all", dependsOn: ["WorkflowBlock"], }, { model: "WorkflowInputExample", schema: "workflows.prisma", tenantPaths: [["workflow"]], dependsOn: ["Workflow"], }, { model: "WorkflowBlockExecution", schema: "workflows.prisma", tenantPaths: [["workflowExecution"]], tenantOrGlobalPaths: [["workflowBlock", "workflow"]], optionalTenantOrGlobalPaths: [ { foreignKey: "fromWorkflowBlockId", path: ["fromWorkflowBlock", "workflow"] }, ], dependsOn: ["WorkflowBlock", "WorkflowExecution"], }, ]; export interface DirectTenantLifecycleModel extends TenantScopedModel { readonly scope: "direct"; } export interface DerivedTenantLifecycleModel extends TenantDerivedModel { readonly scope: "derived-child"; } export type TenantLifecycleModel = DirectTenantLifecycleModel | DerivedTenantLifecycleModel; function buildTenantLifecycleModels(): readonly TenantLifecycleModel[] { const direct: DirectTenantLifecycleModel[] = TENANT_SCOPED_MODELS.map((entry) => ({ ...entry, scope: "direct", })); const derived: DerivedTenantLifecycleModel[] = TENANT_DERIVED_MODELS.map((entry) => ({ ...entry, scope: "derived-child", })); const nodes: TenantLifecycleModel[] = [...direct, ...derived]; const index = new Map(nodes.map((entry, position) => [entry.model, position])); if (index.size !== nodes.length) { throw new Error("Tenant lifecycle registry contains duplicate model names."); } const outgoing = new Map>(); const indegree = new Map(nodes.map((entry) => [entry.model, 0])); const addEdge = (parent: string, child: string): void => { if (!index.has(parent) || !index.has(child)) { throw new Error(`Tenant lifecycle dependency references an unknown model: ${parent} -> ${child}.`); } const children = outgoing.get(parent) ?? new Set(); if (children.has(child)) return; children.add(child); outgoing.set(parent, children); indegree.set(child, (indegree.get(child) ?? 0) + 1); }; // Preserve the existing direct-model order while allowing a derived model // to be inserted before a direct model that points back to it. for (let i = 1; i < direct.length; i += 1) { addEdge(direct[i - 1]!.model, direct[i]!.model); } for (const entry of derived) { for (const dependency of entry.dependsOn) addEdge(dependency, entry.model); for (const target of entry.restoreBefore ?? []) addEdge(entry.model, target); } const ready = nodes.filter((entry) => indegree.get(entry.model) === 0); const ordered: TenantLifecycleModel[] = []; while (ready.length > 0) { ready.sort((a, b) => index.get(a.model)! - index.get(b.model)!); const current = ready.shift()!; ordered.push(current); for (const child of outgoing.get(current.model) ?? []) { const next = (indegree.get(child) ?? 0) - 1; indegree.set(child, next); if (next === 0) ready.push(nodes[index.get(child)!]!); } } if (ordered.length !== nodes.length) { const blocked = nodes.filter((entry) => !ordered.includes(entry)).map((entry) => entry.model); throw new Error(`Tenant lifecycle registry contains a dependency cycle: ${blocked.join(", ")}.`); } return ordered; } /** Parents-first order for snapshot and restore; reverse it for hard-delete. */ export const TENANT_LIFECYCLE_MODELS: readonly TenantLifecycleModel[] = buildTenantLifecycleModels(); const DERIVED_BY_MODEL = new Map(TENANT_DERIVED_MODELS.map((entry) => [entry.model, entry])); export function isTenantDerivedModel(model: string): boolean { return DERIVED_BY_MODEL.has(model); } export function tenantWhereForLifecycleModel( entry: TenantLifecycleModel, tenantId: string, ): Record { if (entry.scope === "direct") return { [entry.tenantField]: tenantId }; const filters = entry.tenantPaths.map((path) => relationPathWhere(path, tenantId)); const primary = filters.length === 1 ? filters[0]! : entry.tenantPathMode === "all" ? { AND: filters } : { OR: filters }; const optional = (entry.optionalTenantPaths ?? []).map(({ foreignKey, path }) => ({ OR: [ { [foreignKey]: null }, relationPathWhere(path, tenantId), ], })); const tenantOrGlobal = (entry.tenantOrGlobalPaths ?? []).map((path) => ({ OR: [relationPathWhere(path, tenantId), relationPathWhere(path, null)], })); const optionalTenantOrGlobal = (entry.optionalTenantOrGlobalPaths ?? []).map( ({ foreignKey, path }) => ({ OR: [ { [foreignKey]: null }, relationPathWhere(path, tenantId), relationPathWhere(path, null), ], }), ); const guards = [...optional, ...tenantOrGlobal, ...optionalTenantOrGlobal]; return guards.length === 0 ? primary : { AND: [primary, ...guards] }; } function relationPathWhere(path: readonly string[], tenantId: string | null): Record { if (path.length === 0) throw new Error("Tenant relation path must not be empty."); return path.reduceRight>( (nested, relation) => ({ [relation]: nested }), { tenantId }, ); } export interface TenantLifecycleGlobalReferencedModel extends GlobalReferencedModel { /** Extra predicate for hybrid models where only the global (tenantId NULL) row is copied. */ readonly where?: Readonly>; /** Do not fetch an id already present in this model's tenant JSONL slice. */ readonly excludeIdsPresentInTenantSlice?: boolean; /** Self-referential FK columns that require parent-first row ordering. */ readonly selfParentFields?: readonly string[]; /** Functional child rows that must accompany a referenced global parent. */ readonly children?: ReadonlyArray<{ readonly model: string; readonly foreignKey: string; }>; } /** * Global and hybrid rows referenced by the complete tenant lifecycle slice. * These are deliberately separate from the direct tenant registry: hybrid * rows keep tenantId=NULL and derived globals have no tenantId at all. */ export const DERIVED_GLOBAL_REFERENCED_MODELS: readonly TenantLifecycleGlobalReferencedModel[] = [ { model: "User", schema: "accounts.prisma", referencedBy: [ { model: "AnalyticsUniqueVisitor", fkColumn: "userId" }, { model: "EmailRead", fkColumn: "userId" }, { model: "GroupUser", fkColumn: "userId" }, { model: "KnowledgeBaseArticle", fkColumn: "createdByUserId" }, ], }, { model: "Role", schema: "permissions.prisma", where: { tenantId: null }, excludeIdsPresentInTenantSlice: true, children: [{ model: "RolePermission", foreignKey: "roleId" }], referencedBy: [{ model: "UserRole", fkColumn: "roleId" }], }, { model: "Permission", schema: "permissions.prisma", referencedBy: [{ model: "RolePermission", fkColumn: "permissionId" }], }, { model: "RolePermission", schema: "permissions.prisma", referencedBy: [], }, { model: "Workflow", schema: "workflows.prisma", where: { tenantId: null }, excludeIdsPresentInTenantSlice: true, children: [ { model: "WorkflowBlock", foreignKey: "workflowId" }, { model: "WorkflowInputExample", foreignKey: "workflowId" }, ], referencedBy: [ { model: "WorkflowExecution", fkColumn: "workflowId" }, // A referenced global block can belong to a different global workflow. { model: "WorkflowBlock", fkColumn: "workflowId" }, ], }, { model: "WorkflowBlock", schema: "workflows.prisma", where: { workflow: { tenantId: null } }, excludeIdsPresentInTenantSlice: true, children: [ { model: "WorkflowBlockConditionGroup", foreignKey: "workflowBlockId" }, { model: "WorkflowBlockToBlock", foreignKey: "fromBlockId" }, ], referencedBy: [ { model: "WorkflowExecution", fkColumn: "waitingBlockId" }, { model: "WorkflowBlockExecution", fkColumn: "workflowBlockId" }, { model: "WorkflowBlockExecution", fkColumn: "fromWorkflowBlockId" }, { model: "WorkflowBlockToBlock", fkColumn: "fromBlockId" }, { model: "WorkflowBlockToBlock", fkColumn: "toBlockId" }, ], }, { model: "WorkflowBlockConditionGroup", schema: "workflows.prisma", children: [ { model: "WorkflowBlockCondition", foreignKey: "workflowBlockConditionGroupId" }, ], referencedBy: [], }, { model: "WorkflowBlockCondition", schema: "workflows.prisma", referencedBy: [], }, { model: "WorkflowBlockToBlock", schema: "workflows.prisma", referencedBy: [], }, { model: "WorkflowInputExample", schema: "workflows.prisma", referencedBy: [], }, { model: "EmailSequence", schema: "emailSequences.prisma", where: { tenantId: null }, excludeIdsPresentInTenantSlice: true, referencedBy: [{ model: "EmailSequenceRun", fkColumn: "sequenceId" }], }, { model: "FeatureFlag", schema: "featureFlags.prisma", where: { tenantId: null }, excludeIdsPresentInTenantSlice: true, selfParentFields: ["parentFlagId"], children: [{ model: "FeatureFlagFilter", foreignKey: "featureFlagId" }], referencedBy: [ { model: "AnalyticsEvent", fkColumn: "featureFlagId" }, // Follow the complete global dependency chain for an empty target. { model: "FeatureFlag", fkColumn: "parentFlagId" }, ], }, { model: "FeatureFlagFilter", schema: "featureFlags.prisma", referencedBy: [], }, ]; function mergeGlobalReferences(): readonly TenantLifecycleGlobalReferencedModel[] { const byModel = new Map< string, Omit & { referencedBy: Array<{ model: string; fkColumn: string }>; } >(); for (const entry of [...GLOBAL_REFERENCED_MODELS, ...DERIVED_GLOBAL_REFERENCED_MODELS]) { const current = byModel.get(entry.model) ?? { ...entry, referencedBy: [] }; current.referencedBy.push(...entry.referencedBy); byModel.set(entry.model, current); } return Array.from(byModel.values()); } export const TENANT_LIFECYCLE_GLOBAL_REFERENCED_MODELS: readonly TenantLifecycleGlobalReferencedModel[] = mergeGlobalReferences();