|
| 1 | +# WebF CLI Development Guide |
| 2 | + |
| 3 | +## Overview |
| 4 | +The WebF CLI is a code generation tool that creates type-safe bindings between Flutter/Dart and JavaScript frameworks (React, Vue). It analyzes TypeScript definition files and generates corresponding Dart classes and JavaScript/TypeScript components. |
| 5 | + |
| 6 | +## Architecture |
| 7 | + |
| 8 | +### Core Components |
| 9 | +- `analyzer.ts` - TypeScript AST analysis with multi-level caching |
| 10 | +- `generator.ts` - Orchestrates code generation for Dart, React, and Vue |
| 11 | +- `dart.ts` - Dart code generation from TypeScript definitions |
| 12 | +- `react.ts` - React component generation |
| 13 | +- `vue.ts` - Vue component generation |
| 14 | +- `commands.ts` - CLI command implementations |
| 15 | +- `logger.ts` - Logging utility without external dependencies |
| 16 | + |
| 17 | +### Key Features |
| 18 | +- Multi-level caching for performance optimization |
| 19 | +- Parallel file processing |
| 20 | +- Type-safe attribute handling with automatic conversions |
| 21 | +- Comprehensive error handling and recovery |
| 22 | + |
| 23 | +## Code Generation Patterns |
| 24 | + |
| 25 | +### TypeScript to Dart Type Mapping |
| 26 | +```typescript |
| 27 | +// Boolean attributes are always non-nullable in Dart |
| 28 | +interface Props { |
| 29 | + open?: boolean; // Generates: bool get open; |
| 30 | + title?: string; // Generates: String? get title; |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +### Attribute Type Conversion |
| 35 | +HTML attributes are always strings, so the generator includes automatic type conversion: |
| 36 | +- Boolean: `value == 'true' || value == ''` |
| 37 | +- Integer: `int.tryParse(value) ?? 0` |
| 38 | +- Double: `double.tryParse(value) ?? 0.0` |
| 39 | +- String: Direct assignment |
| 40 | + |
| 41 | +## Performance Optimizations |
| 42 | + |
| 43 | +### Caching Strategy |
| 44 | +1. **Source File Cache**: Parsed TypeScript AST files are cached |
| 45 | +2. **Type Conversion Cache**: Frequently used type conversions are cached |
| 46 | +3. **File Content Cache**: File contents are cached to detect changes |
| 47 | + |
| 48 | +### Batch Processing |
| 49 | +Files are processed in batches for optimal parallelism: |
| 50 | +```typescript |
| 51 | +await processFilesInBatch(items, batchSize, processor); |
| 52 | +``` |
| 53 | + |
| 54 | +## Testing Guidelines |
| 55 | + |
| 56 | +### Test Structure |
| 57 | +- Unit tests for all core modules |
| 58 | +- Mock file system operations before module imports |
| 59 | +- Test coverage threshold: 70% |
| 60 | + |
| 61 | +### Running Tests |
| 62 | +```bash |
| 63 | +npm test # Run all tests |
| 64 | +npm test -- test/analyzer.test.ts # Run specific test |
| 65 | +npm run test:coverage # Run with coverage report |
| 66 | +``` |
| 67 | + |
| 68 | +### Mock Patterns |
| 69 | +For modules that read files at load time: |
| 70 | +```typescript |
| 71 | +jest.mock('fs'); |
| 72 | +import fs from 'fs'; |
| 73 | +const mockFs = fs as jest.Mocked<typeof fs>; |
| 74 | +mockFs.readFileSync = jest.fn().mockImplementation((path) => { |
| 75 | + // Return appropriate content |
| 76 | +}); |
| 77 | +// Now import the module |
| 78 | +import { moduleUnderTest } from './module'; |
| 79 | +``` |
| 80 | + |
| 81 | +## CLI Usage |
| 82 | + |
| 83 | +### Commands |
| 84 | +```bash |
| 85 | +# Generate code from TypeScript definitions (auto-creates project if needed) |
| 86 | +webf codegen <output-dir> --flutter-package-src=<path> [--framework=react|vue] [--package-name=<name>] [--publish-to-npm] [--npm-registry=<url>] |
| 87 | + |
| 88 | +# Create a new project without code generation |
| 89 | +webf codegen <output-dir> [--framework=react|vue] [--package-name=<name>] |
| 90 | + |
| 91 | +# Generate and publish to npm |
| 92 | +webf codegen <output-dir> --flutter-package-src=<path> --publish-to-npm |
| 93 | + |
| 94 | +# Generate and publish to custom registry |
| 95 | +webf codegen <output-dir> --flutter-package-src=<path> --publish-to-npm --npm-registry=https://custom.registry.com/ |
| 96 | +``` |
| 97 | + |
| 98 | +### Auto-creation Behavior |
| 99 | +The `generate` command now automatically detects if a project needs to be created: |
| 100 | +- If required files (package.json, global.d.ts, tsconfig.json) are missing, it will create a new project |
| 101 | +- If framework or package name are not provided, it will prompt interactively |
| 102 | +- If an existing project is detected, it will use the existing configuration |
| 103 | +- Framework can be auto-detected from existing package.json dependencies |
| 104 | + |
| 105 | +### Metadata Synchronization |
| 106 | +When creating typing projects, the CLI automatically synchronizes metadata from the Flutter package: |
| 107 | +- Reads `pubspec.yaml` from the Flutter package source directory |
| 108 | +- Extracts version and description information |
| 109 | +- Applies this metadata to the generated `package.json` files |
| 110 | +- Ensures typing packages match the same version as the Flutter package |
| 111 | + |
| 112 | +### Automatic Build |
| 113 | +After code generation, the CLI automatically runs `npm run build` if a build script is present in the package.json. This ensures the generated package is immediately ready for use or publishing. The build process: |
| 114 | +- Checks for the presence of a `build` script in package.json |
| 115 | +- Runs the build command if available |
| 116 | +- Continues successfully even if the build fails (with a warning) |
| 117 | +- Provides clear console output about the build status |
| 118 | + |
| 119 | +### NPM Publishing |
| 120 | +The CLI supports automatic npm publishing with the following features: |
| 121 | +- **--publish-to-npm**: Automatically publishes the generated package to npm (build is run automatically) |
| 122 | +- **--npm-registry**: Specify a custom npm registry URL (defaults to https://registry.npmjs.org/) |
| 123 | +- **Interactive publishing**: If not using the --publish-to-npm flag, the CLI will ask if you want to publish after generation |
| 124 | +- **Registry configuration**: When choosing to publish interactively, you can specify a custom registry URL |
| 125 | +- Checks if user is logged in before attempting to publish |
| 126 | +- Temporarily sets and resets registry configuration when custom registry is used |
| 127 | + |
| 128 | +Requirements for publishing: |
| 129 | +- Must be logged in to npm (`npm login`) |
| 130 | +- Package must have a valid package.json |
| 131 | +- Package will be built automatically before publishing (if build script exists) |
| 132 | + |
| 133 | +Publishing workflow: |
| 134 | +1. If `--publish-to-npm` is not specified, CLI prompts after successful generation |
| 135 | +2. If user chooses to publish, CLI asks for registry URL (optional) |
| 136 | +3. Validates npm login status |
| 137 | +4. Publishes to specified registry (no need to build separately) |
| 138 | + |
| 139 | +### Output Directory Behavior |
| 140 | +- Dart files are generated in the Flutter package source directory |
| 141 | +- React/Vue files are generated in the specified output directory |
| 142 | +- If no output directory is specified, a temporary directory is created |
| 143 | +- Temporary directories are created in the system temp folder with prefix `webf-typings-` |
| 144 | +- When using temporary directories, the path is displayed at the end of generation |
| 145 | +- Paths can be absolute or relative to current working directory |
| 146 | + |
| 147 | +### Generated Files Structure |
| 148 | +When running `dartGen`: |
| 149 | +- Dart binding files are generated with `_bindings_generated.dart` suffix |
| 150 | +- Original `.d.ts` files are copied to the output directory maintaining their structure |
| 151 | +- Directory structure from source is preserved in the output |
| 152 | + |
| 153 | +## Development Workflow |
| 154 | + |
| 155 | +### Adding New Features |
| 156 | +1. Update TypeScript interfaces/types |
| 157 | +2. Implement feature with tests |
| 158 | +3. Update templates if needed |
| 159 | +4. Ensure all tests pass |
| 160 | +5. Update this documentation |
| 161 | + |
| 162 | +### Debugging |
| 163 | +Use the logger for debugging: |
| 164 | +```typescript |
| 165 | +import { debug, info, warn, error } from './logger'; |
| 166 | +debug('Processing file:', filename); |
| 167 | +``` |
| 168 | + |
| 169 | +### Template Modification |
| 170 | +Templates are in `/templates/*.tpl`. When modifying: |
| 171 | +1. Update the template file |
| 172 | +2. Update the corresponding generator function |
| 173 | +3. Ensure generated code follows style guidelines |
| 174 | + |
| 175 | +## Common Issues and Solutions |
| 176 | + |
| 177 | +### Issue: Boolean attributes treated as strings |
| 178 | +**Solution**: Use `generateAttributeSetter` which handles type conversion |
| 179 | + |
| 180 | +### Issue: Null type handling |
| 181 | +**Solution**: Check for literal types containing null: |
| 182 | +```typescript |
| 183 | +if (type.kind === ts.SyntaxKind.LiteralType) { |
| 184 | + const literalType = type as ts.LiteralTypeNode; |
| 185 | + if (literalType.literal.kind === ts.SyntaxKind.NullKeyword) { |
| 186 | + return FunctionArgumentType.null; |
| 187 | + } |
| 188 | +} |
| 189 | +``` |
| 190 | + |
| 191 | +### Issue: File changes not detected |
| 192 | +**Solution**: Clear caches before generation: |
| 193 | +```typescript |
| 194 | +clearCaches(); |
| 195 | +``` |
| 196 | + |
| 197 | +## Code Style |
| 198 | +- Use async/await for asynchronous operations |
| 199 | +- Implement proper error handling with try-catch |
| 200 | +- Add descriptive error messages |
| 201 | +- Use TypeScript strict mode |
| 202 | +- Follow existing patterns in the codebase |
0 commit comments