supa-seed
Version:
A constraint-aware, framework-agnostic database seeding framework with deep PostgreSQL business logic discovery and MakerKit integration support
386 lines • 14.5 kB
TypeScript
/**
* MakerKit Framework Strategy
* Implements framework-specific seeding logic for MakerKit applications
*/
import type { createClient } from '@supabase/supabase-js';
import { SeedingStrategy, DatabaseSchema, FrameworkDetectionResult, UserData, User, ConstraintHandlingResult, ConstraintHandler, TableConstraints, StrategyConstraintResult } from '../strategy-interface';
import type { CompleteUserData, CompleteUserResult } from '../../../auth/auth-types';
import type { DevelopmentWebhookConfig, WebhookEndpoint, PlatformWebhookConfig } from '../../../webhooks/webhook-types';
import type { ComplianceEngineResult, ComplianceEngineConfig } from '../../analysis/rls-compliance-engine';
import type { UnifiedDetectionResult } from '../../detection/detection-integration';
import type { AutoConfigurationResult } from '../../detection/auto-configurator';
import type { FlexibleSeedConfig } from '../../../core/types/config-types';
import type { BusinessLogicAnalysisResult, RLSComplianceOptions, RLSComplianceResult, UserContext } from '../../analysis/business-logic-types';
import type { RelationshipAnalysisResult } from '../../analysis/relationship-analyzer';
import type { JunctionTableDetectionResult, JunctionSeedingOptions, JunctionSeedingResult } from '../../../schema/junction-table-handler';
import type { DependencyGraph } from '../../../schema/dependency-graph';
import type { TenantDiscoveryResult, TenantSeedingResult, TenantIsolationReport, TenantDataGenerationOptions, TenantInfo, TenantScopeInfo } from '../../../schema/tenant-types';
import type { StorageIntegrationResult, StorageConfig, StoragePermissionCheck, StorageQuotaInfo, MediaAttachment } from '../../generation/storage/storage-types';
type SupabaseClient = ReturnType<typeof createClient>;
export declare class MakerKitStrategy implements SeedingStrategy {
name: string;
private client;
private version?;
private detectedFeatures;
private constraintEngine?;
private constraintRegistry?;
private businessLogicAnalyzer?;
private rlsCompliantSeeder?;
private detectionEngine?;
private autoConfigurator?;
private detectionResults?;
private autoConfiguration?;
private relationshipAnalyzer?;
private junctionTableHandler?;
private multiTenantManager?;
private storageIntegrationManager?;
private identityManager?;
private webhookManager?;
private rlsComplianceEngine?;
private rlsComplianceValidator?;
private authFlowConfig;
initialize(client: SupabaseClient): Promise<void>;
/**
* Perform smart detection and auto-configuration (Task 2.3.2)
*/
performSmartDetectionAndConfiguration(baseConfiguration?: Partial<FlexibleSeedConfig>): Promise<AutoConfigurationResult>;
/**
* Get detection results (if available)
*/
getDetectionResults(): UnifiedDetectionResult | undefined;
/**
* Get auto-configuration results (if available)
*/
getAutoConfiguration(): AutoConfigurationResult | undefined;
/**
* Apply auto-configuration to seeding process
*/
applyAutoConfiguration(userConfiguration?: Partial<FlexibleSeedConfig>): Promise<Partial<FlexibleSeedConfig>>;
/**
* Get platform-specific user archetypes based on detection
*/
getPlatformSpecificArchetypes(): string[];
/**
* Get optimized seeding parameters based on detection
*/
getOptimizedSeedingParameters(): {
userCount: number;
setupsPerUser: number;
imagesPerSetup: number;
enableRealImages: boolean;
};
getPriority(): number;
detect(schema: DatabaseSchema): Promise<FrameworkDetectionResult>;
createUser(data: UserData): Promise<User>;
/**
* Create complete user with auth.users + auth.identities + accounts + profiles
* Implements FR-1.1: Complete authentication flow
*/
createCompleteUser(data: CompleteUserData): Promise<CompleteUserResult>;
handleConstraints(table: string, data: any): Promise<ConstraintHandlingResult>;
getRecommendations(): string[];
supportsFeature(feature: string): boolean;
/**
* Configure MFA settings for the strategy
* Implements FR-1.2: Add MFA Factor Support
*/
configureMFA(enableMFA: boolean, options?: {
defaultSecurityLevel?: 'basic' | 'enhanced' | 'maximum';
supportedFactorTypes?: ('totp' | 'phone')[];
enforceForRoles?: string[];
}): void;
/**
* Get MFA validation result for the platform
* TODO: MFA functionality temporarily disabled
*/
validateMFASupport(): Promise<{
supported: boolean;
tableExists: boolean;
hasPermissions: boolean;
errors: string[];
warnings: string[];
}>;
/**
* Configure development webhooks for the strategy
* Implements FR-1.3: Development Webhook Setup
*/
configureWebhooks(config: DevelopmentWebhookConfig): Promise<void>;
/**
* Setup development webhook endpoints automatically
*/
setupDevelopmentWebhooks(): Promise<{
success: boolean;
endpoints: WebhookEndpoint[];
errors: string[];
}>;
/**
* Generate platform-specific webhook configuration
*/
generatePlatformWebhookConfig(architecture?: 'individual' | 'team' | 'hybrid', domain?: 'outdoor' | 'saas' | 'ecommerce' | 'social' | 'generic'): PlatformWebhookConfig | null;
/**
* Validate webhook support for the platform
*/
validateWebhookSupport(): Promise<{
supported: boolean;
configured: boolean;
errors: string[];
warnings: string[];
}>;
/**
* Trigger webhook for user creation (integrates with createCompleteUser)
*/
private triggerUserCreatedWebhook;
/**
* Discover constraints using MakerKit-aware analysis
*/
discoverConstraints(tableNames?: string[]): Promise<StrategyConstraintResult>;
/**
* Get MakerKit-specific constraint handlers
*/
getConstraintHandlers(): ConstraintHandler[];
/**
* Apply constraint fixes using MakerKit-aware logic
*/
applyConstraintFixes(table: string, data: any, constraints: TableConstraints): Promise<ConstraintHandlingResult>;
/**
* Analyze business logic patterns for MakerKit
*/
analyzeBusinessLogic(): Promise<BusinessLogicAnalysisResult>;
/**
* Seed data with RLS compliance for MakerKit
*/
seedWithRLSCompliance(table: string, data: any[], userContext?: UserContext): Promise<RLSComplianceResult>;
/**
* Get RLS compliance options for MakerKit
*/
getRLSComplianceOptions(): RLSComplianceOptions;
/**
* Analyze database relationships for MakerKit-aware seeding
*/
analyzeRelationships(): Promise<RelationshipAnalysisResult>;
/**
* Get dependency graph optimized for MakerKit seeding order
*/
getDependencyGraph(): Promise<DependencyGraph>;
/**
* Detect junction tables with MakerKit-specific patterns
*/
detectJunctionTables(): Promise<JunctionTableDetectionResult>;
/**
* Seed junction table with MakerKit-specific options
*/
seedJunctionTable(tableName: string, options?: Partial<JunctionSeedingOptions>): Promise<JunctionSeedingResult>;
/**
* Get optimal seeding order for MakerKit schemas
*/
getSeedingOrder(): Promise<string[]>;
/**
* Adjust seeding order for MakerKit-specific requirements
*/
private adjustSeedingOrderForMakerKit;
private detectMakerKitVersion;
/**
* Create MFA factors for a user based on their preferences
* Implements FR-1.2: Add MFA Factor Support
* TODO: MFA functionality not fully implemented - returning empty array
*/
private createMFAFactorsForUser;
/**
* Get default auth flow configuration for MakerKit
*/
private getDefaultAuthFlowConfig;
/**
* Ensure account record exists for user
*/
private ensureAccountExists;
/**
* Ensure profile record exists for user
*/
private ensureProfileExists;
/**
* Multi-Tenant Methods Implementation
*/
/**
* Discover tenant-scoped tables and relationships
*/
discoverTenantScopes(): Promise<TenantDiscoveryResult>;
/**
* Create tenant-aware data with proper tenant isolation
*/
createTenantScopedData(tenantId: string, tableName: string, data: any[], options?: Partial<TenantDataGenerationOptions>): Promise<any[]>;
/**
* Generate tenant accounts (personal and team)
*/
generateTenantAccounts(count: number, options?: Partial<TenantDataGenerationOptions>): Promise<TenantInfo[]>;
/**
* Create MakerKit account record in database
*/
private createMakerKitAccount;
/**
* Validate tenant boundary isolation
*/
validateTenantIsolation(tenantId: string): Promise<TenantIsolationReport>;
/**
* Seed data across multiple tenants with proper isolation
*/
seedMultiTenantData(tenants: TenantInfo[], options?: Partial<TenantDataGenerationOptions>): Promise<TenantSeedingResult>;
/**
* Generate sample data for a tenant and table
*/
private generateTenantSampleData;
/**
* Get tenant scope information for a table
*/
getTenantScopeInfo(tableName: string): Promise<TenantScopeInfo | null>;
/**
* Storage Integration Methods Implementation
*/
/**
* Integrate with Supabase Storage for file uploads and media management
*/
integrateWithStorage(setupId: string, accountId?: string, config?: Partial<StorageConfig>): Promise<StorageIntegrationResult>;
/**
* Check storage permissions and RLS compliance
*/
checkStoragePermissions(bucketName: string): Promise<StoragePermissionCheck>;
/**
* Get storage quota and usage information
*/
getStorageQuota(bucketName: string): Promise<StorageQuotaInfo>;
/**
* Generate and upload media attachments for a specific entity
*/
generateMediaAttachments(entityId: string, entityType: string, count?: number, config?: Partial<StorageConfig>): Promise<MediaAttachment[]>;
/**
* Get framework-specific storage configuration
*/
getStorageConfig(): Partial<StorageConfig>;
/**
* Enhanced RLS Compliance Validation Methods (Task 1.4.5)
* Comprehensive RLS compliance validation for 100% security coverage
*/
/**
* Perform comprehensive RLS compliance analysis for MakerKit applications
*/
validateRLSCompliance(options?: Partial<ComplianceEngineConfig>): Promise<ComplianceEngineResult>;
/**
* Quick RLS compliance check for seeding operations
*/
quickRLSCheck(tableName: string, operation?: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE', userContext?: UserContext): Promise<{
isCompliant: boolean;
requiresUserContext: boolean;
recommendations: string[];
riskLevel: 'low' | 'medium' | 'high' | 'critical';
}>;
/**
* Validate RLS compliance before seeding operation
*/
validatePreSeedingRLS(tableName: string, dataCount: number, userContext?: UserContext): Promise<{
approved: boolean;
complianceStatus: 'compliant' | 'warning' | 'blocked';
message: string;
suggestedActions: string[];
}>;
/**
* Generate comprehensive RLS compliance report for MakerKit
*/
generateRLSComplianceReport(format?: 'json' | 'markdown' | 'html'): Promise<string>;
/**
* Auto-fix common MakerKit RLS issues (conservative approach)
*/
autoFixMakerKitRLSIssues(options?: {
dryRun?: boolean;
enableRLSOnly?: boolean;
skipCriticalFixes?: boolean;
}): Promise<{
fixesApplied: number;
fixesFailed: number;
fixesSkipped: number;
recommendations: string[];
requiresManualReview: string[];
}>;
/**
* Private helper methods for MakerKit RLS enhancement
*/
private enhanceComplianceResultForMakerKit;
private generateMakerKitRLSRecommendations;
private assessMakerKitRLSRisk;
private checkMakerKitSpecificRLSPatterns;
private checkForConstraint;
private analyzeMakerKitRLSPatterns;
private generateMakerKitSpecificRecommendations;
private generateMakerKitRLSFixRecommendations;
private enhanceMarkdownReportForMakerKit;
/**
* Advanced constraint handling with multi-table resolution
*/
handleAdvancedConstraints(tableName: string, data: any, constraints: any[]): Promise<ConstraintHandlingResult>;
/**
* Generate intelligent slugs for team accounts
*/
generateTeamAccountSlug(data: any): Promise<string>;
/**
* Validate and fix constraint violations with advanced debugging
*/
validateAndFixConstraints(tableName: string, data: any[], constraints: any[]): Promise<{
validatedData: any[];
constraintReport: any;
debuggingSession?: string;
}>;
/**
* Handle complex MakerKit business rules
*/
handleMakerKitBusinessRules(data: any, tableName: string): Promise<any>;
/**
* Handle account creation business rules
*/
private handleAccountCreationRules;
/**
* Handle organization membership rules
*/
private handleMembershipRules;
/**
* Handle subscription business rules
*/
private handleSubscriptionRules;
/**
* Handle invitation workflow rules
*/
private handleInvitationRules;
/**
* Generate comprehensive constraint handling report
*/
generateConstraintHandlingReport(format?: 'json' | 'markdown'): Promise<string>;
/**
* Analyze constraint handling statistics
*/
private analyzeConstraintHandlingStats;
/**
* Generate markdown constraint report
*/
private generateConstraintMarkdownReport;
/**
* Helper methods for constraint analysis
*/
private isMakerKitSpecificConstraint;
private isComplexConstraint;
private getTableList;
/**
* Apply record modifications from multi-table resolver
*/
private applyModifications;
/**
* Get compliance details from union type
*/
private getComplianceDetails;
/**
* Calculate grade from numeric score
*/
private calculateGradeFromScore;
/**
* Convert resolver results to constraint fixes
*/
private convertToConstraintFixes;
}
export {};
//# sourceMappingURL=makerkit-strategy.d.ts.map