UNPKG

brick-codegen

Version:

Better React Native native module development

704 lines (703 loc) 19.7 kB
//#region src/scanner.d.ts interface ScannedModule { name: string; path: string; specPath: string; packageJsonPath: string; version: string; hasIosImplementation: boolean; hasAndroidImplementation: boolean; brickConfig?: any; androidPackage?: string; androidModuleName?: string; androidPath?: string; } interface ScanResult { modules: ScannedModule[]; errors: string[]; warnings: string[]; } declare class Scanner { private config; constructor(config: ComponentConfig); /** * Scans package.json dependencies for Brick modules * In library mode: only scans current package for .brick.ts files * In user project mode: scans dependencies for Brick modules */ scanBrickModules(): Promise<ScannedModule[]>; /** * Scans a single module to determine if it's a Brick module */ private scanSingleModule; /** * Checks if a package.json indicates a Brick module */ private isBrickModule; /** * Finds the spec file for a module */ private findSpecFile; /** * Checks if module has iOS implementation */ private hasIosImplementation; /** * Checks if module has Android implementation */ private hasAndroidImplementation; /** * Scans for local Brick modules (for development) */ private scanLocalModules; /** * Validates implementations for a module */ validateImplementations(module: ScannedModule): Promise<string[]>; /** * Validates iOS implementation */ private validateIosImplementation; /** * Validates Android implementation */ private validateAndroidImplementation; /** * Gets detailed scan results with validation */ getDetailedScanResults(): Promise<ScanResult>; /** * Scans current library for .brick.ts files (library mode only) */ scanCurrentLibrary(): Promise<ScannedModule[]>; private log; } //#endregion //#region src/parser.d.ts interface ParsedModule { name: string; moduleName: string; version: string; specPath: string; constants: ModuleConstant[]; methods: ModuleMethod[]; events?: ModuleEvent[]; sourceModule: ScannedModule; interfaceDefinitions: InterfaceDefinition[]; } interface ModuleMethod { name: string; params: MethodParameter[]; returnType: string; isAsync: boolean; isSync: boolean; signature: string; jsDocComment?: string; deprecated?: boolean; } interface MethodParameter { name: string; type: string; optional: boolean; defaultValue?: any; jsDocComment?: string; /** If parameter is a function type, structured representation */ functionType?: { paramTypes: string[]; returnType: string; /** * For each function parameter, whether it was declared as a rest parameter ("...args"). * This helps platform generators distinguish between a single array argument vs. TS rest. */ paramRestFlags?: boolean[]; }; /** True if parameter is a function/callback */ isFunction?: boolean; } interface ModuleConstant { name: string; type: string; value?: any; readonly: boolean; jsDocComment?: string; } interface ModuleEvent { name: string; payload?: string; jsDocComment?: string; /** Source file path where this event was defined */ sourceFile?: string; /** Line number in source file */ sourceLine?: number; /** Column number in source file */ sourceColumn?: number; } interface InterfaceDefinition { name: string; properties: InterfaceProperty[]; jsDocComment?: string; } interface InterfaceProperty { name: string; type: string; optional: boolean; jsDocComment?: string; } declare class Parser { private config; private interfaceDefinitions; private generatedInterfaces; private typeAnalyzer; private morphProject; private morphSourceFile; private currentSourceFile; private currentModuleName; constructor(config: ComponentConfig); /** * Extracts line and column information from a TypeScript node */ private getNodeLocation; /** * Creates error context from current parsing state */ private createErrorContext; /** * Parses a module specification file */ parseModuleSpec(module: ScannedModule): Promise<ParsedModule[]>; /** * Creates TypeScript source file */ private createSourceFile; /** * Extracts module information from source file */ private extractModuleInfo; /** * Visits a TypeScript AST node */ private visitNode; /** * Processes interface declaration */ private processInterface; /** * Processes type alias declaration */ private processTypeAlias; /** * Processes variable statement */ private processVariableStatement; /** * Checks if an interface is a module spec interface */ private isModuleSpecInterface; /** * Extracts module name from interface name * Example: "CalculatorModuleSpec" -> "Calculator" */ private extractModuleNameFromInterface; /** * Checks if a type alias is a module spec type */ private isModuleSpecType; /** * Checks if node has export modifier */ private hasExportModifier; /** * Extracts property from interface/type */ private extractProperty; /** * Extracts method from interface */ private extractMethod; /** * Converts a property with function type to a method * Handles properties like: methodName: (param: Type) => ReturnType */ private convertPropertyToMethod; /** * Extracts constants from a type literal */ private extractConstantsFromType; /** * Extracts supported events from array literal */ private extractSupportedEvents; /** * Extracts parameters from method signature */ private extractParameters; /** * Extracts default value from expression */ private extractDefaultValue; /** * Gets type string from type node */ private getTypeString; /** * Generates an interface name for nested object types */ private generateNestedInterfaceName; /** * Extracts nested object type as interface definition */ private extractNestedInterface; /** * Converts TypeScript type to string representation */ private typeToString; /** * Gets type string with method context for generating anonymous interfaces * Handles anonymous object types in method parameters and return types */ private getTypeStringWithMethodContext; /** * Checks if a type is a Promise type (string-based for backward compatibility) * For new code, prefer using ts-morph type analysis directly */ private isPromiseType; /** * Checks if a type node is a Promise using semantic analysis */ private isPromiseTypeNode; /** * Builds method signature string */ private buildMethodSignature; /** * Extracts JSDoc comment from node * Cleans up asterisk prefixes from each line */ private extractJSDocComment; /** * Checks if node is marked as deprecated */ private isDeprecated; /** * Infers type from value expression */ private inferTypeFromValue; /** * Extracts literal value from expression */ private extractLiteralValue; /** * Validates parsed module structure */ private validateParsedModule; /** * Validates method name conventions */ private isValidMethodName; /** * Validates event name conventions */ private isValidEventName; /** * Validates naming conventions */ validateNamingConventions(parsed: ParsedModule): string[]; /** * Validates types in the parsed module */ validateTypes(parsed: ParsedModule): Promise<string[]>; /** * Checks if type is valid */ private isValidType; private isCapitalCase; private isCamelCase; private isConstantCase; /** * Extracts interface definition from TypeScript AST */ private extractInterfaceDefinition; private capitalizeFirst; private log; } //#endregion //#region src/main-index.d.ts interface BrickCodegenConfig { projectRoot: string; outputIos: string; outputAndroid: string; outputAndroidAppPath: string; outputTypescript: string; debug?: boolean; platforms?: string[]; libraryMode?: boolean; clean?: boolean; } interface ComponentConfig { projectRoot: string; outputTypescript: string; outputIos: string; outputAndroid: string; outputAndroidAppPath: string; libraryMode?: boolean; debug?: boolean; selectedPlatforms?: string[]; } //#endregion //#region src/platforms/platform-interface.d.ts /** * Base interface with common methods for all platforms */ interface BasePlatformGenerator { /** * Check if this generator supports the target platform */ supports(target: string): boolean; /** * Generate bridge code for the platform * @param modules Parsed module specifications * @param scannedModules All scanned brick modules from dependencies */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; /** * Check if platform is available in current environment */ isAvailable(): boolean; } /** * iOS-specific platform generator interface */ interface IOSPlatformGeneratorInterface extends BasePlatformGenerator { /** * Platform name identifier - always "ios" for iOS platform */ getPlatformName(): "ios"; /** * Generate library types for iOS (Swift structs) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generate library protocol for iOS (Swift protocol) */ generateLibraryProtocol(module: ParsedModule): Promise<string>; } /** * Android-specific platform generator interface */ interface AndroidPlatformGeneratorInterface extends BasePlatformGenerator { /** * Platform name identifier - always "android" for Android platform */ getPlatformName(): "android"; /** * Generate library types for Android (Kotlin data classes) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generate library interface for Android (Kotlin interface) */ generateLibraryInterface(module: ParsedModule): Promise<string>; } /** * Discriminated union type for platform generators */ type PlatformGenerator = IOSPlatformGeneratorInterface | AndroidPlatformGeneratorInterface; /** * Type guard to check if a generator is for iOS */ declare function isIOSPlatformGenerator(generator: PlatformGenerator): generator is IOSPlatformGeneratorInterface; /** * Type guard to check if a generator is for Android */ declare function isAndroidPlatformGenerator(generator: PlatformGenerator): generator is AndroidPlatformGeneratorInterface; type SupportedPlatform = "ios" | "android"; //#endregion //#region src/platforms/android-platform.d.ts declare class AndroidPlatformGenerator implements AndroidPlatformGeneratorInterface { private config; private currentOutputDir; private scannedModules; private typeMapper; private bridgeGenerator; constructor(config: ComponentConfig); getPlatformName(): "android"; supports(target: string): boolean; /** * Main method - Generates Android bridge files */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; isAvailable(): boolean; /** * Generates Kotlin data classes for complex types and interfaces */ private generateKotlinDataClasses; /** * Generates a single Kotlin data class from TypeScript inline object type * Note: This is a fallback for inline objects. Most types should come from AST-based interfaces. */ private generateKotlinDataClass; /** * Gets available brick modules from scanned modules * Uses the scanned modules from Scanner instead of re-scanning */ private detectBrickModules; /** * Generate build.gradle */ private generateBuildGradle; private mapTypeScriptToKotlin; private getAllMethods; private getAllEvents; private getAllConstants; private capitalize; private logGenerated; /** * Generates BrickModuleBase.kt interface */ private generateBrickModuleBase; /** * Generates the main Android bridge file (BrickModule.kt) - like iOS BrickModule.mm */ private generateAndroidBridge; /** * Generates library imports for data types used in BrickModuleImpl */ private generateLibraryImports; /** * Generates Kotlin implementation file (BrickModuleImpl.kt) - like iOS BrickModuleImpl.swift */ private generateKotlinImplementation; /** * Extracts interface definitions from parsed module AST */ private extractInterfaceDefinitions; /** * Generates Kotlin data class from TypeScript interface definition */ private generateKotlinDataClassFromInterface; /** * Generates local module types in .brick/src/main/java/com/brickmodule/codegen/ directory */ private generateLocalModuleTypes; /** * Generates Kotlin types for library mode (public API) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generates Kotlin interface for library mode (public API) */ generateLibraryInterface(module: ParsedModule): Promise<string>; } //#endregion //#region src/platforms/ios-platform.d.ts declare class IOSPlatformGenerator implements IOSPlatformGeneratorInterface { private config; private scannedModules; private typeMapper; private bridgeGenerator; private methodGenerator; private protocolGenerator; private structGenerator; constructor(config: ComponentConfig); getPlatformName(): "ios"; supports(target: string): boolean; /** * Main method - Generates iOS bridge files (moved from BridgeGenerator.generateIOSBridge) */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; isAvailable(): boolean; /** * Generates BrickCodegen.h umbrella header file */ private generateBrickCodegenHeader; /** * Generates BrickModule.h header file */ private generateBrickModuleHeader; /** * Generates the main Objective-C bridge file (BrickModule.mm) */ private generateObjectiveCBridge; /** * Generates all Swift implementation files */ private generateSwiftImplementationFiles; /** * Generates main BrickModule.swift file */ private generateBrickModuleSwift; /** * Helper method to get Swift default value for a type */ private getSwiftDefaultValue; /** * Generates module-specific extension file (BrickModule+ModuleName.swift) */ private generateModuleExtension; /** * Generates the BrickModuleImpl.swift implementation holder */ private generateBrickModuleImplSwift; /** * Generates type aliases for a specific module */ private generateModuleTypeAliases; /** * Generates a Swift method implementation for a specific module */ private generateSwiftModuleMethod; /** * Generates a constant getter for a specific module */ private generateModuleConstantGetter; /** * Generates local module types in .brick/Types/ directory */ private generateLocalModuleTypes; /** * Generates event helper extension for protocol * Used by both library and local modules */ private generateEventHelpersExtension; /** * Generates Swift types for library mode (public API) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generates Swift protocol for library mode (public API) */ generateLibraryProtocol(module: ParsedModule): Promise<string>; /** * Generates BrickModule.podspec for iOS integration with automatic dependencies */ private generatePodspec; /** * Generates podspec dependencies based on discovered Brick modules * Uses the scanned modules from Scanner instead of re-scanning */ private generatePodspecDependencies; private getAllMethods; private getAllEvents; private getAllConstants; private logGenerated; } //#endregion //#region src/platforms/platform-registry.d.ts declare class PlatformRegistry { private generators; private scannedModules; constructor(config: ComponentConfig); /** * Set scanned modules to be passed to platform generators */ setScannedModules(modules: ScannedModule[]): void; /** * Get platform generator by name */ getGenerator(platform: SupportedPlatform): PlatformGenerator | undefined; /** * Get platform generator by name (alias for getGenerator) */ getPlatform(platform: SupportedPlatform): PlatformGenerator | undefined; /** * Get iOS platform generator with proper typing */ getIOSPlatform(): IOSPlatformGeneratorInterface | undefined; /** * Get Android platform generator with proper typing */ getAndroidPlatform(): AndroidPlatformGeneratorInterface | undefined; /** * Get all available platforms */ getAvailablePlatforms(): SupportedPlatform[]; /** * Generate bridge code for specific platform */ generateForPlatform(platform: SupportedPlatform, modules: ParsedModule[]): Promise<string[]>; /** * Generate bridge code for all available platforms */ generateForAllPlatforms(modules: ParsedModule[]): Promise<{ [platform: string]: string[]; }>; /** * Check if a platform is supported */ supports(platform: string): boolean; /** * Check if a platform is available */ isPlatformAvailable(platform: string): boolean; /** * Get platform generator by name */ getPlatformGenerator(platform: string): PlatformGenerator | undefined; } //#endregion //#region src/generator.d.ts declare class Generator { private config; private platformRegistry?; constructor(config: ComponentConfig, platformRegistry?: PlatformRegistry); /** * Main generation method - Generates .brick folder structure with package.json and NativeBrickModule.ts */ generateTypeScriptFiles(modules: ParsedModule[]): Promise<string[]>; /** * Generates package.json for .brick folder */ private generatePackageJson; /** * Generates TurboModule specification for React Native Codegen * This is the only file generated by brick-codegen */ private generateTurboModuleSpec; private getAllEvents; private capitalizeFirst; /** * Gets all methods from all modules */ private getAllMethods; /** * Gets all constants from all modules */ private getAllConstants; /** * Generates bridge code for all platforms using DI pattern */ generateBridgeCode(modules: ParsedModule[]): Promise<{ ios: string[]; android: string[]; allFiles: string[]; }>; /** * Main unified generation method - Generates all files including TypeScript specs and bridge code */ generateAll(modules: ParsedModule[]): Promise<string[]>; private log; private logGenerated; } //#endregion //#region src/utils/type-mapping.d.ts /** * Type mapping utilities for different platforms * Consolidates type conversion logic from signature-mapper.ts */ interface TypeMapping { typescript: string; swift: string; objectiveC: string; java: string; kotlin: string; } declare const TYPE_MAPPINGS: Record<string, TypeMapping>; type Platform = "swift" | "objectiveC" | "java" | "kotlin"; declare function mapTypeScriptType(tsType: string, platform: Platform): string; declare function generateMethodSignature(methodName: string, params: Array<{ name: string; type: string; }>, returnType: string, platform: Platform, isAsync?: boolean): string; //#endregion export { AndroidPlatformGenerator, AndroidPlatformGeneratorInterface, type BrickCodegenConfig, type ComponentConfig, Generator, IOSPlatformGenerator, IOSPlatformGeneratorInterface, Parser, Platform, PlatformGenerator, PlatformRegistry, Scanner, SupportedPlatform, TYPE_MAPPINGS, TypeMapping, generateMethodSignature, isAndroidPlatformGenerator, isIOSPlatformGenerator, mapTypeScriptType }; //# sourceMappingURL=index-BTt-qjT4.d.ts.map