Compare commits

..

78 Commits

Author SHA1 Message Date
Sergey Penkovsky
e47adbb7fd style(cherrypick_generator): format generator files 2026-03-24 10:30:06 +03:00
Sergey Penkovsky
b7979d653e refactor(cherrypick_generator): migrate inject codegen to code_builder 2026-03-02 12:47:02 +03:00
Sergey Penkovsky
3c550db8cd Add OpenSpec system specification 2026-02-27 14:33:30 +03:00
Sergey Penkovsky
e6b3017384 chore(release): publish packages
- cherrypick_annotations@4.0.0-dev.0
 - cherrypick_generator@4.0.0-dev.0
2026-01-29 23:18:12 +03:00
Sergey Penkovsky
3b2df58e9a feat!: update Dart SDK minimum versions
BREAKING CHANGE: Minimum Dart SDK version updated
- cherrypick_annotations: 3.8.0 -> 3.9.0
- cherrypick_generator: requires Dart 3.9.0+

This change may require users to update their Dart SDK.
2026-01-29 23:17:58 +03:00
Sergey Penkovsky
f9100eb9ba style: remove unnecessary 'this.' qualifiers in binding.dart
- Remove unnecessary 'this.' qualifiers from deprecated methods
- Fix linter warnings (unnecessary_this)
2026-01-29 23:04:22 +03:00
Sergey Penkovsky
94b3ba284a chore: update Flutter to 3.38.1 and bump Dart SDK versions
- Update Flutter version from 3.32.0 to 3.38.1 in .fvmrc
- Bump Dart SDK minimum version in pubspec.yaml files:
  - Root: 3.2.0 -> 3.8.0
  - cherrypick_annotations: 3.8.0 -> 3.9.0
  - cherrypick/example: 2.12.0 -> 3.2.0
  - examples/postly: 3.8.0 -> 3.9.0
- Apply code formatting fixes in cherrypick_generator
- Update dependencies in pubspec.lock files
2026-01-29 23:02:37 +03:00
Sergey Penkovsky
0651f74472 chore(release): publish packages
- cherrypick_annotations@3.0.2
 - cherrypick_generator@3.0.2
2026-01-29 16:58:46 +03:00
Sergey Penkovsky
776f29945a chore: format code and update deps 2026-01-29 16:57:28 +03:00
Sergey Penkovsky
49361f2f9e Merge pull request #27 from pese-git/develop
Develop
2026-01-29 16:41:03 +03:00
Sergey Penkovsky
4953e917c9 Merge branch 'master' into develop 2026-01-15 09:00:10 +03:00
Sergey Penkovsky
1997110d92 chore(release): publish packages
- cherrypick@3.0.2
 - cherrypick_flutter@3.0.2
 - talker_cherrypick_logger@3.0.2
2025-10-20 17:31:40 +03:00
Sergey Penkovsky
0e600ca3a2 Merge pull request #25 from pese-git/issues/24
Issues/24
2025-10-20 17:28:01 +03:00
Sergey Penkovsky
25ae208ea1 fix(test): fix warning 2025-10-20 16:20:20 +03:00
Sergey Penkovsky
685c0ae49c fix(scope): properly clear binding and module references on dispose
Add memory leak/finalizer test to ensure no strong references remain after closing and disposing a scope.
2025-10-13 17:32:10 +03:00
Sergey Penkovsky
98d81b13a8 freeze deps 2025-10-13 17:26:39 +03:00
Sergey Penkovsky
cccf460f01 chore(release): publish packages
- cherrypick_annotations@3.0.2-dev.0
 - cherrypick_generator@3.0.2-dev.0
2025-09-09 18:15:03 +03:00
Sergey Penkovsky
0c1ef70b73 feat(examples): update client_app and postly implementation details
- Refactored and updated pages, router, DI modules, and feature implementations in both example projects:
  - client_app: main.dart and my_home_page.dart updated for improved navigation and structure.
  - postly: updated DI wiring, presentation pages, repository implementation, and routing logic.
- Applied small improvements and code consistency changes in the examples.

docs: add new documentation assets and benchmarking script

BREAKING CHANGE:
Examples now reflect the latest changes in the DI framework and are ready for Dart 3.8+ and cherrypick_generator element2 API compatibility.
2025-09-09 18:08:39 +03:00
Sergey Penkovsky
eb6d786600 refactor(generator): migrate cherrypick_generator to analyzer element2 API
- Fully migrated core cherrypick_generator and submodules to new analyzer element2 system:
  - Updated all GeneratorForAnnotation overrides to use Element2, ClassElement2, MethodElement2, FieldElement2 and new annotation/metadata access patterns.
  - Migrated signature and bodies for helpers, parsers, annotation validators, meta utils, and type parsers.
  - Fixed tests to use readerWriter instead of deprecated reader argument.
  - Refactored usage of now-absent 'metadata', 'parameters', 'fields', 'methods', 'source', and similar members to use correct *.firstFragment.* or API alternatives.
  - Cleaned up old imports and unused code.

test(generator): update generator integration tests

- Updated test calls to use correct TestReaderWriter type and bring test infra in line with current build_runner/testing API.

build: update dependencies and pubspec to support latest analyzer/build ecosystem

- Raised Dart SDK and package constraints as required for generated code and codegen plugins.
- Updated pubspecs in root/examples as needed by build warnings.

docs: add plots and assets (new files)

BREAKING CHANGE:
- Requires Dart 3.8+ and analyzer that supports element2.
- All downstream codegen/tests depending on Element API must migrate to Element2 signatures and data model.
2025-09-09 18:08:39 +03:00
Sergey Penkovsky
c483d8c9e2 chore(release): publish packages
- cherrypick@3.0.1
 - cherrypick_annotations@3.0.1
 - cherrypick_flutter@3.0.1
 - cherrypick_generator@3.0.1
 - talker_cherrypick_logger@3.0.1
2025-09-09 13:47:11 +03:00
Sergey Penkovsky
a74cec645e Merge pull request #23 from pese-git/develop
Modified Files Summary

Configuration Files
- `.fvmrc` - FVM configuration
- `melos.yaml` - Melos workspace configuration
- Multiple `pubspec.yaml` files across packages

Documentation
- `README.md` (root and all packages) - Added Netlify badges
- Standardized CI/CD badge formatting

Dependency Management
- `pubspec.lock` files in example projects
- Dependency version adjustments

Code Quality
- `cherrypick_generator/analysis_options.yaml` - Updated analysis rules

Change Categories

📚 Documentation Improvements
- Added Netlify deployment status badges
- Enhanced project visibility
- Standardized badge formatting

⚙️ Maintenance Updates
- Development dependency version adjustments
- Environment constraint updates
- Improved cross-version compatibility

🛠️ Configuration Changes
- FVM configuration updates
- Melos workspace adjustments
- Analysis rules refinement

Impact Assessment

  Non-Breaking Changes
All modifications are backward compatible and include:
- Documentation enhancements
- Development environment improvements
- Dependency version updates
- Configuration refinements

🚀 Ready for Merge
The `develop` branch contains maintenance improvements that are:
-  Tested and stable
-  Non-breaking
-  Documentation-focused
-  Environment compatibility improvements
2025-09-09 13:46:23 +03:00
Sergey Penkovsky
082b5a6fb6 docs: add Netlify deployment status badge to README files
- Added Netlify deployment status badge to all package README files
- Standardized CI/CD badge formatting across the project
- Improves visibility of deployment status for documentation and examples
- Maintains consistent badge styling with existing Melos + FVM CI badge
2025-09-09 13:22:39 +03:00
Sergey Penkovsky
6c1ba523c6 chore(deps): adjust dev dependencies versions for broad compatibility
- Downgraded lints and test dependencies in multiple packages to ensure consistent analyzer and test ecosystem for Dart 3.2+.
- cherrypick_generator: Bump analyzer to ^7.7.1 and mockito to ^5.4.5 for patch updates and compatibility.
- cherrypick_flutter: Lowered flutter_lints and test to versions compatible with current stable toolchain.
- talker_cherrypick_logger: Lowered lints and test for alignment with mono-repo versions.
- melos.yaml: Added clean_all script for removing generated files and build artifacts repo-wide.

No functional code changes, only dependency and tooling improvements.
2025-09-09 12:45:12 +03:00
Sergey Penkovsky
651b2a26d6 chore(env): update Flutter and SDK constraints for compatibility
- Downgraded Flutter version in .fvmrc from 3.29.3 to 3.27.0 for compatibility with current dependencies
- Raised Dart SDK constraint in benchmark_di/pubspec.yaml from >=3.0.0 <4.0.0 to >=3.2.0 <4.0.0 to align with required package minimums

This change ensures environment compatibility for dependency resolution and build tools. No functional code changes.
2025-09-09 08:53:50 +03:00
Sergey Penkovsky
ec6e9aefd3 add banner 2025-09-09 00:47:00 +03:00
Sergey Penkovsky
751cb08064 Update approach descriptions in release notes
- Enhanced description of development approaches in both Russian and English versions
- Clarified distinction between programmatic (imperative) and declarative approaches
- Improved terminology consistency across both language versions
2025-09-09 00:46:09 +03:00
Sergey Penkovsky
b2fbce74b3 Code formatting fixes and dependency updates
- Fixed code formatting in benchmark_di CLI and adapter files
- Updated pubspec.lock files for benchmark_di, client_app, and postly examples
- Minor formatting improvements in disposable example
2025-09-08 17:22:49 +03:00
Sergey Penkovsky
81f14f5231 chore(release): publish packages
- cherrypick@3.0.0
 - cherrypick_annotations@3.0.0
 - cherrypick_flutter@3.0.0
 - cherrypick_generator@3.0.0
 - talker_cherrypick_logger@3.0.0
2025-09-08 17:17:50 +03:00
Sergey Penkovsky
a9101513e1 Add CI/CD badges to package README files
- Added Melos + FVM CI badges to all package README.md files
- Standardized badge formatting across all packages
- Improved project visibility with build status indicators
2025-09-08 17:16:51 +03:00
Sergey Penkovsky
f1cf1d054f Merge pull request #22 from pese-git/develop
# Release - CherryPick 3.x

> **CherryPick** — a lightweight and modular DI framework for Dart and Flutter that solves dependency injection through strong typing, code generation, and dependency control.

Version **3.x** was recently released with significant improvements.

## Main Changes in 3.x

* **O(1) dependency resolution** — thanks to Map indexing of bindings, performance does not depend on the size of the scope in the DI graph. This provides noticeable speedup in large projects.
* **Protection against circular dependencies** — checking works both within a single scope and across the entire hierarchy. When a cycle is detected, an informative exception with the dependency chain is thrown.
* **Integration with Talker** — all DI events (registration, creation, deletion, errors) are logged and can be displayed in the console or UI.
* **Automatic resource cleanup** — objects implementing `Disposable` are properly released when the scope is closed.
* **Stabilized declarative approach support** — annotations and code generation now work more reliably and are more convenient for use in projects.

## Resource Cleanup Example

```dart
class MyServiceWithSocket implements Disposable {
  @override
  Future<void> dispose() async {
    await socket.close();
    print('Socket closed!');
  }
}

class AppModule extends Module {
  @override
  void builder(Scope currentScope) {
    // singleton Api
    bind<MyServiceWithSocket>()
      .toProvide(() => MyServiceWithSocket())
      .singleton();
  }
}

scope.installModules([AppModule()]);

await CherryPick.closeRootScope(); // will wait for async dispose to complete
```

## Circular Dependency Checking

One of the new features in CherryPick 3.x is built-in cycle protection.
This helps catch situations early where services start depending on each other recursively.

### How to Enable Checking

For checking within a single scope:

```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```

For global checking across the entire hierarchy:

```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```

### How a Cycle Can Occur

Suppose we have two services that depend on each other:

```dart
class UserService {
  final OrderService orderService;
  UserService(this.orderService);
}

class OrderService {
  final UserService userService;
  OrderService(this.userService);
}
```

If we register them in the same scope:

```dart
class AppModule extends Module {
  @override
  void builder(Scope currentScope) {
    bind<UserService>().toProvide(() => UserService(scope.resolve()));
    bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
  }
}

final scope = CherryPick.openRootScope()
  ..enableCycleDetection()
  ..installModules([AppModule()]);

scope.resolve<UserService>();
```

Then when trying to resolve the dependency, an exception will be thrown:

```bash
 Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```

This way, the error is detected immediately, not "somewhere in runtime".

## Integration with Talker

CherryPick 3.x allows logging all DI events through [Talker](https://pub.dev/packages/talker): registration, object creation, deletion, and errors. This is convenient for debugging and diagnosing the dependency graph.

Connection example:

```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```

After this, DI events will be displayed in the console or UI:

```bash
┌───────────────────────────────────────────────────────────────
│ [info]    9:41:33  | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
│ [verbose] 9:41:33  | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```

In the log, you can see when scopes are created, which objects are registered and deleted, and catch errors and cycles in real time.


## Declarative Approach with Annotations

In addition to fully programmatic module descriptions, CherryPick supports **declarative DI style through annotations**.  
This allows minimizing manual code and automatically generating modules and mixins for automatic dependency injection.

Example of a declarative module:

```dart
@module()
abstract class AppModule extends Module {
  @provide()
  @singleton()
  Api api() => Api();

  @provide()
  Repo repo(Api api) => Repo(api);
}
````

After code generation, you can automatically inject dependencies into widgets or services:

```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
  @inject()
  late final Repo repo;

  MyScreen() {
    _inject(this);
  }
}
```

This way you can choose a convenient style: either **purely programmatic** or **declarative with annotations**.


## Who Might Find CherryPick Useful?

* Projects where it's important to guarantee **no cycles in the dependency graph**;
* Teams that want to **minimize manual DI code** and use a declarative style with annotations;
* Applications that require **automatic resource cleanup** (sockets, controllers, streams).

## Useful Links

* 📦 Package: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Code: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Documentation: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)
2025-09-08 17:04:48 +03:00
Sergey Penkovsky
f1ad1c42b5 Add ignore comment for deprecated member warning in binding.dart
- Added // ignore: deprecated_member_use_from_same_package comment
- This suppresses the warning about deprecated toProvideAsync method
- The comment is needed to maintain code quality while keeping backward compatibility
2025-09-08 16:50:45 +03:00
Sergey Penkovsky
be7f3e0392 Add release notes for CherryPick 3.x in both Russian and English
- Added comprehensive release notes for CherryPick 3.x
- Includes new features: O(1) dependency resolution, circular dependency protection
- Added Talker integration and automatic resource cleanup examples
- Added declarative approach with annotations section
- Both Russian and English versions included
2025-09-08 16:48:12 +03:00
Sergey Penkovsky
1b0615810d add presentation 2025-09-08 15:48:58 +03:00
Sergey Penkovsky
ef04f464da Update README.md 2025-09-08 15:40:09 +03:00
Sergey Penkovsky
6826f0f62c chore: synchronize package versions to 3.0.0-dev.X across all packages
- Unified MAJOR.MINOR versioning across all cherrypick ecosystem packages
- Updated cherrypick_annotations from 1.1.2-dev.2 to 3.0.0-dev.0
- Updated cherrypick_generator from 2.0.0-dev.2 to 3.0.0-dev.0
- Updated cherrypick_flutter from 1.1.3-dev.12 to 3.0.0-dev.1
- Updated documentation URLs from .dev to .netlify.app domain
- Maintained semantic versioning consistency for mono-repository management

This change ensures:
- Clear compatibility signaling between interdependent packages
- Simplified dependency management for consumers
- Consistent release versioning across the ecosystem
2025-09-08 15:06:19 +03:00
Sergey Penkovsky
9e517d047f chore(release): publish packages
- cherrypick@3.0.0-dev.13
 - cherrypick_flutter@3.0.0-dev.1
 - talker_cherrypick_logger@3.0.0-dev.1
2025-09-08 14:58:37 +03:00
Sergey Penkovsky
68a16aaa0c chore(release): publish packages
- talker_cherrypick_logger@3.0.0-dev.0
2025-09-08 14:57:29 +03:00
Sergey Penkovsky
679b2b87b7 chore(release): publish packages
- cherrypick_flutter@3.0.0-dev.0
2025-09-08 14:56:44 +03:00
Sergey Penkovsky
dbdae94673 chore(release): publish packages
- cherrypick_generator@3.0.0-dev.0
2025-09-08 14:55:04 +03:00
Sergey Penkovsky
4220967447 chore(release): publish packages
- cherrypick_annotations@3.0.0-dev.0
2025-09-08 14:53:10 +03:00
Sergey Penkovsky
dfe16fb10f chore: add yarn.lock file to track exact dependency versions 2025-09-08 14:42:46 +03:00
Sergey Penkovsky
ce2e770cbe docs: add important warnings about toInstance limitations and singleton behavior with params
- Add detailed warning about toInstance usage restrictions in module builders
- Explain singleton behavior with parameterized providers
- Clarify singleton() usage with toInstance() calls
- Update both English and Russian documentation versions
2025-09-08 14:07:48 +03:00
Sergey Penkovsky
7f5f5c4064 Merge pull request #21 from pese-git/website
Implement Website
2025-09-08 13:09:46 +03:00
Sergey Penkovsky
04ecb6d3a6 docs: update contributors list with GitHub links and add new contributor 2025-09-08 10:50:42 +03:00
Sergey Penkovsky
484061148d docs(binding,docs): clarify .singleton() with .toInstance() behavior in docs and API
- Add an explicit note and warning about the effect (or lack thereof) of calling `.singleton()` after `.toInstance()`:
  - in singleton() API doc-comment in binding.dart,
  - in README.md (after all binding usage patterns),
  - in full_tutorial_en.md and full_tutorial_ru.md.
- Explain that `.singleton()` has no effect on objects registered with `.toInstance()` — they are always single instance.
- Recommend `.singleton()` only for providers (toProvide/toProvideAsync), not direct instances.
- Improves clarity and prevents misuse/confusion for end users and future maintainers.
2025-09-08 10:46:20 +03:00
Sergey Penkovsky
b5b672765e docs(binding,docs): explain .singleton() + parametric provider behavior
- Add an explicit warning and usage examples for .singleton() combined with toProvideWithParams/toProvideAsyncWithParams:
  - in API doc-comment for singleton() in binding.dart,
  - in README.md and both full tutorials (EN/RU).
- Show correct and incorrect usage/pitfalls for parameterized providers and singleton.
- Help users avoid unintended singleton caching when using providers with parameters.
- Motivation: Prevent common confusion, make advanced DI scenarios safer and more obvious.
2025-09-08 10:18:19 +03:00
Sergey Penkovsky
482b7b0f5f docs(binding): clarify registration limitation in API doc
- Add an explicit warning and usage pattern examples to the toInstance() method doc-comment.
- Explain why resolving dependencies registered with toInstance inside the same Module.builder does not work.
- Reference safe and unsafe code samples for users navigating via IDE and API documentation.
2025-09-08 09:51:40 +03:00
Sergey Penkovsky
722a4d7980 docs(di): clarify 'toInstance' binding limitations in builder
- Add explicit note for users about the impossibility to use scope.resolve<T>() for just-to-be-registered types inside Module.builder when registering chained dependencies via toInstance.
- Show correct and incorrect usage patterns, functional and anti-pattern Dart examples in RU and EN full tutorials.
- Add the warning to the main README after core concept bindings block, improving discoverability for users starting with the library.
- Motivation: Prevent common misuse and hard-to-debug runtime errors for users who construct chains using toInstance/resolve inside the builder.
2025-09-08 09:23:00 +03:00
Sergey Penkovsky
16cd7199aa fix: fix examples 2025-09-05 09:37:24 +03:00
Sergey Penkovsky
1cbcce5b38 chore(release): publish packages
- cherrypick_annotations@1.1.2-dev.2
 - cherrypick_generator@2.0.0-dev.2
2025-08-22 14:39:33 +03:00
Sergey Penkovsky
264c4bbb88 docs(annotations): improve API documentation and usage example
- Add detailed English doc comments for all main annotations (inject, injectable, instance, provide, scope, etc)
- Add fully documented example/example.dart illustrating real-world DI scenario
- Clarify stub sections (Module class, generated mixins)
- Aligns package with pub.dev quality and best practice requirements

No breaking changes.
2025-08-22 09:39:25 +03:00
Sergey Penkovsky
cbb5dcc3a0 docs(benchmark_di): update reports with extended analysis, peak memory and revised recommendations 2025-08-20 08:50:14 +03:00
Sergey Penkovsky
d281c18a75 feat(benchmark_di): add yx_scope DI adapter and CLI integration 2025-08-20 07:49:10 +03:00
Sergey Penkovsky
8ef12e990f chore(release): publish packages
- cherrypick@3.0.0-dev.12
 - cherrypick_flutter@1.1.3-dev.12
 - talker_cherrypick_logger@1.1.0-dev.7
2025-08-19 10:48:20 +03:00
Sergey Penkovsky
5c57370755 fix(benchmark) - hide warning 2025-08-19 10:47:53 +03:00
Sergey Penkovsky
8711dc83d0 docs(benchmark_di): update benchmark results and add test parameters for all DI in REPORT.md/RU.md 2025-08-19 10:29:53 +03:00
Sergey Penkovsky
043737e2c9 fix(scope): prevent concurrent modification in dispose()
- Create defensive copies of _scopeMap and _disposables
- Remove redundant try-catch blocks
- Improve memory safety during teardown
2025-08-19 09:57:02 +03:00
Sergey Penkovsky
ed65e3c23d fix(benchmark): improve CherryPickAdapter teardown reliability
- Add error handling for scope disposal
- Add null check for _scope variable
- Prevent concurrent modification exceptions
2025-08-19 09:22:45 +03:00
Sergey Penkovsky
a897c1b31b feat(benchmark_di): add Kiwi DI adapter and CLI integration 2025-08-18 18:40:07 +03:00
Sergey Penkovsky
dd9c3faa62 fix(binding): fix unterminated string literal and syntax issues in binding.dart 2025-08-18 18:35:41 +03:00
Sergey Penkovsky
846d55b124 feat(i18n): localize main page and enable i18n for homepage texts
- Updated index.tsx to use <Translate> and translate() for all main texts (title, subtitle, CTA, description) — now fully i18n-ready.
- Added new translation files (code.json, navbar.json, footer.json, etc.) to support Russian language for homepage and UI.
- Enables seamless language switching and correct translations of homepage elements.
2025-08-15 15:09:55 +03:00
Sergey Penkovsky
4f91d442af feat(i18n): localize FeatureList on homepage with <Translate> component
- Updated HomepageFeatures/index.tsx to use Docusaurus <Translate> component and unique ids for each feature title and description.
- Enables full i18n support for FeatureList (English & Russian).
- All feature texts are now ready for integration with Docusaurus translation workflow.
2025-08-15 14:40:33 +03:00
Sergey Penkovsky
d0c3870af6 feat(i18n): add Russian translation for docs intro page
- Added the initial Russian localizable version for the documentation introduction section ().
- Makes the first step of the CherryPick documentation available to Russian-speaking users.
- Ensures the /ru/docs/intro route is available and translated.
2025-08-15 10:10:37 +03:00
Sergey Penkovsky
c8292035b6 chore(docs): update editUrl for docs to project repository
- Changed docs.editUrl in docusaurus.config.ts to point to the actual GitHub repository (https://github.com/pese-git/cherrypick/tree/website/website).
- Allows users to edit documentation directly in this project's repo via the 'Edit this page' links.
2025-08-15 09:28:37 +03:00
Sergey Penkovsky
63ee3a9966 chore(config): remove blog preset block from docusaurus.config.ts
- Deleted all blog-related configuration from docusaurus.config.ts
- Intended for disabling or cleaning up unused blog features
2025-08-15 09:24:46 +03:00
Sergey Penkovsky
a4c5fd922e chore(release): publish packages
- cherrypick@3.0.0-dev.10
 - cherrypick_annotations@1.1.2-dev.1
 - cherrypick_flutter@1.1.3-dev.10
 - cherrypick_generator@2.0.0-dev.1
 - talker_cherrypick_logger@1.1.0-dev.5
2025-08-15 09:06:46 +03:00
Sergey Penkovsky
8870b8ce54 docs(pub): update homepage and documentation URLs in pubspec.yaml to new official site 2025-08-15 09:04:39 +03:00
Sergey Penkovsky
1f7e1d120d fix: update logo icon 2025-08-15 08:58:08 +03:00
Sergey Penkovsky
bcc5278c83 Fix Netlify SPA routing 2025-08-14 17:34:18 +03:00
Sergey Penkovsky
8863b10cbe feat: update dns 2025-08-14 16:57:25 +03:00
Sergey Penkovsky
e0a5ae66f6 fix(docs): comment out all broken links to allow successful Docusaurus build
- Commented out references to non-existent files and examples in both English and Russian documentation:
  - circular-dependency-detection.md
  - logging.md
  - documentation-links.md
  - using-annotations.md
- This fix prevents build failures caused by unresolved links in Docusaurus for both locales.
- All offending links are now non-blocking comments, allowing the site to build and deploy successfully until the related pages are added.
2025-08-14 16:24:57 +03:00
Sergey Penkovsky
9fee26c524 feat(i18n): add initial Russian localization for documentation and site config
- Added full Russian translations for all main documentation sections () into .
- Sections translated include: key features, installation, getting started, all core concepts, advanced features, API reference, FAQ, links, additional modules, contributing, and license.
- Updated  to ensure language switching is available and Russian locale is active.
- Each Russian file preserves the structure and formatting of the original Markdown, with machine-aided draft translation for immediate use.
- Lays the groundwork for UI language switching (en/ru) and enables further manual translation refinement and review.
2025-08-14 15:46:53 +03:00
Sergey Penkovsky
248bf4c8c5 feat(website): update home page to showcase CherryPick DI documentation
- Replaced the main action button text with 'Explore CherryPick Documentation 🍒' instead of 'Docusaurus Tutorial'.
- Updated the button link to target /docs/intro (main docs entry point).
- Changed <Layout> props:
  - Page title now uses project title only (siteConfig.title)
  - Added a CherryPick-related site description for better SEO and context.
- The homepage is now tailored to reflect CherryPick's purpose as a Dart & Flutter DI library instead of Docusaurus boilerplate.
2025-08-14 13:41:54 +03:00
Sergey Penkovsky
f4c4fe49a0 init: docusaurus website project 2025-08-13 18:19:25 +03:00
Sergey Penkovsky
298cb65ac8 chore(release): publish packages
- talker_cherrypick_logger@1.1.0-dev.4
2025-08-13 15:58:08 +03:00
Sergey Penkovsky
1b9db31c13 docs(readme): update install instructions to use pub.dev as default method and remove obsolete git example
The main installation guide now recommends pub.dev with ^latest tags. Removed the outdated GitHub install block for clarity and simplicity. No functional code changes.
2025-08-13 15:57:28 +03:00
Sergey Penkovsky
ca3cd2c8fd Merge pull request #20 from pese-git/code-format
style: reformat codebase using melos format
2025-08-13 15:46:05 +03:00
Sergey Penkovsky
c91e15319b style: reformat codebase using melos format
Applied consistent code formatting across all packages using \$ melos format
  └> dart format .
     └> RUNNING (in 8 packages)

--------------------------------------------------------------------------------
benchmark_di:
Formatted 18 files (0 changed) in 0.30 seconds.
benchmark_di: SUCCESS
--------------------------------------------------------------------------------
cherrypick:
Formatted 24 files (0 changed) in 0.34 seconds.
cherrypick: SUCCESS
--------------------------------------------------------------------------------
cherrypick_annotations:
Formatted 11 files (0 changed) in 0.14 seconds.
cherrypick_annotations: SUCCESS
--------------------------------------------------------------------------------
cherrypick_flutter:
Formatted 3 files (0 changed) in 0.15 seconds.
cherrypick_flutter: SUCCESS
--------------------------------------------------------------------------------
cherrypick_generator:
Formatted 17 files (0 changed) in 0.27 seconds.
cherrypick_generator: SUCCESS
--------------------------------------------------------------------------------
client_app:
Formatted 4 files (0 changed) in 0.14 seconds.
client_app: SUCCESS
--------------------------------------------------------------------------------
postly:
Formatted lib/router/app_router.gr.dart
Formatted 23 files (1 changed) in 0.33 seconds.
postly: SUCCESS
--------------------------------------------------------------------------------
talker_cherrypick_logger:
Formatted 4 files (0 changed) in 0.18 seconds.
talker_cherrypick_logger: SUCCESS
--------------------------------------------------------------------------------

$ melos format
  └> dart format .
     └> SUCCESS. No functional or logic changes included.
2025-08-13 15:38:44 +03:00
197 changed files with 34697 additions and 1609 deletions

2
.fvmrc
View File

@@ -1,3 +1,3 @@
{ {
"flutter": "3.29.3" "flutter": "3.38.1"
} }

149
.github/prompts/opsx-apply.prompt.md vendored Normal file
View File

@@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

154
.github/prompts/opsx-archive.prompt.md vendored Normal file
View File

@@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

170
.github/prompts/opsx-explore.prompt.md vendored Normal file
View File

@@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

103
.github/prompts/opsx-propose.prompt.md vendored Normal file
View File

@@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

288
.github/skills/openspec-explore/SKILL.md vendored Normal file
View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

110
.github/skills/openspec-propose/SKILL.md vendored Normal file
View File

@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -3,6 +3,489 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2026-01-29
### Changes
---
Packages with breaking changes:
- [`cherrypick_annotations` - `v4.0.0-dev.0`](#cherrypick_annotations---v400-dev0)
- [`cherrypick_generator` - `v4.0.0-dev.0`](#cherrypick_generator---v400-dev0)
Packages with other changes:
- There are no other changes in this release.
---
#### `cherrypick_annotations` - `v4.0.0-dev.0`
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
#### `cherrypick_generator` - `v4.0.0-dev.0`
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
## 2026-01-29
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v3.0.3`](#cherrypick_annotations---v303)
- [`cherrypick_generator` - `v3.0.3`](#cherrypick_generator---v303)
---
#### `cherrypick_annotations` - `v3.0.3`
#### `cherrypick_generator` - `v3.0.3`
## 2026-01-29
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v3.0.2`](#cherrypick_annotations---v302)
- [`cherrypick_generator` - `v3.0.2`](#cherrypick_generator---v302)
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
- `cherrypick_annotations` - `v3.0.2`
- `cherrypick_generator` - `v3.0.2`
---
#### `cherrypick_annotations` - `v3.0.2`
#### `cherrypick_generator` - `v3.0.2`
## 2025-10-20
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.2`](#cherrypick---v302)
- [`cherrypick_flutter` - `v3.0.2`](#cherrypick_flutter---v302)
- [`talker_cherrypick_logger` - `v3.0.2`](#talker_cherrypick_logger---v302)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v3.0.2`
- `talker_cherrypick_logger` - `v3.0.2`
---
#### `cherrypick` - `v3.0.2`
- **FIX**(test): fix warning.
- **FIX**(scope): properly clear binding and module references on dispose.
## 2025-09-09
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v3.0.2-dev.0`](#cherrypick_annotations---v302-dev0)
- [`cherrypick_generator` - `v3.0.2-dev.0`](#cherrypick_generator---v302-dev0)
---
#### `cherrypick_annotations` - `v3.0.2-dev.0`
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
#### `cherrypick_generator` - `v3.0.2-dev.0`
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
## 2025-09-09
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.1`](#cherrypick---v301)
- [`cherrypick_annotations` - `v3.0.1`](#cherrypick_annotations---v301)
- [`cherrypick_flutter` - `v3.0.1`](#cherrypick_flutter---v301)
- [`cherrypick_generator` - `v3.0.1`](#cherrypick_generator---v301)
- [`talker_cherrypick_logger` - `v3.0.1`](#talker_cherrypick_logger---v301)
---
#### `cherrypick` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_annotations` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_flutter` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_generator` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `talker_cherrypick_logger` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
## 2025-09-08
### Changes
---
Packages with breaking changes:
- [`cherrypick` - `v3.0.0`](#cherrypick---v300)
- [`cherrypick_annotations` - `v3.0.0`](#cherrypick_annotations---v300)
- [`cherrypick_flutter` - `v3.0.0`](#cherrypick_flutter---v300)
- [`cherrypick_generator` - `v3.0.0`](#cherrypick_generator---v300)
- [`talker_cherrypick_logger` - `v3.0.0`](#talker_cherrypick_logger---v300)
Packages with other changes:
- There are no other changes in this release.
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
- `cherrypick` - `v3.0.0`
- `cherrypick_annotations` - `v3.0.0`
- `cherrypick_flutter` - `v3.0.0`
- `cherrypick_generator` - `v3.0.0`
- `talker_cherrypick_logger` - `v3.0.0`
---
#### `cherrypick` - `v3.0.0`
#### `cherrypick_annotations` - `v3.0.0`
#### `cherrypick_flutter` - `v3.0.0`
#### `cherrypick_generator` - `v3.0.0`
#### `talker_cherrypick_logger` - `v3.0.0`
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.0-dev.13`](#cherrypick---v300-dev13)
- [`cherrypick_flutter` - `v3.0.0-dev.1`](#cherrypick_flutter---v300-dev1)
- [`talker_cherrypick_logger` - `v3.0.0-dev.1`](#talker_cherrypick_logger---v300-dev1)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v3.0.0-dev.1`
- `talker_cherrypick_logger` - `v3.0.0-dev.1`
---
#### `cherrypick` - `v3.0.0-dev.13`
- **FIX**: fix examples.
- **DOCS**: update contributors list with GitHub links and add new contributor.
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
- **DOCS**(binding): clarify registration limitation in API doc.
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`talker_cherrypick_logger` - `v3.0.0-dev.0`](#talker_cherrypick_logger---v300-dev0)
---
#### `talker_cherrypick_logger` - `v3.0.0-dev.0`
- chore(talker_cherrypick_logger): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_flutter` - `v3.0.0-dev.0`](#cherrypick_flutter---v300-dev0)
---
#### `cherrypick_flutter` - `v3.0.0-dev.0`
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_generator` - `v3.0.0-dev.0`](#cherrypick_generator---v300-dev0)
---
#### `cherrypick_generator` - `v3.0.0-dev.0`
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v3.0.0-dev.0`](#cherrypick_annotations---v300-dev0)
---
#### `cherrypick_annotations` - `v3.0.0-dev.0`
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
## 2025-08-22
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v1.1.2-dev.2`](#cherrypick_annotations---v112-dev2)
- [`cherrypick_generator` - `v2.0.0-dev.2`](#cherrypick_generator---v200-dev2)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_generator` - `v2.0.0-dev.2`
---
#### `cherrypick_annotations` - `v1.1.2-dev.2`
- **DOCS**(annotations): improve API documentation and usage example.
## 2025-08-19
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.0-dev.12`](#cherrypick---v300-dev12)
- [`cherrypick_flutter` - `v1.1.3-dev.12`](#cherrypick_flutter---v113-dev12)
- [`talker_cherrypick_logger` - `v1.1.0-dev.7`](#talker_cherrypick_logger---v110-dev7)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v1.1.3-dev.12`
- `talker_cherrypick_logger` - `v1.1.0-dev.7`
---
#### `cherrypick` - `v3.0.0-dev.12`
- **FIX**(scope): prevent concurrent modification in dispose().
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
## 2025-08-19
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.0-dev.11`](#cherrypick---v300-dev11)
- [`cherrypick_flutter` - `v1.1.3-dev.11`](#cherrypick_flutter---v113-dev11)
- [`talker_cherrypick_logger` - `v1.1.0-dev.6`](#talker_cherrypick_logger---v110-dev6)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v1.1.3-dev.11`
- `talker_cherrypick_logger` - `v1.1.0-dev.6`
---
#### `cherrypick` - `v3.0.0-dev.11`
- **FIX**(scope): prevent concurrent modification in dispose().
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
## 2025-08-15
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.0-dev.10`](#cherrypick---v300-dev10)
- [`cherrypick_annotations` - `v1.1.2-dev.1`](#cherrypick_annotations---v112-dev1)
- [`cherrypick_flutter` - `v1.1.3-dev.10`](#cherrypick_flutter---v113-dev10)
- [`cherrypick_generator` - `v2.0.0-dev.1`](#cherrypick_generator---v200-dev1)
- [`talker_cherrypick_logger` - `v1.1.0-dev.5`](#talker_cherrypick_logger---v110-dev5)
---
#### `cherrypick` - `v3.0.0-dev.10`
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
#### `cherrypick_annotations` - `v1.1.2-dev.1`
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
#### `cherrypick_flutter` - `v1.1.3-dev.10`
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
#### `cherrypick_generator` - `v2.0.0-dev.1`
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
#### `talker_cherrypick_logger` - `v1.1.0-dev.5`
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 2025-08-13
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`talker_cherrypick_logger` - `v1.1.0-dev.4`](#talker_cherrypick_logger---v110-dev4)
---
#### `talker_cherrypick_logger` - `v1.1.0-dev.4`
- **DOCS**(readme): update install instructions to use pub.dev as default method and remove obsolete git example.
## 2025-08-13 ## 2025-08-13
### Changes ### Changes

View File

@@ -1,4 +1,5 @@
# Contributors # Contributors
- Sergey Penkovsky <sergey.penkovsky@gmail.com> - [Sergey Penkovsky](https://github.com/pese-git)
- Klim Yaroshevich <yarashevich_kv@st.by> - [Klim Yaroshevich](https://github.com/KlimYarosh)
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick Workspace # CherryPick Workspace
CherryPick Workspace is a modular, open-source dependency injection ecosystem for Dart and Flutter, designed to offer lightweight, flexible, and scalable DI suitable for both backend and frontend (Flutter) development. This monorepo contains the main DI runtime library, annotation helpers, code generation for modular bindings, and seamless Flutter integration. CherryPick Workspace is a modular, open-source dependency injection ecosystem for Dart and Flutter, designed to offer lightweight, flexible, and scalable DI suitable for both backend and frontend (Flutter) development. This monorepo contains the main DI runtime library, annotation helpers, code generation for modular bindings, and seamless Flutter integration.

View File

@@ -1,4 +1,11 @@
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod # Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod vs kiwi
## Benchmark Parameters
- chainCount = 100
- nestingDepth = 100
- repeat = 5
- warmup = 2
## Benchmark Scenarios ## Benchmark Scenarios
@@ -11,41 +18,49 @@
--- ---
## Comparative Table: chainCount=10, nestingDepth=10 (Mean, PeakRSS) ## Comparative Table: chainCount=100, nestingDepth=100, repeat=5, warmup=2 (Mean time, µs)
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS | | Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:| |------------------|------------|--------|----------|-------|----------|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 | | chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 | | chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 | | register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 | | named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 | | override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 | | chainAsync | 493.8 | 34.0 | 5,039.0 | | 87.2 |
## Maximum Load: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS | ## Peak Memory Usage (Peak RSS, Kb)
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 | | Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 | |------------------|------------|--------|----------|--------|----------|
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 | | chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 | | chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 | | register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 | | named | 241,040 | 229,632| 280,144 | 271,872| 266,352 |
| override | 356,912 | 331,456| 329,808 | 369,104| 304,416 |
| chainAsync | 311,616 | 434,592| 301,168 | | 328,912 |
--- ---
## Analysis ## Analysis
- **get_it** is the absolute leader in all scenarios, especially under deep/nested chains and async. - **get_it** remains the clear leader for both speed and memory usage (lowest latency across most scenarios; excellent memory efficiency even on deep chains).
- **cherrypick** is highly competitive and much faster than riverpod on any complex graph. - **kiwi** shows the lowest memory footprint in chainSingleton, but is unavailable for async chains.
- **riverpod** is only suitable for small/simple DI graphs due to major slowdowns with depth, async, or override. - **yx_scope** demonstrates highly stable performance for both sync and async chains, often at the cost of higher memory usage, especially in the register/override scenarios.
- **cherrypick** comfortably beats riverpod, but is outperformed by get_it/kiwi/yx_scope, especially on async and heavy nested chains. It uses a bit less memory than yx_scope and kiwi, but can spike in memory/latency for override.
- **riverpod** is unsuitable for deep or async chains—latency and memory usage grow rapidly.
- **Peak memory (RSS):** usually around 320340 MB for all DI; riverpod/kiwi occasionally drops below 300MB. named/factory scenarios use much less.
- **Stability:** yx_scope and get_it have the lowest latency spikes; cherrypick can show peaks on override/async; riverpod is least stable on async (stddev/mean much worse).
### Recommendations ### Recommendations
- Use **get_it** for performance-critical and deeply nested graphs.
- Use **cherrypick** for scalable/testable apps if a small speed loss is acceptable. - **get_it** (and often **kiwi**, if you don't need async): best for ultra-fast deep graphs and minimum peak memory.
- Use **riverpod** only if you rely on Flutter integration and your DI chains are simple. - **yx_scope**: best blend of performance and async stability; perfect for production mixed DI.
- **cherrypick**: great for modular/testable architectures, unless absolute peak is needed; lower memory than yx_scope in some scenarios.
- **riverpod**: only for shallow DI or UI wiring in Flutter.
--- ---
_Last updated: August 8, 2025._ _Last updated: August 20, 2025._
_Please see scenario source for details._

View File

@@ -1,51 +1,63 @@
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod # Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod vs kiwi
## Параметры запуска:
- chainCount = 100
- nestingDepth = 100
- repeat = 5
- warmup = 2
## Описание сценариев ## Описание сценариев
1. **RegisterSingleton** — регистрация и получение объекта-синглтона (базовая скорость DI). 1. **RegisterSingleton** — регистрация и получение singleton (базовая скорость DI).
2. **ChainSingleton** — цепочка зависимостей A → B → ... → N (singleton). Глубокий singleton-резолвинг. 2. **ChainSingleton** — цепочка зависимостей A → B → ... → N (singleton). Глубокий singleton-резолвинг.
3. **ChainFactory** — все элементы цепочки — фабрики. Stateless построение графа. 3. **ChainFactory** — все элементы цепочки — factory. Stateless построение графа.
4. **AsyncChain** — асинхронная цепочка (async factory). Тестирует async/await граф. 4. **AsyncChain** — асинхронная цепочка (async factory). Тест async/await графа.
5. **Named** — регистрация двух биндингов с именами, разрешение по имени. 5. **Named** — регистрация двух биндингов с именами, разрешение по имени.
6. **Override** — регистрация биндинга/цепочки в дочернем scope. Проверка override/scoping. 6. **Override** — регистрация биндинга/цепочки в дочернем scope.
--- ---
## Сводная таблица: chainCount=10, nestingDepth=10 (Mean, PeakRSS) ## Сравнительная таблица: chainCount=100, nestingDepth=100, repeat=5, warmup=2 (среднее время, мкс)
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS | | Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:| |------------------|------------|--------|----------|-------|----------|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 | | chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 | | chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 | | register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 | | named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 | | override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 | | chainAsync | 493.8 | 34.0 | 5,039.0 | | 87.2 |
## Максимальная нагрузка: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS | ## Пиковое потребление памяти (Peak RSS, Кб)
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 | | Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 | |------------------|------------|--------|----------|--------|----------|
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 | | chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 | | chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 | | register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 | | named | 241,040 | 229,632| 280,144 | 271,872| 266,352 |
| override | 356,912 | 331,456| 329,808 | 369,104| 304,416 |
| chainAsync | 311,616 | 434,592| 301,168 | | 328,912 |
--- ---
## Краткий анализ и рекомендации ## Краткий анализ и рекомендации
- **get_it** всегда лидер, особенно на глубине/асинхронных графах. - **get_it** — абсолютный лидер по скорости и памяти на всех графах (минимальная задержка, небольшой peak RSS в любых цепочках).
- **cherrypick** заметно быстрее riverpod на сложных сценариях, опережая его в разы. - **kiwi** — минимальное потребление памяти в chainSingleton/Factory, но не для асинхронности.
- **riverpod** подходит только для простых/небольших графов — при росте глубины или async/override резко проигрывает по скорости. - **yx_scope** — очень ровная производительность даже на сложных async/sync-цепях, иногда с пиком в памяти на override/register, но задержки всегда минимальны.
- **cherrypick** — стабильнее riverpod, но ощутимо уступает top-3 по латентности на длинных/async-графах; по памяти лучше yx_scope для override/named.
- **riverpod** — непригоден для глубоких/async-графов: память и время растут очень сильно.
- **Пиковое потребление памяти**: большинство DI держится в районе 320340 Мб (большие цепи), на мелких named/factory — крайне мало.
- **Стабильность**: yx_scope и get_it показывают наименьшие скачки времени; у cherrypick иногда всплески на override/async, у riverpod — на async графе stddev почти равен mean!
### Рекомендации ### Рекомендации
- Используйте **get_it** для критичных к скорости приложений/сложных графов зависимостей. - Используйте **get_it** (или **kiwi**, если не нужен async) для максимальной производительности и минимального пикового использования памяти.
- Выбирайте **cherrypick** для масштабируемых, тестируемых архитектур, если микросекундная разница не критична. - **yx_scope** — идеально для production-графов с миксом sync/async.
- **riverpod** уместен только для реактивного UI или простых графов DI. - **cherrypick** — хорошо для модульных и тестируемых приложений, если не требуется абсолютная “микросекундная” производительность.
- **riverpod** — только если граф плоский или нужно DI только для UI во Flutter.
--- ---
_Обновлено: 8 августа 2025_ _Обновлено: 20 августа 2025._

View File

@@ -73,7 +73,8 @@ class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
_childDi!.resolve<UniversalService>(); _childDi!.resolve<UniversalService>();
break; break;
case UniversalScenario.asyncChain: case UniversalScenario.asyncChain:
throw UnsupportedError('asyncChain supported only in UniversalChainAsyncBenchmark'); throw UnsupportedError(
'asyncChain supported only in UniversalChainAsyncBenchmark');
} }
} }
} }

View File

@@ -1,6 +1,8 @@
import 'dart:math'; import 'dart:math';
import 'package:benchmark_di/cli/report/markdown_report.dart'; import 'package:benchmark_di/cli/report/markdown_report.dart';
import 'package:benchmark_di/di_adapters/yx_scope_adapter.dart';
import 'package:benchmark_di/di_adapters/yx_scope_universal_container.dart';
import 'package:benchmark_di/scenarios/universal_scenario.dart'; import 'package:benchmark_di/scenarios/universal_scenario.dart';
import 'package:cherrypick/cherrypick.dart'; import 'package:cherrypick/cherrypick.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
@@ -16,6 +18,8 @@ import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
import 'package:benchmark_di/di_adapters/cherrypick_adapter.dart'; import 'package:benchmark_di/di_adapters/cherrypick_adapter.dart';
import 'package:benchmark_di/di_adapters/get_it_adapter.dart'; import 'package:benchmark_di/di_adapters/get_it_adapter.dart';
import 'package:benchmark_di/di_adapters/riverpod_adapter.dart'; import 'package:benchmark_di/di_adapters/riverpod_adapter.dart';
import 'package:benchmark_di/di_adapters/kiwi_adapter.dart';
import 'package:kiwi/kiwi.dart';
/// Command-line interface (CLI) runner for benchmarks. /// Command-line interface (CLI) runner for benchmarks.
/// ///
@@ -36,8 +40,11 @@ class BenchmarkCliRunner {
if (config.di == 'getit') { if (config.di == 'getit') {
final di = GetItAdapter(); final di = GetItAdapter();
if (scenario == UniversalScenario.asyncChain) { if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<GetIt>(di, final benchAsync = UniversalChainAsyncBenchmark<GetIt>(
chainCount: c, nestingDepth: d, mode: mode, di,
chainCount: c,
nestingDepth: d,
mode: mode,
); );
benchResult = await BenchmarkRunner.runAsync( benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync, benchmark: benchAsync,
@@ -45,8 +52,41 @@ class BenchmarkCliRunner {
repeats: config.repeats, repeats: config.repeats,
); );
} else { } else {
final benchSync = UniversalChainBenchmark<GetIt>(di, final benchSync = UniversalChainBenchmark<GetIt>(
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario, di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
);
benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync,
warmups: config.warmups,
repeats: config.repeats,
);
}
} else if (config.di == 'kiwi') {
final di = KiwiAdapter();
if (scenario == UniversalScenario.asyncChain) {
// UnsupportedError будет выброшен адаптером, но если дойдёт — вызывать async benchmark
final benchAsync = UniversalChainAsyncBenchmark<KiwiContainer>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
);
benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync,
warmups: config.warmups,
repeats: config.repeats,
);
} else {
final benchSync = UniversalChainBenchmark<KiwiContainer>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
); );
benchResult = await BenchmarkRunner.runSync( benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync, benchmark: benchSync,
@@ -57,8 +97,12 @@ class BenchmarkCliRunner {
} else if (config.di == 'riverpod') { } else if (config.di == 'riverpod') {
final di = RiverpodAdapter(); final di = RiverpodAdapter();
if (scenario == UniversalScenario.asyncChain) { if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<Map<String, rp.ProviderBase<Object?>>>(di, final benchAsync = UniversalChainAsyncBenchmark<
chainCount: c, nestingDepth: d, mode: mode, Map<String, rp.ProviderBase<Object?>>>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
); );
benchResult = await BenchmarkRunner.runAsync( benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync, benchmark: benchAsync,
@@ -66,8 +110,43 @@ class BenchmarkCliRunner {
repeats: config.repeats, repeats: config.repeats,
); );
} else { } else {
final benchSync = UniversalChainBenchmark<Map<String, rp.ProviderBase<Object?>>>(di, final benchSync = UniversalChainBenchmark<
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario, Map<String, rp.ProviderBase<Object?>>>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
);
benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync,
warmups: config.warmups,
repeats: config.repeats,
);
}
} else if (config.di == 'yx_scope') {
final di = YxScopeAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync =
UniversalChainAsyncBenchmark<UniversalYxScopeContainer>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
);
benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync,
warmups: config.warmups,
repeats: config.repeats,
);
} else {
final benchSync =
UniversalChainBenchmark<UniversalYxScopeContainer>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
); );
benchResult = await BenchmarkRunner.runSync( benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync, benchmark: benchSync,
@@ -78,8 +157,11 @@ class BenchmarkCliRunner {
} else { } else {
final di = CherrypickDIAdapter(); final di = CherrypickDIAdapter();
if (scenario == UniversalScenario.asyncChain) { if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<Scope>(di, final benchAsync = UniversalChainAsyncBenchmark<Scope>(
chainCount: c, nestingDepth: d, mode: mode, di,
chainCount: c,
nestingDepth: d,
mode: mode,
); );
benchResult = await BenchmarkRunner.runAsync( benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync, benchmark: benchAsync,
@@ -87,8 +169,12 @@ class BenchmarkCliRunner {
repeats: config.repeats, repeats: config.repeats,
); );
} else { } else {
final benchSync = UniversalChainBenchmark<Scope>(di, final benchSync = UniversalChainBenchmark<Scope>(
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario, di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
); );
benchResult = await BenchmarkRunner.runSync( benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync, benchmark: benchSync,
@@ -103,7 +189,11 @@ class BenchmarkCliRunner {
var median = timings[timings.length ~/ 2]; var median = timings[timings.length ~/ 2];
var minVal = timings.first; var minVal = timings.first;
var maxVal = timings.last; var maxVal = timings.last;
var stddev = timings.isEmpty ? 0 : sqrt(timings.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) / timings.length); var stddev = timings.isEmpty
? 0
: sqrt(
timings.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) /
timings.length);
results.add({ results.add({
'benchmark': 'Universal_$bench', 'benchmark': 'Universal_$bench',
'chainCount': c, 'chainCount': c,
@@ -128,6 +218,7 @@ class BenchmarkCliRunner {
'json': JsonReport(), 'json': JsonReport(),
'markdown': MarkdownReport(), 'markdown': MarkdownReport(),
}; };
print(reportGenerators[config.format]?.render(results) ?? PrettyReport().render(results)); print(reportGenerators[config.format]?.render(results) ??
PrettyReport().render(results));
} }
} }

View File

@@ -8,14 +8,19 @@ import 'package:benchmark_di/scenarios/universal_scenario.dart';
enum UniversalBenchmark { enum UniversalBenchmark {
/// Simple singleton registration benchmark /// Simple singleton registration benchmark
registerSingleton, registerSingleton,
/// Chain of singleton dependencies /// Chain of singleton dependencies
chainSingleton, chainSingleton,
/// Chain using factories /// Chain using factories
chainFactory, chainFactory,
/// Async chain resolution /// Async chain resolution
chainAsync, chainAsync,
/// Named registration benchmark /// Named registration benchmark
named, named,
/// Override/child-scope benchmark /// Override/child-scope benchmark
override, override,
} }
@@ -65,23 +70,32 @@ T parseEnum<T>(String value, List<T> values, T defaultValue) {
} }
/// Parses comma-separated integer list from [s]. /// Parses comma-separated integer list from [s].
List<int> parseIntList(String s) => List<int> parseIntList(String s) => s
s.split(',').map((e) => int.tryParse(e.trim()) ?? 0).where((x) => x > 0).toList(); .split(',')
.map((e) => int.tryParse(e.trim()) ?? 0)
.where((x) => x > 0)
.toList();
/// CLI config describing what and how to benchmark. /// CLI config describing what and how to benchmark.
class BenchmarkCliConfig { class BenchmarkCliConfig {
/// Benchmarks enabled to run (scenarios). /// Benchmarks enabled to run (scenarios).
final List<UniversalBenchmark> benchesToRun; final List<UniversalBenchmark> benchesToRun;
/// List of chain counts (parallel, per test). /// List of chain counts (parallel, per test).
final List<int> chainCounts; final List<int> chainCounts;
/// List of nesting depths (max chain length, per test). /// List of nesting depths (max chain length, per test).
final List<int> nestDepths; final List<int> nestDepths;
/// How many times to repeat each trial. /// How many times to repeat each trial.
final int repeats; final int repeats;
/// How many times to warm-up before measuring. /// How many times to warm-up before measuring.
final int warmups; final int warmups;
/// Output report format. /// Output report format.
final String format; final String format;
/// Name of DI implementation ("cherrypick" or "getit") /// Name of DI implementation ("cherrypick" or "getit")
final String di; final String di;
BenchmarkCliConfig({ BenchmarkCliConfig({
@@ -105,7 +119,9 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
..addOption('repeat', abbr: 'r', defaultsTo: '2') ..addOption('repeat', abbr: 'r', defaultsTo: '2')
..addOption('warmup', abbr: 'w', defaultsTo: '1') ..addOption('warmup', abbr: 'w', defaultsTo: '1')
..addOption('format', abbr: 'f', defaultsTo: 'pretty') ..addOption('format', abbr: 'f', defaultsTo: 'pretty')
..addOption('di', defaultsTo: 'cherrypick', help: 'DI implementation: cherrypick, getit or riverpod') ..addOption('di',
defaultsTo: 'cherrypick',
help: 'DI implementation: cherrypick, getit or riverpod')
..addFlag('help', abbr: 'h', negatable: false, help: 'Show help'); ..addFlag('help', abbr: 'h', negatable: false, help: 'Show help');
final result = parser.parse(args); final result = parser.parse(args);
if (result['help'] == true) { if (result['help'] == true) {

View File

@@ -5,20 +5,32 @@ class CsvReport extends ReportGenerator {
/// List of all keys/columns to include in the CSV output. /// List of all keys/columns to include in the CSV output.
@override @override
final List<String> keys = [ final List<String> keys = [
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us', 'benchmark',
'min_us','max_us','trials','timings_us','memory_diff_kb','delta_peak_kb','peak_rss_kb' 'chainCount',
'nestingDepth',
'mean_us',
'median_us',
'stddev_us',
'min_us',
'max_us',
'trials',
'timings_us',
'memory_diff_kb',
'delta_peak_kb',
'peak_rss_kb'
]; ];
/// Renders rows as a CSV table string. /// Renders rows as a CSV table string.
@override @override
String render(List<Map<String, dynamic>> rows) { String render(List<Map<String, dynamic>> rows) {
final header = keys.join(','); final header = keys.join(',');
final lines = rows.map((r) => final lines = rows
keys.map((k) { .map((r) => keys.map((k) {
final v = r[k]; final v = r[k];
if (v is List) return '"${v.join(';')}"'; if (v is List) return '"${v.join(';')}"';
return (v ?? '').toString(); return (v ?? '').toString();
}).join(',') }).join(','))
).toList(); .toList();
return ([header] + lines).join('\n'); return ([header] + lines).join('\n');
} }
} }

View File

@@ -5,6 +5,7 @@ class JsonReport extends ReportGenerator {
/// No specific keys; outputs all fields in raw map. /// No specific keys; outputs all fields in raw map.
@override @override
List<String> get keys => []; List<String> get keys => [];
/// Renders all result rows as a pretty-printed JSON array. /// Renders all result rows as a pretty-printed JSON array.
@override @override
String render(List<Map<String, dynamic>> rows) { String render(List<Map<String, dynamic>> rows) {

View File

@@ -7,25 +7,46 @@ class MarkdownReport extends ReportGenerator {
/// List of columns (keys) to show in the Markdown table. /// List of columns (keys) to show in the Markdown table.
@override @override
final List<String> keys = [ final List<String> keys = [
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us', 'benchmark',
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb' 'chainCount',
'nestingDepth',
'mean_us',
'median_us',
'stddev_us',
'min_us',
'max_us',
'trials',
'memory_diff_kb',
'delta_peak_kb',
'peak_rss_kb'
]; ];
/// Friendly display names for each benchmark type. /// Friendly display names for each benchmark type.
static const nameMap = { static const nameMap = {
'Universal_UniversalBenchmark.registerSingleton':'RegisterSingleton', 'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
'Universal_UniversalBenchmark.chainSingleton':'ChainSingleton', 'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
'Universal_UniversalBenchmark.chainFactory':'ChainFactory', 'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
'Universal_UniversalBenchmark.chainAsync':'AsyncChain', 'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
'Universal_UniversalBenchmark.named':'Named', 'Universal_UniversalBenchmark.named': 'Named',
'Universal_UniversalBenchmark.override':'Override', 'Universal_UniversalBenchmark.override': 'Override',
}; };
/// Renders all results as a formatted Markdown table with aligned columns and a legend. /// Renders all results as a formatted Markdown table with aligned columns and a legend.
@override @override
String render(List<Map<String, dynamic>> rows) { String render(List<Map<String, dynamic>> rows) {
final headers = [ final headers = [
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)' 'Benchmark',
'Chain Count',
'Depth',
'Mean (us)',
'Median',
'Stddev',
'Min',
'Max',
'N',
'ΔRSS(KB)',
'ΔPeak(KB)',
'PeakRSS(KB)'
]; ];
final dataRows = rows.map((r) { final dataRows = rows.map((r) {
final readableName = nameMap[r['benchmark']] ?? r['benchmark']; final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
@@ -73,6 +94,6 @@ class MarkdownReport extends ReportGenerator {
> `PeakRSS(KB)` Max observed RSS memory (KB) > `PeakRSS(KB)` Max observed RSS memory (KB)
'''; ''';
return '$legend\n\n${([headerLine, divider] + lines).join('\n')}' ; return '$legend\n\n${([headerLine, divider] + lines).join('\n')}';
} }
} }

View File

@@ -7,8 +7,18 @@ class PrettyReport extends ReportGenerator {
/// List of columns to output in the pretty report. /// List of columns to output in the pretty report.
@override @override
final List<String> keys = [ final List<String> keys = [
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us', 'benchmark',
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb' 'chainCount',
'nestingDepth',
'mean_us',
'median_us',
'stddev_us',
'min_us',
'max_us',
'trials',
'memory_diff_kb',
'delta_peak_kb',
'peak_rss_kb'
]; ];
/// Mappings from internal benchmark IDs to display names. /// Mappings from internal benchmark IDs to display names.
@@ -25,7 +35,18 @@ class PrettyReport extends ReportGenerator {
@override @override
String render(List<Map<String, dynamic>> rows) { String render(List<Map<String, dynamic>> rows) {
final headers = [ final headers = [
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)' 'Benchmark',
'Chain Count',
'Depth',
'Mean (us)',
'Median',
'Stddev',
'Min',
'Max',
'N',
'ΔRSS(KB)',
'ΔPeak(KB)',
'PeakRSS(KB)'
]; ];
final header = headers.join('\t'); final header = headers.join('\t');
final lines = rows.map((r) { final lines = rows.map((r) {

View File

@@ -4,6 +4,7 @@
abstract class ReportGenerator { abstract class ReportGenerator {
/// Renders the given [results] as a formatted string (table, markdown, csv, etc). /// Renders the given [results] as a formatted string (table, markdown, csv, etc).
String render(List<Map<String, dynamic>> results); String render(List<Map<String, dynamic>> results);
/// List of output columns/keys included in the export (or [] for auto/all). /// List of output columns/keys included in the export (or [] for auto/all).
List<String> get keys; List<String> get keys;
} }

View File

@@ -7,10 +7,13 @@ import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
class BenchmarkResult { class BenchmarkResult {
/// List of timings for each run (in microseconds). /// List of timings for each run (in microseconds).
final List<num> timings; final List<num> timings;
/// Difference in memory (RSS, in KB) after running. /// Difference in memory (RSS, in KB) after running.
final int memoryDiffKb; final int memoryDiffKb;
/// Difference between peak RSS and initial RSS (in KB). /// Difference between peak RSS and initial RSS (in KB).
final int deltaPeakKb; final int deltaPeakKb;
/// Peak RSS memory observed (in KB). /// Peak RSS memory observed (in KB).
final int peakRssKb; final int peakRssKb;
BenchmarkResult({ BenchmarkResult({
@@ -19,6 +22,7 @@ class BenchmarkResult {
required this.deltaPeakKb, required this.deltaPeakKb,
required this.peakRssKb, required this.peakRssKb,
}); });
/// Computes a BenchmarkResult instance from run timings and memory data. /// Computes a BenchmarkResult instance from run timings and memory data.
factory BenchmarkResult.collect({ factory BenchmarkResult.collect({
required List<num> timings, required List<num> timings,
@@ -64,7 +68,8 @@ class BenchmarkRunner {
rssValues.add(ProcessInfo.currentRss); rssValues.add(ProcessInfo.currentRss);
benchmark.teardown(); benchmark.teardown();
} }
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore); return BenchmarkResult.collect(
timings: timings, rssValues: rssValues, memBefore: memBefore);
} }
/// Runs an asynchronous benchmark ([UniversalChainAsyncBenchmark]) for a given number of [warmups] and [repeats]. /// Runs an asynchronous benchmark ([UniversalChainAsyncBenchmark]) for a given number of [warmups] and [repeats].
@@ -91,6 +96,7 @@ class BenchmarkRunner {
rssValues.add(ProcessInfo.currentRss); rssValues.add(ProcessInfo.currentRss);
await benchmark.teardown(); await benchmark.teardown();
} }
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore); return BenchmarkResult.collect(
timings: timings, rssValues: rssValues, memBefore: memBefore);
} }
} }

View File

@@ -4,7 +4,6 @@ import 'package:benchmark_di/scenarios/universal_service.dart';
import 'package:cherrypick/cherrypick.dart'; import 'package:cherrypick/cherrypick.dart';
import 'di_adapter.dart'; import 'di_adapter.dart';
/// Test module that generates a chain of service bindings for benchmarking. /// Test module that generates a chain of service bindings for benchmarking.
/// ///
/// Configurable by chain count, nesting depth, binding mode, and scenario /// Configurable by chain count, nesting depth, binding mode, and scenario
@@ -12,10 +11,13 @@ import 'di_adapter.dart';
class UniversalChainModule extends Module { class UniversalChainModule extends Module {
/// Number of chains to create. /// Number of chains to create.
final int chainCount; final int chainCount;
/// Depth of each chain. /// Depth of each chain.
final int nestingDepth; final int nestingDepth;
/// How modules are registered (factory/singleton/async). /// How modules are registered (factory/singleton/async).
final UniversalBindingMode bindingMode; final UniversalBindingMode bindingMode;
/// Which di scenario to generate (chained, named, etc). /// Which di scenario to generate (chained, named, etc).
final UniversalScenario scenario; final UniversalScenario scenario;
@@ -40,7 +42,8 @@ class UniversalChainModule extends Module {
bind<UniversalService>() bind<UniversalService>()
.toProvideAsync(() async { .toProvideAsync(() async {
final prev = level > 1 final prev = level > 1
? await currentScope.resolveAsync<UniversalService>(named: prevDepName) ? await currentScope.resolveAsync<UniversalService>(
named: prevDepName)
: null; : null;
return UniversalServiceImpl( return UniversalServiceImpl(
value: depName, value: depName,
@@ -58,13 +61,18 @@ class UniversalChainModule extends Module {
case UniversalScenario.register: case UniversalScenario.register:
// Simple singleton registration. // Simple singleton registration.
bind<UniversalService>() bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(value: 'reg', dependency: null)) .toProvide(
() => UniversalServiceImpl(value: 'reg', dependency: null))
.singleton(); .singleton();
break; break;
case UniversalScenario.named: case UniversalScenario.named:
// Named factory registration for two distinct objects. // Named factory registration for two distinct objects.
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl1')).withName('impl1'); bind<UniversalService>()
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl2')).withName('impl2'); .toProvide(() => UniversalServiceImpl(value: 'impl1'))
.withName('impl1');
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(value: 'impl2'))
.withName('impl2');
break; break;
case UniversalScenario.chain: case UniversalScenario.chain:
// Chain of nested services, with dependency on previous level by name. // Chain of nested services, with dependency on previous level by name.
@@ -79,7 +87,8 @@ class UniversalChainModule extends Module {
bind<UniversalService>() bind<UniversalService>()
.toProvide(() => UniversalServiceImpl( .toProvide(() => UniversalServiceImpl(
value: depName, value: depName,
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName), dependency: currentScope.tryResolve<UniversalService>(
named: prevDepName),
)) ))
.withName(depName) .withName(depName)
.singleton(); .singleton();
@@ -88,7 +97,8 @@ class UniversalChainModule extends Module {
bind<UniversalService>() bind<UniversalService>()
.toProvide(() => UniversalServiceImpl( .toProvide(() => UniversalServiceImpl(
value: depName, value: depName,
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName), dependency: currentScope.tryResolve<UniversalService>(
named: prevDepName),
)) ))
.withName(depName); .withName(depName);
break; break;
@@ -96,7 +106,9 @@ class UniversalChainModule extends Module {
bind<UniversalService>() bind<UniversalService>()
.toProvideAsync(() async => UniversalServiceImpl( .toProvideAsync(() async => UniversalServiceImpl(
value: depName, value: depName,
dependency: await currentScope.resolveAsync<UniversalService>(named: prevDepName), dependency:
await currentScope.resolveAsync<UniversalService>(
named: prevDepName),
)) ))
.withName(depName) .withName(depName)
.singleton(); .singleton();
@@ -107,14 +119,16 @@ class UniversalChainModule extends Module {
// Регистрация алиаса без имени (на последний элемент цепочки) // Регистрация алиаса без имени (на последний элемент цепочки)
final depName = '${chainCount}_$nestingDepth'; final depName = '${chainCount}_$nestingDepth';
bind<UniversalService>() bind<UniversalService>()
.toProvide(() => currentScope.resolve<UniversalService>(named: depName)) .toProvide(
() => currentScope.resolve<UniversalService>(named: depName))
.singleton(); .singleton();
break; break;
case UniversalScenario.override: case UniversalScenario.override:
// handled at benchmark level, но алиас нужен прямо в этом scope! // handled at benchmark level, но алиас нужен прямо в этом scope!
final depName = '${chainCount}_$nestingDepth'; final depName = '${chainCount}_$nestingDepth';
bind<UniversalService>() bind<UniversalService>()
.toProvide(() => currentScope.resolve<UniversalService>(named: depName)) .toProvide(
() => currentScope.resolve<UniversalService>(named: depName))
.singleton(); .singleton();
break; break;
case UniversalScenario.asyncChain: case UniversalScenario.asyncChain:
@@ -124,7 +138,6 @@ class UniversalChainModule extends Module {
} }
} }
class CherrypickDIAdapter extends DIAdapter<Scope> { class CherrypickDIAdapter extends DIAdapter<Scope> {
Scope? _scope; Scope? _scope;
final bool _isSubScope; final bool _isSubScope;
@@ -158,7 +171,8 @@ class CherrypickDIAdapter extends DIAdapter<Scope> {
]); ]);
}; };
} }
throw UnsupportedError('Scenario $scenario not supported by CherrypickDIAdapter'); throw UnsupportedError(
'Scenario $scenario not supported by CherrypickDIAdapter');
} }
@override @override
@@ -170,9 +184,9 @@ class CherrypickDIAdapter extends DIAdapter<Scope> {
_scope!.resolveAsync<T>(named: named); _scope!.resolveAsync<T>(named: named);
@override @override
void teardown() { Future<void> teardown() async {
if (!_isSubScope) { if (!_isSubScope) {
CherryPick.closeRootScope(); await CherryPick.closeRootScope();
_scope = null; _scope = null;
} }
// SubScope teardown не требуется // SubScope teardown не требуется

View File

@@ -1,4 +1,5 @@
import 'package:benchmark_di/scenarios/universal_binding_mode.dart'; import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
/// Универсальная абстракция для DI-адаптера с унифицированной функцией регистрации. /// Универсальная абстракция для DI-адаптера с унифицированной функцией регистрации.
/// Теперь для каждого адаптера задаём строгий generic тип контейнера. /// Теперь для каждого адаптера задаём строгий generic тип контейнера.
typedef Registration<TContainer> = void Function(TContainer); typedef Registration<TContainer> = void Function(TContainer);

View File

@@ -80,9 +80,11 @@ class GetItAdapter extends DIAdapter<GetIt> {
getIt.registerSingletonAsync<UniversalService>( getIt.registerSingletonAsync<UniversalService>(
() async { () async {
final prev = level > 1 final prev = level > 1
? await getIt.getAsync<UniversalService>(instanceName: prevDepName) ? await getIt.getAsync<UniversalService>(
instanceName: prevDepName)
: null; : null;
return UniversalServiceImpl(value: depName, dependency: prev); return UniversalServiceImpl(
value: depName, dependency: prev);
}, },
instanceName: depName, instanceName: depName,
); );
@@ -90,11 +92,16 @@ class GetItAdapter extends DIAdapter<GetIt> {
} }
break; break;
case UniversalScenario.register: case UniversalScenario.register:
getIt.registerSingleton<UniversalService>(UniversalServiceImpl(value: 'reg', dependency: null)); getIt.registerSingleton<UniversalService>(
UniversalServiceImpl(value: 'reg', dependency: null));
break; break;
case UniversalScenario.named: case UniversalScenario.named:
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl1'), instanceName: 'impl1'); getIt.registerFactory<UniversalService>(
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl2'), instanceName: 'impl2'); () => UniversalServiceImpl(value: 'impl1'),
instanceName: 'impl1');
getIt.registerFactory<UniversalService>(
() => UniversalServiceImpl(value: 'impl2'),
instanceName: 'impl2');
break; break;
case UniversalScenario.chain: case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) { for (int chain = 1; chain <= chainCount; chain++) {
@@ -129,7 +136,8 @@ class GetItAdapter extends DIAdapter<GetIt> {
() async => UniversalServiceImpl( () async => UniversalServiceImpl(
value: depName, value: depName,
dependency: level > 1 dependency: level > 1
? await getIt.getAsync<UniversalService>(instanceName: prevDepName) ? await getIt.getAsync<UniversalService>(
instanceName: prevDepName)
: null, : null,
), ),
instanceName: depName, instanceName: depName,
@@ -143,7 +151,8 @@ class GetItAdapter extends DIAdapter<GetIt> {
// handled at benchmark level // handled at benchmark level
break; break;
} }
if (scenario == UniversalScenario.chain || scenario == UniversalScenario.override) { if (scenario == UniversalScenario.chain ||
scenario == UniversalScenario.override) {
final depName = '${chainCount}_$nestingDepth'; final depName = '${chainCount}_$nestingDepth';
getIt.registerSingleton<UniversalService>( getIt.registerSingleton<UniversalService>(
getIt<UniversalService>(instanceName: depName), getIt<UniversalService>(instanceName: depName),

View File

@@ -0,0 +1,132 @@
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
import 'package:benchmark_di/scenarios/universal_scenario.dart';
import 'package:benchmark_di/scenarios/universal_service.dart';
import 'package:kiwi/kiwi.dart';
import 'di_adapter.dart';
/// DIAdapter-для KiwiContainer с поддержкой universal benchmark сценариев.
class KiwiAdapter extends DIAdapter<KiwiContainer> {
late KiwiContainer _container;
// ignore: unused_field
final bool _isSubScope;
KiwiAdapter({KiwiContainer? container, bool isSubScope = false})
: _isSubScope = isSubScope {
_container = container ?? KiwiContainer();
}
@override
void setupDependencies(void Function(KiwiContainer container) registration) {
registration(_container);
}
@override
Registration<KiwiContainer> universalRegistration<S extends Enum>({
required S scenario,
required int chainCount,
required int nestingDepth,
required UniversalBindingMode bindingMode,
}) {
if (scenario is UniversalScenario) {
if (scenario == UniversalScenario.asyncChain ||
bindingMode == UniversalBindingMode.asyncStrategy) {
throw UnsupportedError(
'Kiwi does not support async dependencies or async binding scenarios.');
}
return (container) {
switch (scenario) {
case UniversalScenario.asyncChain:
break;
case UniversalScenario.register:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(value: 'reg', dependency: null),
);
break;
case UniversalScenario.named:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl1'),
name: 'impl1');
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl2'),
name: 'impl2');
break;
case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
switch (bindingMode) {
case UniversalBindingMode.singletonStrategy:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.factoryStrategy:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.asyncStrategy:
// Не поддерживается
break;
}
}
}
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
case UniversalScenario.override:
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
}
};
}
throw UnsupportedError('Scenario $scenario not supported by KiwiAdapter');
}
@override
T resolve<T extends Object>({String? named}) {
// Для asyncChain нужен resolve<Future<T>>
if (T.toString().startsWith('Future<')) {
return _container.resolve<T>(named);
} else {
return _container.resolve<T>(named);
}
}
@override
Future<T> resolveAsync<T extends Object>({String? named}) async {
if (T.toString().startsWith('Future<')) {
// resolve<Future<T>>, unwrap result
return Future.value(_container.resolve<T>(named));
} else {
// Для совместимости с chain/override
return Future.value(_container.resolve<T>(named));
}
}
@override
void teardown() {
_container.clear();
}
@override
KiwiAdapter openSubScope(String name) {
// Возвращаем новый scoped контейнер (отдельный). Наследование не реализовано.
return KiwiAdapter(container: KiwiContainer.scoped(), isSubScope: true);
}
@override
Future<void> waitForAsyncReady() async {}
}

View File

@@ -20,7 +20,9 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
_parent = parent; _parent = parent;
@override @override
void setupDependencies(void Function(Map<String, rp.ProviderBase<Object?>> container) registration) { void setupDependencies(
void Function(Map<String, rp.ProviderBase<Object?>> container)
registration) {
_container ??= _parent == null _container ??= _parent == null
? rp.ProviderContainer() ? rp.ProviderContainer()
: rp.ProviderContainer(parent: _parent); : rp.ProviderContainer(parent: _parent);
@@ -76,7 +78,8 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
} }
@override @override
Registration<Map<String, rp.ProviderBase<Object?>>> universalRegistration<S extends Enum>({ Registration<Map<String, rp.ProviderBase<Object?>>>
universalRegistration<S extends Enum>({
required S scenario, required S scenario,
required int chainCount, required int chainCount,
required int nestingDepth, required int nestingDepth,
@@ -86,25 +89,34 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
return (providers) { return (providers) {
switch (scenario) { switch (scenario) {
case UniversalScenario.register: case UniversalScenario.register:
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'reg', dependency: null)); providers['UniversalService'] = rp.Provider<UniversalService>(
(ref) => UniversalServiceImpl(value: 'reg', dependency: null));
break; break;
case UniversalScenario.named: case UniversalScenario.named:
providers['impl1'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl1')); providers['impl1'] = rp.Provider<UniversalService>(
providers['impl2'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl2')); (ref) => UniversalServiceImpl(value: 'impl1'));
providers['impl2'] = rp.Provider<UniversalService>(
(ref) => UniversalServiceImpl(value: 'impl2'));
break; break;
case UniversalScenario.chain: case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) { for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) { for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}'; final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level'; final depName = '${chain}_$level';
providers[depName] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl( providers[depName] =
rp.Provider<UniversalService>((ref) => UniversalServiceImpl(
value: depName, value: depName,
dependency: level > 1 ? ref.watch(providers[prevDepName] as rp.ProviderBase<UniversalService>) : null, dependency: level > 1
? ref.watch(providers[prevDepName]
as rp.ProviderBase<UniversalService>)
: null,
)); ));
} }
} }
final depName = '${chainCount}_$nestingDepth'; final depName = '${chainCount}_$nestingDepth';
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => ref.watch(providers[depName] as rp.ProviderBase<UniversalService>)); providers['UniversalService'] = rp.Provider<UniversalService>(
(ref) => ref.watch(
providers[depName] as rp.ProviderBase<UniversalService>));
break; break;
case UniversalScenario.override: case UniversalScenario.override:
// handled at benchmark level // handled at benchmark level
@@ -114,24 +126,31 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
for (int level = 1; level <= nestingDepth; level++) { for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}'; final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level'; final depName = '${chain}_$level';
providers[depName] = rp.FutureProvider<UniversalService>((ref) async { providers[depName] =
rp.FutureProvider<UniversalService>((ref) async {
return UniversalServiceImpl( return UniversalServiceImpl(
value: depName, value: depName,
dependency: level > 1 dependency: level > 1
? await ref.watch((providers[prevDepName] as rp.FutureProvider<UniversalService>).future) as UniversalService? ? await ref.watch((providers[prevDepName]
as rp.FutureProvider<UniversalService>)
.future) as UniversalService?
: null, : null,
); );
}); });
} }
} }
final depName = '${chainCount}_$nestingDepth'; final depName = '${chainCount}_$nestingDepth';
providers['UniversalService'] = rp.FutureProvider<UniversalService>((ref) async { providers['UniversalService'] =
return await ref.watch((providers[depName] as rp.FutureProvider<UniversalService>).future); rp.FutureProvider<UniversalService>((ref) async {
return await ref.watch(
(providers[depName] as rp.FutureProvider<UniversalService>)
.future);
}); });
break; break;
} }
}; };
} }
throw UnsupportedError('Scenario $scenario not supported by RiverpodAdapter'); throw UnsupportedError(
'Scenario $scenario not supported by RiverpodAdapter');
} }
} }

View File

@@ -0,0 +1,130 @@
// ignore_for_file: invalid_use_of_protected_member
import 'package:benchmark_di/di_adapters/di_adapter.dart';
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
import 'package:benchmark_di/scenarios/universal_scenario.dart';
import 'package:benchmark_di/scenarios/universal_service.dart';
import 'package:benchmark_di/di_adapters/yx_scope_universal_container.dart';
/// DIAdapter для yx_scope UniversalYxScopeContainer
class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
late UniversalYxScopeContainer _scope;
@override
void setupDependencies(
void Function(UniversalYxScopeContainer container) registration) {
_scope = UniversalYxScopeContainer();
registration(_scope);
}
@override
T resolve<T extends Object>({String? named}) {
return _scope.depFor<T>(name: named).get;
}
@override
Future<T> resolveAsync<T extends Object>({String? named}) async {
return resolve<T>(named: named);
}
@override
void teardown() {
// У yx_scope нет явного dispose на ScopeContainer, но можно добавить очистку Map/Deps если потребуется
// Ничего не делаем
}
@override
YxScopeAdapter openSubScope(String name) {
// Для простоты всегда возвращаем новый контейнер, сабскоупы не реализованы явно
return YxScopeAdapter();
}
@override
Future<void> waitForAsyncReady() async {
// Все зависимости синхронны
return;
}
@override
Registration<UniversalYxScopeContainer>
universalRegistration<S extends Enum>({
required S scenario,
required int chainCount,
required int nestingDepth,
required UniversalBindingMode bindingMode,
}) {
if (scenario is UniversalScenario) {
return (scope) {
switch (scenario) {
case UniversalScenario.asyncChain:
for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
final dep = scope.dep<UniversalService>(
() => UniversalServiceImpl(
value: depName,
dependency: level > 1
? scope.depFor<UniversalService>(name: prevDepName).get
: null,
),
name: depName,
);
scope.register<UniversalService>(dep, name: depName);
}
}
break;
case UniversalScenario.register:
final dep = scope.dep<UniversalService>(
() => UniversalServiceImpl(value: 'reg', dependency: null),
);
scope.register<UniversalService>(dep);
break;
case UniversalScenario.named:
final dep1 = scope.dep<UniversalService>(
() => UniversalServiceImpl(value: 'impl1'),
name: 'impl1',
);
final dep2 = scope.dep<UniversalService>(
() => UniversalServiceImpl(value: 'impl2'),
name: 'impl2',
);
scope.register<UniversalService>(dep1, name: 'impl1');
scope.register<UniversalService>(dep2, name: 'impl2');
break;
case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
final dep = scope.dep<UniversalService>(
() => UniversalServiceImpl(
value: depName,
dependency: level > 1
? scope.depFor<UniversalService>(name: prevDepName).get
: null,
),
name: depName,
);
scope.register<UniversalService>(dep, name: depName);
}
}
break;
case UniversalScenario.override:
// handled at benchmark level
break;
}
if (scenario == UniversalScenario.chain ||
scenario == UniversalScenario.override) {
final depName = '${chainCount}_$nestingDepth';
final lastDep = scope.dep<UniversalService>(
() => scope.depFor<UniversalService>(name: depName).get,
);
scope.register<UniversalService>(lastDep);
}
};
}
throw UnsupportedError(
'Scenario $scenario not supported by YxScopeAdapter');
}
}

View File

@@ -0,0 +1,30 @@
import 'package:yx_scope/yx_scope.dart';
/// Universal container for dynamic DI registration in yx_scope (for benchmarks).
/// Allows to register and resolve deps by name/type at runtime.
class UniversalYxScopeContainer extends ScopeContainer {
final Map<String, Dep<dynamic>> _namedDeps = {};
final Map<Type, Dep<dynamic>> _typedDeps = {};
void register<T>(Dep<T> dep, {String? name}) {
if (name != null) {
_namedDeps[_depKey<T>(name)] = dep;
} else {
_typedDeps[T] = dep;
}
}
Dep<T> depFor<T>({String? name}) {
if (name != null) {
final dep = _namedDeps[_depKey<T>(name)];
if (dep is Dep<T>) return dep;
throw Exception('No dep for type $T/$name');
} else {
final dep = _typedDeps[T];
if (dep is Dep<T>) return dep;
throw Exception('No dep for type $T');
}
}
static String _depKey<T>(String name) => '$T@$name';
}

View File

@@ -2,12 +2,16 @@
enum UniversalScenario { enum UniversalScenario {
/// Single registration. /// Single registration.
register, register,
/// Chain of dependencies. /// Chain of dependencies.
chain, chain,
/// Named registrations. /// Named registrations.
named, named,
/// Child-scope override scenario. /// Child-scope override scenario.
override, override,
/// Asynchronous chain scenario. /// Asynchronous chain scenario.
asyncChain, asyncChain,
} }

View File

@@ -1,4 +1,3 @@
/// Base interface for any universal service in the benchmarks. /// Base interface for any universal service in the benchmarks.
/// ///
/// Represents an object in the dependency chain with an identifiable value /// Represents an object in the dependency chain with an identifiable value
@@ -6,6 +5,7 @@
abstract class UniversalService { abstract class UniversalService {
/// String ID for this service instance (e.g. chain/level info). /// String ID for this service instance (e.g. chain/level info).
final String value; final String value;
/// Optional reference to dependency service in the chain. /// Optional reference to dependency service in the chain.
final UniversalService? dependency; final UniversalService? dependency;
UniversalService({required this.value, this.dependency}); UniversalService({required this.value, this.dependency});

View File

@@ -47,7 +47,7 @@ packages:
path: "../cherrypick" path: "../cherrypick"
relative: true relative: true
source: path source: path
version: "3.0.0-dev.8" version: "3.0.2"
collection: collection:
dependency: transitive dependency: transitive
description: description:
@@ -72,6 +72,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.2.0" version: "8.2.0"
kiwi:
dependency: "direct main"
description:
name: kiwi
sha256: d078364a90fb1b93852bb74468efdf4aaae35c036c538c1cf4f9c74a19df9a61
url: "https://pub.dev"
source: hosted
version: "5.0.1"
lazy_memo: lazy_memo:
dependency: transitive dependency: transitive
description: description:
@@ -128,5 +136,13 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.0" version: "1.0.0"
yx_scope:
dependency: "direct main"
description:
name: yx_scope
sha256: "9ba98b442261596311363bf7361622e5ccc67189705b8d042ca23c9de366f8bf"
url: "https://pub.dev"
source: hosted
version: "1.1.2"
sdks: sdks:
dart: ">=3.6.0 <4.0.0" dart: ">=3.6.0 <4.0.0"

View File

@@ -4,7 +4,7 @@ publish_to: none
description: Universal benchmark for any DI library (cherrypick, get_it, and others) description: Universal benchmark for any DI library (cherrypick, get_it, and others)
environment: environment:
sdk: '>=3.0.0 <4.0.0' sdk: '>=3.2.0 <4.0.0'
dependencies: dependencies:
cherrypick: cherrypick:
@@ -12,6 +12,8 @@ dependencies:
args: ^2.7.0 args: ^2.7.0
get_it: ^8.2.0 get_it: ^8.2.0
riverpod: ^2.6.1 riverpod: ^2.6.1
kiwi: ^5.0.1
yx_scope: ^1.1.2
dev_dependencies: dev_dependencies:
lints: ^5.0.0 lints: ^5.0.0

View File

@@ -1,3 +1,39 @@
## 3.0.2
- **FIX**(test): fix warning.
- **FIX**(scope): properly clear binding and module references on dispose.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.13
- **FIX**: fix examples.
- **DOCS**: update contributors list with GitHub links and add new contributor.
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
- **DOCS**(binding): clarify registration limitation in API doc.
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
## 3.0.0-dev.12
- **FIX**(scope): prevent concurrent modification in dispose().
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
## 3.0.0-dev.11
- **FIX**(scope): prevent concurrent modification in dispose().
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
## 3.0.0-dev.10
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 3.0.0-dev.9 ## 3.0.0-dev.9
- **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section. - **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick # CherryPick
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter. `cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter.
@@ -102,31 +107,98 @@ A **Binding** acts as a configuration for how to create or provide a particular
#### Example #### Example
```dart ```dart
// Provide a direct instance void builder(Scope scope) {
Binding<String>().toInstance("Hello world"); // Provide a direct instance
bind<String>().toInstance("Hello world");
// Provide an async direct instance // Provide an async direct instance
Binding<String>().toInstanceAsync(Future.value("Hello world")); bind<String>().toInstanceAsync(Future.value("Hello world"));
// Provide a lazy sync instance using a factory // Provide a lazy sync instance using a factory
Binding<String>().toProvide(() => "Hello world"); bind<String>().toProvide(() => "Hello world");
// Provide a lazy async instance using a factory // Provide a lazy async instance using a factory
Binding<String>().toProvideAsync(() async => "Hello async world"); bind<String>().toProvideAsync(() async => "Hello async world");
// Provide an instance with dynamic parameters (sync) // Provide an instance with dynamic parameters (sync)
Binding<String>().toProvideWithParams((params) => "Hello $params"); bind<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (async) // Provide an instance with dynamic parameters (async)
Binding<String>().toProvideAsyncWithParams((params) async => "Hello $params"); bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Named instance for retrieval by name // Named instance for retrieval by name
Binding<String>().toProvide(() => "Hello world").withName("my_string"); bind<String>().toProvide(() => "Hello world").withName("my_string");
// Mark as singleton (only one instance within the scope) // Mark as singleton (only one instance within the scope)
Binding<String>().toProvide(() => "Hello world").singleton(); bind<String>().toProvide(() => "Hello world").singleton();
}
``` ```
> ⚠️ **Important note about using `toInstance` in Module `builder`:**
>
> If you register a chain of dependencies via `toInstance` inside a Module's `builder`, **do not** call `scope.resolve<T>()` for types that are also being registered in the same builder — at the moment they are registered.
>
> CherryPick initializes all bindings in the builder sequentially. Dependencies registered earlier are not yet available to `resolve` within the same builder execution. Trying to resolve just-registered types will result in an error (`Can't resolve dependency ...`).
>
> **How to do it right:**
> Manually construct the full dependency chain before calling `toInstance`:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies **only** to `toInstance`. With `toProvide`/`toProvideAsync` and similar providers, you can safely use `scope.resolve<T>()` inside the builder.
> ⚠️ **Special note regarding `.singleton()` with `toProvideWithParams()` / `toProvideAsyncWithParams()`:**
>
> If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters; every subsequent call (regardless of params) will return the same (cached) instance.
>
> **Example:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
> final a = scope.resolve<Service>(params: 1); // creates Service(1)
> final b = scope.resolve<Service>(params: 2); // returns Service(1)
> print(identical(a, b)); // true
> ```
>
> Use this pattern only when you want a “master” singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
> **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
### Module ### Module
A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope. A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope.
@@ -716,6 +788,14 @@ CherryPick provides a set of official add-on modules for advanced use cases and
--- ---
## Contributors
- [Sergey Penkovsky](https://github.com/pese-git)
- [Klim Yaroshevich](https://github.com/KlimYarosh)
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)
---
## Contributing ## Contributing
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick). Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -36,18 +36,16 @@ class DatabaseModule extends Module {
class ApiModule extends Module { class ApiModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<ApiService>().toProvide(() => ApiService( bind<ApiService>()
currentScope.resolve<DatabaseService>() .toProvide(() => ApiService(currentScope.resolve<DatabaseService>()));
));
} }
} }
class UserModule extends Module { class UserModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService( bind<UserService>()
currentScope.resolve<ApiService>() .toProvide(() => UserService(currentScope.resolve<ApiService>()));
));
} }
} }
@@ -65,18 +63,16 @@ class CircularServiceB {
class CircularModuleA extends Module { class CircularModuleA extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<CircularServiceA>().toProvide(() => CircularServiceA( bind<CircularServiceA>().toProvide(
currentScope.resolve<CircularServiceB>() () => CircularServiceA(currentScope.resolve<CircularServiceB>()));
));
} }
} }
class CircularModuleB extends Module { class CircularModuleB extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<CircularServiceB>().toProvide(() => CircularServiceB( bind<CircularServiceB>().toProvide(
currentScope.resolve<CircularServiceA>() () => CircularServiceB(currentScope.resolve<CircularServiceA>()));
));
} }
} }
@@ -87,11 +83,13 @@ void main() {
print('1. Globally enable cycle detection:'); print('1. Globally enable cycle detection:');
CherryPick.enableGlobalCycleDetection(); CherryPick.enableGlobalCycleDetection();
print('✅ Global cycle detection enabled: ${CherryPick.isGlobalCycleDetectionEnabled}'); print(
'✅ Global cycle detection enabled: ${CherryPick.isGlobalCycleDetectionEnabled}');
// All new scopes will automatically have cycle detection enabled // All new scopes will automatically have cycle detection enabled
final globalScope = CherryPick.openRootScope(); final globalScope = CherryPick.openRootScope();
print('✅ Root scope has cycle detection enabled: ${globalScope.isCycleDetectionEnabled}'); print(
'✅ Root scope has cycle detection enabled: ${globalScope.isCycleDetectionEnabled}');
// Install modules without circular dependencies // Install modules without circular dependencies
globalScope.installModules([ globalScope.installModules([
@@ -112,7 +110,8 @@ void main() {
// Создаем безопасный скоуп (с автоматически включенным обнаружением) // Создаем безопасный скоуп (с автоматически включенным обнаружением)
final safeScope = CherryPick.openSafeRootScope(); final safeScope = CherryPick.openSafeRootScope();
print('✅ Safe scope created with cycle detection: ${safeScope.isCycleDetectionEnabled}'); print(
'✅ Safe scope created with cycle detection: ${safeScope.isCycleDetectionEnabled}');
safeScope.installModules([ safeScope.installModules([
DatabaseModule(), DatabaseModule(),
@@ -153,30 +152,37 @@ void main() {
// Создаем скоуп без обнаружения // Создаем скоуп без обнаружения
// ignore: unused_local_variable // ignore: unused_local_variable
final specificScope = CherryPick.openRootScope(); final specificScope = CherryPick.openRootScope();
print(' Detection in root scope: ${CherryPick.isCycleDetectionEnabledForScope()}'); print(
' Detection in root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
// Включаем обнаружение для конкретного скоупа // Включаем обнаружение для конкретного скоупа
CherryPick.enableCycleDetectionForScope(); CherryPick.enableCycleDetectionForScope();
print('✅ Detection enabled for root scope: ${CherryPick.isCycleDetectionEnabledForScope()}'); print(
'✅ Detection enabled for root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
// Создаем дочерний скоуп // Создаем дочерний скоуп
// ignore: unused_local_variable // ignore: unused_local_variable
final featureScope = CherryPick.openScope(scopeName: 'feature.auth'); final featureScope = CherryPick.openScope(scopeName: 'feature.auth');
print(' Detection in feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}'); print(
' Detection in feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}');
// Включаем обнаружение для дочернего скоупа // Включаем обнаружение для дочернего скоупа
CherryPick.enableCycleDetectionForScope(scopeName: 'feature.auth'); CherryPick.enableCycleDetectionForScope(scopeName: 'feature.auth');
print('✅ Detection enabled for feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}'); print(
'✅ Detection enabled for feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}');
print(''); print('');
// Example 5: Creating safe child scopes // Example 5: Creating safe child scopes
print('5. Creating safe child scopes:'); print('5. Creating safe child scopes:');
final safeFeatureScope = CherryPick.openSafeScope(scopeName: 'feature.payments'); final safeFeatureScope =
print('✅ Safe feature scope created: ${safeFeatureScope.isCycleDetectionEnabled}'); CherryPick.openSafeScope(scopeName: 'feature.payments');
print(
'✅ Safe feature scope created: ${safeFeatureScope.isCycleDetectionEnabled}');
// You can create a complex hierarchy of scopes // You can create a complex hierarchy of scopes
final complexScope = CherryPick.openSafeScope(scopeName: 'app.feature.auth.login'); final complexScope =
CherryPick.openSafeScope(scopeName: 'app.feature.auth.login');
print('✅ Complex scope created: ${complexScope.isCycleDetectionEnabled}'); print('✅ Complex scope created: ${complexScope.isCycleDetectionEnabled}');
print(''); print('');
@@ -209,7 +215,8 @@ void main() {
print(''); print('');
print('🚀 Production mode:'); print('🚀 Production mode:');
print(' CherryPick.disableGlobalCycleDetection(); // Disable for performance'); print(
' CherryPick.disableGlobalCycleDetection(); // Disable for performance');
print(' final scope = CherryPick.openRootScope(); // Regular scope'); print(' final scope = CherryPick.openRootScope(); // Regular scope');
print(''); print('');
@@ -219,7 +226,8 @@ void main() {
print(''); print('');
print('🎯 Feature-specific:'); print('🎯 Feature-specific:');
print(' CherryPick.enableCycleDetectionForScope(scopeName: "feature.critical");'); print(
' CherryPick.enableCycleDetectionForScope(scopeName: "feature.critical");');
print(' // Enable only for critical features'); print(' // Enable only for critical features');
// Cleanup // Cleanup

View File

@@ -29,18 +29,16 @@ class OrderService {
class UserModule extends Module { class UserModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService( bind<UserService>()
currentScope.resolve<OrderService>() .toProvide(() => UserService(currentScope.resolve<OrderService>()));
));
} }
} }
class OrderModule extends Module { class OrderModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<OrderService>().toProvide(() => OrderService( bind<OrderService>()
currentScope.resolve<UserService>() .toProvide(() => OrderService(currentScope.resolve<UserService>()));
));
} }
} }
@@ -103,9 +101,8 @@ class ImprovedUserModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<UserRepository>().singleton().toProvide(() => UserRepository()); bind<UserRepository>().singleton().toProvide(() => UserRepository());
bind<ImprovedUserService>().toProvide(() => ImprovedUserService( bind<ImprovedUserService>().toProvide(
currentScope.resolve<UserRepository>() () => ImprovedUserService(currentScope.resolve<UserRepository>()));
));
} }
} }
@@ -115,8 +112,7 @@ class ImprovedOrderModule extends Module {
bind<OrderRepository>().singleton().toProvide(() => OrderRepository()); bind<OrderRepository>().singleton().toProvide(() => OrderRepository());
bind<ImprovedOrderService>().toProvide(() => ImprovedOrderService( bind<ImprovedOrderService>().toProvide(() => ImprovedOrderService(
currentScope.resolve<OrderRepository>(), currentScope.resolve<OrderRepository>(),
currentScope.resolve<ImprovedUserService>() currentScope.resolve<ImprovedUserService>()));
));
} }
} }
@@ -127,7 +123,8 @@ void main() {
print('1. Attempt to create a scope with circular dependencies:'); print('1. Attempt to create a scope with circular dependencies:');
try { try {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
scope.enableCycleDetection(); // Включаем обнаружение циклических зависимостей scope
.enableCycleDetection(); // Включаем обнаружение циклических зависимостей
scope.installModules([ scope.installModules([
UserModule(), UserModule(),
@@ -144,6 +141,8 @@ void main() {
// Example 2: Without circular dependency detection (dangerous!) // Example 2: Without circular dependency detection (dangerous!)
print('2. Same code without circular dependency detection:'); print('2. Same code without circular dependency detection:');
try { try {
CherryPick.disableGlobalCrossScopeCycleDetection();
CherryPick.disableGlobalCycleDetection();
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
// НЕ включаем обнаружение циклических зависимостей // НЕ включаем обнаружение циклических зависимостей
@@ -184,7 +183,6 @@ void main() {
orderService.createOrder('ORD-001', 'John'); orderService.createOrder('ORD-001', 'John');
final orders = orderService.getOrdersForUser('John'); final orders = orderService.getOrdersForUser('John');
print('✅ Orders for user John: $orders'); print('✅ Orders for user John: $orders');
} catch (e) { } catch (e) {
print('❌ Error: $e'); print('❌ Error: $e');
} }

View File

@@ -14,6 +14,14 @@ class MyService implements Disposable {
void doSomething() => print('Doing something...'); void doSomething() => print('Doing something...');
} }
/// Пример модуля CherryPick
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}
void main() { void main() {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
@@ -30,11 +38,3 @@ void main() {
scope.dispose(); scope.dispose();
print('Service wasDisposed = ${service.wasDisposed}'); // true print('Service wasDisposed = ${service.wasDisposed}'); // true
} }
/// Пример модуля CherryPick
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}

View File

@@ -4,7 +4,7 @@ homepage: localhost
publish_to: none publish_to: none
environment: environment:
sdk: ">=2.12.0 <3.0.0" sdk: '>=3.2.0 <4.0.0'
dependencies: dependencies:

Binary file not shown.

View File

@@ -77,7 +77,8 @@ class CycleDetector {
); );
if (_resolutionStack.contains(dependencyKey)) { if (_resolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey); final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey); final cycle = _resolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
_observer.onCycleDetected(cycle); _observer.onCycleDetected(cycle);
_observer.onError('Cycle detected for $dependencyKey', null, null); _observer.onError('Cycle detected for $dependencyKey', null, null);
throw CircularDependencyException( throw CircularDependencyException(
@@ -99,7 +100,8 @@ class CycleDetector {
); );
_resolutionStack.remove(dependencyKey); _resolutionStack.remove(dependencyKey);
// Only remove from history if it's the last one // Only remove from history if it's the last one
if (_resolutionHistory.isNotEmpty && _resolutionHistory.last == dependencyKey) { if (_resolutionHistory.isNotEmpty &&
_resolutionHistory.last == dependencyKey) {
_resolutionHistory.removeLast(); _resolutionHistory.removeLast();
} }
} }
@@ -124,7 +126,8 @@ class CycleDetector {
} }
/// Gets the current dependency resolution chain (for diagnostics or debugging). /// Gets the current dependency resolution chain (for diagnostics or debugging).
List<String> get currentResolutionChain => List.unmodifiable(_resolutionHistory); List<String> get currentResolutionChain =>
List.unmodifiable(_resolutionHistory);
/// Returns a unique string key for type [T] (+name). /// Returns a unique string key for type [T] (+name).
String _createDependencyKey<T>(String? named) { String _createDependencyKey<T>(String? named) {
@@ -205,7 +208,8 @@ mixin CycleDetectionMixin {
: dependencyType.toString(); : dependencyType.toString();
if (_cycleDetector!._resolutionStack.contains(dependencyKey)) { if (_cycleDetector!._resolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey); final cycleStartIndex =
_cycleDetector!._resolutionHistory.indexOf(dependencyKey);
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex) final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey); ..add(dependencyKey);
observer.onCycleDetected(cycle); observer.onCycleDetected(cycle);

View File

@@ -14,7 +14,6 @@
import 'dart:collection'; import 'dart:collection';
import 'package:cherrypick/cherrypick.dart'; import 'package:cherrypick/cherrypick.dart';
/// GlobalCycleDetector detects and prevents circular dependencies across an entire DI scope hierarchy. /// GlobalCycleDetector detects and prevents circular dependencies across an entire DI scope hierarchy.
/// ///
/// This is particularly important for modular/feature-based applications /// This is particularly important for modular/feature-based applications
@@ -45,13 +44,16 @@ class GlobalCycleDetector {
final List<String> _globalResolutionHistory = []; final List<String> _globalResolutionHistory = [];
// Map of active detectors for subscopes (rarely used directly) // Map of active detectors for subscopes (rarely used directly)
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>(); final Map<String, CycleDetector> _scopeDetectors =
HashMap<String, CycleDetector>();
GlobalCycleDetector._internal({required CherryPickObserver observer}): _observer = observer; GlobalCycleDetector._internal({required CherryPickObserver observer})
: _observer = observer;
/// Returns the singleton global detector instance, initializing it if needed. /// Returns the singleton global detector instance, initializing it if needed.
static GlobalCycleDetector get instance { static GlobalCycleDetector get instance {
_instance ??= GlobalCycleDetector._internal(observer: CherryPick.globalObserver); _instance ??=
GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
return _instance!; return _instance!;
} }
@@ -70,9 +72,11 @@ class GlobalCycleDetector {
if (_globalResolutionStack.contains(dependencyKey)) { if (_globalResolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey); final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey); final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
_observer.onCycleDetected(cycle, scopeName: scopeId); _observer.onCycleDetected(cycle, scopeName: scopeId);
_observer.onError('Global circular dependency detected for $dependencyKey', null, null); _observer.onError(
'Global circular dependency detected for $dependencyKey', null, null);
throw CircularDependencyException( throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey', 'Global circular dependency detected for $dependencyKey',
cycle, cycle,
@@ -88,7 +92,8 @@ class GlobalCycleDetector {
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId); final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
_globalResolutionStack.remove(dependencyKey); _globalResolutionStack.remove(dependencyKey);
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) { if (_globalResolutionHistory.isNotEmpty &&
_globalResolutionHistory.last == dependencyKey) {
_globalResolutionHistory.removeLast(); _globalResolutionHistory.removeLast();
} }
} }
@@ -101,13 +106,16 @@ class GlobalCycleDetector {
String? scopeId, String? scopeId,
T Function() action, T Function() action,
) { ) {
final dependencyKey = _createDependencyKeyFromType(dependencyType, named, scopeId); final dependencyKey =
_createDependencyKeyFromType(dependencyType, named, scopeId);
if (_globalResolutionStack.contains(dependencyKey)) { if (_globalResolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey); final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey); final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
_observer.onCycleDetected(cycle, scopeName: scopeId); _observer.onCycleDetected(cycle, scopeName: scopeId);
_observer.onError('Global circular dependency detected for $dependencyKey', null, null); _observer.onError(
'Global circular dependency detected for $dependencyKey', null, null);
throw CircularDependencyException( throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey', 'Global circular dependency detected for $dependencyKey',
cycle, cycle,
@@ -121,7 +129,8 @@ class GlobalCycleDetector {
return action(); return action();
} finally { } finally {
_globalResolutionStack.remove(dependencyKey); _globalResolutionStack.remove(dependencyKey);
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) { if (_globalResolutionHistory.isNotEmpty &&
_globalResolutionHistory.last == dependencyKey) {
_globalResolutionHistory.removeLast(); _globalResolutionHistory.removeLast();
} }
} }
@@ -129,7 +138,8 @@ class GlobalCycleDetector {
/// Get per-scope detector (not usually needed by consumers). /// Get per-scope detector (not usually needed by consumers).
CycleDetector getScopeDetector(String scopeId) { CycleDetector getScopeDetector(String scopeId) {
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(observer: CherryPick.globalObserver)); return _scopeDetectors.putIfAbsent(
scopeId, () => CycleDetector(observer: CherryPick.globalObserver));
} }
/// Remove detector for a given scope. /// Remove detector for a given scope.
@@ -144,7 +154,8 @@ class GlobalCycleDetector {
} }
/// Get current global dependency resolution chain (for debugging or diagnostics). /// Get current global dependency resolution chain (for debugging or diagnostics).
List<String> get globalResolutionChain => List.unmodifiable(_globalResolutionHistory); List<String> get globalResolutionChain =>
List.unmodifiable(_globalResolutionHistory);
/// Clears all global and per-scope state in this detector. /// Clears all global and per-scope state in this detector.
void clear() { void clear() {
@@ -157,7 +168,8 @@ class GlobalCycleDetector {
void _detectorClear(detector) => detector.clear(); void _detectorClear(detector) => detector.clear();
/// Creates a unique dependency key string including scope and name (for diagnostics/cycle checks). /// Creates a unique dependency key string including scope and name (for diagnostics/cycle checks).
String _createDependencyKeyFromType(Type type, String? named, String? scopeId) { String _createDependencyKeyFromType(
Type type, String? named, String? scopeId) {
final typeName = type.toString(); final typeName = type.toString();
final namePrefix = named != null ? '@$named' : ''; final namePrefix = named != null ? '@$named' : '';
final scopePrefix = scopeId != null ? '[$scopeId]' : ''; final scopePrefix = scopeId != null ? '[$scopeId]' : '';

View File

@@ -16,7 +16,6 @@ import 'package:cherrypick/src/global_cycle_detector.dart';
import 'package:cherrypick/src/observer.dart'; import 'package:cherrypick/src/observer.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
Scope? _rootScope; Scope? _rootScope;
/// Global logger for all [Scope]s managed by [CherryPick]. /// Global logger for all [Scope]s managed by [CherryPick].
@@ -80,7 +79,8 @@ class CherryPick {
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) { if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
_rootScope!.enableCycleDetection(); _rootScope!.enableCycleDetection();
} }
if (_globalCrossScopeCycleDetectionEnabled && !_rootScope!.isGlobalCycleDetectionEnabled) { if (_globalCrossScopeCycleDetectionEnabled &&
!_rootScope!.isGlobalCycleDetectionEnabled) {
_rootScope!.enableGlobalCycleDetection(); _rootScope!.enableGlobalCycleDetection();
} }
return _rootScope!; return _rootScope!;
@@ -96,7 +96,8 @@ class CherryPick {
/// ``` /// ```
static Future<void> closeRootScope() async { static Future<void> closeRootScope() async {
if (_rootScope != null) { if (_rootScope != null) {
await _rootScope!.dispose(); // Автоматический вызов dispose для rootScope! await _rootScope!
.dispose(); // Автоматический вызов dispose для rootScope!
_rootScope = null; _rootScope = null;
} }
} }
@@ -141,13 +142,15 @@ class CherryPick {
/// ```dart /// ```dart
/// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature'); /// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature');
/// ``` /// ```
static void enableCycleDetectionForScope({String scopeName = '', String separator = '.'}) { static void enableCycleDetectionForScope(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator); final scope = _getScope(scopeName, separator);
scope.enableCycleDetection(); scope.enableCycleDetection();
} }
/// Disables cycle detection for a given scope. See [enableCycleDetectionForScope]. /// Disables cycle detection for a given scope. See [enableCycleDetectionForScope].
static void disableCycleDetectionForScope({String scopeName = '', String separator = '.'}) { static void disableCycleDetectionForScope(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator); final scope = _getScope(scopeName, separator);
scope.disableCycleDetection(); scope.disableCycleDetection();
} }
@@ -158,7 +161,8 @@ class CherryPick {
/// ```dart /// ```dart
/// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api'); /// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api');
/// ``` /// ```
static bool isCycleDetectionEnabledForScope({String scopeName = '', String separator = '.'}) { static bool isCycleDetectionEnabledForScope(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator); final scope = _getScope(scopeName, separator);
return scope.isCycleDetectionEnabled; return scope.isCycleDetectionEnabled;
} }
@@ -171,7 +175,8 @@ class CherryPick {
/// ```dart /// ```dart
/// print(CherryPick.getCurrentResolutionChain(scopeName: 'feature.api')); /// print(CherryPick.getCurrentResolutionChain(scopeName: 'feature.api'));
/// ``` /// ```
static List<String> getCurrentResolutionChain({String scopeName = '', String separator = '.'}) { static List<String> getCurrentResolutionChain(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator); final scope = _getScope(scopeName, separator);
return scope.currentResolutionChain; return scope.currentResolutionChain;
} }
@@ -229,14 +234,13 @@ class CherryPick {
if (nameParts.isEmpty) { if (nameParts.isEmpty) {
throw Exception('Can not open sub scope because scopeName can not split'); throw Exception('Can not open sub scope because scopeName can not split');
} }
final scope = nameParts.fold( final scope = nameParts.fold(openRootScope(),
openRootScope(), (Scope previous, String element) => previous.openSubScope(element));
(Scope previous, String element) => previous.openSubScope(element)
);
if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) { if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) {
scope.enableCycleDetection(); scope.enableCycleDetection();
} }
if (_globalCrossScopeCycleDetectionEnabled && !scope.isGlobalCycleDetectionEnabled) { if (_globalCrossScopeCycleDetectionEnabled &&
!scope.isGlobalCycleDetectionEnabled) {
scope.enableGlobalCycleDetection(); scope.enableGlobalCycleDetection();
} }
return scope; return scope;
@@ -252,21 +256,21 @@ class CherryPick {
/// CherryPick.closeScope(scopeName: 'network.super.api'); /// CherryPick.closeScope(scopeName: 'network.super.api');
/// ``` /// ```
@experimental @experimental
static Future<void> closeScope({String scopeName = '', String separator = '.'}) async { static Future<void> closeScope(
{String scopeName = '', String separator = '.'}) async {
if (scopeName.isEmpty) { if (scopeName.isEmpty) {
await closeRootScope(); await closeRootScope();
return; return;
} }
final nameParts = scopeName.split(separator); final nameParts = scopeName.split(separator);
if (nameParts.isEmpty) { if (nameParts.isEmpty) {
throw Exception('Can not close sub scope because scopeName can not split'); throw Exception(
'Can not close sub scope because scopeName can not split');
} }
if (nameParts.length > 1) { if (nameParts.length > 1) {
final lastPart = nameParts.removeLast(); final lastPart = nameParts.removeLast();
final scope = nameParts.fold( final scope = nameParts.fold(openRootScope(),
openRootScope(), (Scope previous, String element) => previous.openSubScope(element));
(Scope previous, String element) => previous.openSubScope(element)
);
await scope.closeSubScope(lastPart); await scope.closeSubScope(lastPart);
} else { } else {
await openRootScope().closeSubScope(nameParts.first); await openRootScope().closeSubScope(nameParts.first);
@@ -316,7 +320,8 @@ class CherryPick {
/// print('Global cross-scope detection is ON'); /// print('Global cross-scope detection is ON');
/// } /// }
/// ``` /// ```
static bool get isGlobalCrossScopeCycleDetectionEnabled => _globalCrossScopeCycleDetectionEnabled; static bool get isGlobalCrossScopeCycleDetectionEnabled =>
_globalCrossScopeCycleDetectionEnabled;
/// Returns the current global dependency resolution chain (across all scopes). /// Returns the current global dependency resolution chain (across all scopes).
/// ///
@@ -367,7 +372,8 @@ class CherryPick {
/// ```dart /// ```dart
/// final featureScope = CherryPick.openGlobalSafeScope(scopeName: 'featureA.api'); /// final featureScope = CherryPick.openGlobalSafeScope(scopeName: 'featureA.api');
/// ``` /// ```
static Scope openGlobalSafeScope({String scopeName = '', String separator = '.'}) { static Scope openGlobalSafeScope(
{String scopeName = '', String separator = '.'}) {
final scope = openScope(scopeName: scopeName, separator: separator); final scope = openScope(scopeName: scopeName, separator: separator);
scope.enableCycleDetection(); scope.enableCycleDetection();
scope.enableGlobalCycleDetection(); scope.enableGlobalCycleDetection();

View File

@@ -49,7 +49,8 @@ abstract class CherryPickObserver {
/// ```dart /// ```dart
/// observer.onInstanceCreated('MyService', MyService, instance, scopeName: 'root'); /// observer.onInstanceCreated('MyService', MyService, instance, scopeName: 'root');
/// ``` /// ```
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}); void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName});
/// Called when an instance is disposed (removed from cache and/or finalized). /// Called when an instance is disposed (removed from cache and/or finalized).
/// ///
@@ -57,7 +58,8 @@ abstract class CherryPickObserver {
/// ```dart /// ```dart
/// observer.onInstanceDisposed('MyService', MyService, instance, scopeName: 'root'); /// observer.onInstanceDisposed('MyService', MyService, instance, scopeName: 'root');
/// ``` /// ```
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}); void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName});
// === Module events === // === Module events ===
/// Called when modules are installed into the container. /// Called when modules are installed into the container.
@@ -157,19 +159,23 @@ class PrintCherryPickObserver implements CherryPickObserver {
print('[request][CherryPick] $name$type (scope: $scopeName)'); print('[request][CherryPick] $name$type (scope: $scopeName)');
@override @override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) => void onInstanceCreated(String name, Type type, Object instance,
print('[create][CherryPick] $name$type => $instance (scope: $scopeName)'); {String? scopeName}) =>
print(
'[create][CherryPick] $name$type => $instance (scope: $scopeName)');
@override @override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) => void onInstanceDisposed(String name, Type type, Object instance,
print('[dispose][CherryPick] $name$type => $instance (scope: $scopeName)'); {String? scopeName}) =>
print(
'[dispose][CherryPick] $name$type => $instance (scope: $scopeName)');
@override @override
void onModulesInstalled(List<String> modules, {String? scopeName}) => void onModulesInstalled(List<String> modules, {String? scopeName}) => print(
print('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)'); '[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
@override @override
void onModulesRemoved(List<String> modules, {String? scopeName}) => void onModulesRemoved(List<String> modules, {String? scopeName}) => print(
print('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)'); '[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
@override @override
void onScopeOpened(String name) => print('[scope opened][CherryPick] $name'); void onScopeOpened(String name) => print('[scope opened][CherryPick] $name');
@@ -178,8 +184,8 @@ class PrintCherryPickObserver implements CherryPickObserver {
void onScopeClosed(String name) => print('[scope closed][CherryPick] $name'); void onScopeClosed(String name) => print('[scope closed][CherryPick] $name');
@override @override
void onCycleDetected(List<String> chain, {String? scopeName}) => void onCycleDetected(List<String> chain, {String? scopeName}) => print(
print('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}'); '[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
@override @override
void onCacheHit(String name, Type type, {String? scopeName}) => void onCacheHit(String name, Type type, {String? scopeName}) =>
@@ -210,9 +216,11 @@ class SilentCherryPickObserver implements CherryPickObserver {
@override @override
void onInstanceRequested(String name, Type type, {String? scopeName}) {} void onInstanceRequested(String name, Type type, {String? scopeName}) {}
@override @override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {} void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) {}
@override @override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {} void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) {}
@override @override
void onModulesInstalled(List<String> modules, {String? scopeName}) {} void onModulesInstalled(List<String> modules, {String? scopeName}) {}
@override @override

View File

@@ -68,7 +68,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
final Map<String, Scope> _scopeMap = HashMap(); final Map<String, Scope> _scopeMap = HashMap();
Scope(this._parentScope, {required CherryPickObserver observer}) : _observer = observer { Scope(this._parentScope, {required CherryPickObserver observer})
: _observer = observer {
setScopeId(_generateScopeId()); setScopeId(_generateScopeId());
observer.onScopeOpened(scopeId ?? 'NO_ID'); observer.onScopeOpened(scopeId ?? 'NO_ID');
observer.onDiagnostic( observer.onDiagnostic(
@@ -87,7 +88,6 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
// индекс для мгновенного поиска bindingов // индекс для мгновенного поиска bindingов
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {}; final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
/// Generates a unique identifier string for this scope instance. /// Generates a unique identifier string for this scope instance.
/// ///
/// Used internally for diagnostics, logging and global scope tracking. /// Used internally for diagnostics, logging and global scope tracking.
@@ -280,7 +280,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
return withCycleDetection<T>(T, named, () { return withCycleDetection<T>(T, named, () {
var resolved = _tryResolveInternal<T>(named: named, params: params); var resolved = _tryResolveInternal<T>(named: named, params: params);
if (resolved != null) { if (resolved != null) {
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId); observer.onInstanceCreated(T.toString(), T, resolved,
scopeName: scopeId);
observer.onDiagnostic( observer.onDiagnostic(
'Successfully resolved: $T', 'Successfully resolved: $T',
details: { details: {
@@ -360,10 +361,12 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
T result; T result;
if (isGlobalCycleDetectionEnabled) { if (isGlobalCycleDetectionEnabled) {
result = await withGlobalCycleDetection<Future<T>>(T, named, () async { result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params); return await _resolveAsyncWithLocalDetection<T>(
named: named, params: params);
}); });
} else { } else {
result = await _resolveAsyncWithLocalDetection<T>(named: named, params: params); result = await _resolveAsyncWithLocalDetection<T>(
named: named, params: params);
} }
_trackDisposable(result); _trackDisposable(result);
return result; return result;
@@ -371,11 +374,14 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
/// Resolves [T] asynchronously using local cycle detector. Throws if not found. /// Resolves [T] asynchronously using local cycle detector. Throws if not found.
/// Internal implementation for async [resolveAsync]. /// Internal implementation for async [resolveAsync].
Future<T> _resolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async { Future<T> _resolveAsyncWithLocalDetection<T>(
{String? named, dynamic params}) async {
return withCycleDetection<Future<T>>(T, named, () async { return withCycleDetection<Future<T>>(T, named, () async {
var resolved = await _tryResolveAsyncInternal<T>(named: named, params: params); var resolved =
await _tryResolveAsyncInternal<T>(named: named, params: params);
if (resolved != null) { if (resolved != null) {
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId); observer.onInstanceCreated(T.toString(), T, resolved,
scopeName: scopeId);
observer.onDiagnostic( observer.onDiagnostic(
'Successfully async resolved: $T', 'Successfully async resolved: $T',
details: { details: {
@@ -410,10 +416,12 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
T? result; T? result;
if (isGlobalCycleDetectionEnabled) { if (isGlobalCycleDetectionEnabled) {
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async { result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params); return await _tryResolveAsyncWithLocalDetection<T>(
named: named, params: params);
}); });
} else { } else {
result = await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params); result = await _tryResolveAsyncWithLocalDetection<T>(
named: named, params: params);
} }
if (result != null) _trackDisposable(result); if (result != null) _trackDisposable(result);
return result; return result;
@@ -421,7 +429,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
/// Attempts to resolve [T] asynchronously using local cycle detector. Returns null if missing. /// Attempts to resolve [T] asynchronously using local cycle detector. Returns null if missing.
/// Internal implementation for async [tryResolveAsync]. /// Internal implementation for async [tryResolveAsync].
Future<T?> _tryResolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async { Future<T?> _tryResolveAsyncWithLocalDetection<T>(
{String? named, dynamic params}) async {
if (isCycleDetectionEnabled) { if (isCycleDetectionEnabled) {
return withCycleDetection<Future<T?>>(T, named, () async { return withCycleDetection<Future<T?>>(T, named, () async {
return await _tryResolveAsyncInternal<T>(named: named, params: params); return await _tryResolveAsyncInternal<T>(named: named, params: params);
@@ -432,7 +441,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
} }
/// Direct async resolution for [T] without cycle check. Returns null if missing. Internal use only. /// Direct async resolution for [T] without cycle check. Returns null if missing. Internal use only.
Future<T?> _tryResolveAsyncInternal<T>({String? named, dynamic params}) async { Future<T?> _tryResolveAsyncInternal<T>(
{String? named, dynamic params}) async {
final resolver = _findBindingResolver<T>(named); final resolver = _findBindingResolver<T>(named);
// 1 - Try from own modules; 2 - Fallback to parent // 1 - Try from own modules; 2 - Fallback to parent
return resolver?.resolveAsync(params) ?? return resolver?.resolveAsync(params) ??
@@ -476,17 +486,22 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
/// await myScope.dispose(); /// await myScope.dispose();
/// ``` /// ```
Future<void> dispose() async { Future<void> dispose() async {
// First dispose children scopes // Create copies to avoid concurrent modification
for (final subScope in _scopeMap.values) { final scopesCopy = Map<String, Scope>.from(_scopeMap);
for (final subScope in scopesCopy.values) {
await subScope.dispose(); await subScope.dispose();
} }
_scopeMap.clear(); _scopeMap.clear();
// Then dispose own disposables
for (final d in _disposables) { final disposablesCopy = Set<Disposable>.from(_disposables);
try { for (final d in disposablesCopy) {
await d.dispose(); await d.dispose();
} catch (_) {}
} }
_disposables.clear(); _disposables.clear();
// Clear modules
_modulesList.clear();
// Clear binding-index
_bindingResolvers.clear();
} }
} }

View File

@@ -1,8 +1,8 @@
name: cherrypick name: cherrypick
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects. description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
version: 3.0.0-dev.9 version: 3.0.2
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://cherrypick-di.netlify.app
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
topics: topics:
@@ -13,14 +13,14 @@ topics:
- inversion-of-control - inversion-of-control
environment: environment:
sdk: ">=3.5.2 <4.0.0" sdk: '>=3.2.0 <4.0.0'
dependencies: dependencies:
meta: ^1.3.0 meta: ^1.3.0
dev_dependencies: dev_dependencies:
lints: ^5.0.0 lints: ^4.0.0
test: ^1.25.15 test: ^1.25.6
mockito: ^5.0.6 mockito: ^5.4.4
melos: ^6.3.2 melos: ^6.3.2

View File

@@ -0,0 +1,65 @@
import 'dart:async';
import 'package:cherrypick/cherrypick.dart';
import 'package:test/test.dart';
class HeavyService implements Disposable {
static int instanceCount = 0;
HeavyService() {
instanceCount++;
print('HeavyService created. Instance count: '
'\u001b[32m$instanceCount\u001b[0m');
}
@override
void dispose() {
instanceCount--;
print('HeavyService disposed. Instance count: '
'\u001b[31m$instanceCount\u001b[0m');
}
static final Finalizer<String> _finalizer = Finalizer((msg) {
print('GC FINALIZED HeavyService: $msg');
});
void registerFinalizer() => _finalizer.attach(this, toString(), detach: this);
}
class HeavyModule extends Module {
@override
void builder(Scope scope) {
bind<HeavyService>().toProvide(() => HeavyService());
}
}
void main() {
test('Binding memory is cleared after closing and reopening scope', () async {
final root = CherryPick.openRootScope();
for (int i = 0; i < 10; i++) {
print('\nIteration $i -------------------------------');
final subScope = root.openSubScope('leak-test-scope');
subScope.installModules([HeavyModule()]);
final service = subScope.resolve<HeavyService>();
expect(service, isNotNull);
await root.closeSubScope('leak-test-scope');
// Dart GC не сразу удаляет освобождённые объекты, добавляем паузу и вызываем GC.
await Future.delayed(const Duration(milliseconds: 200));
}
// Если dispose не вызвался, instanceCount > 0 => утечка.
expect(HeavyService.instanceCount, equals(0));
});
test('Service is finalized after scope is closed/cleaned', () async {
final root = CherryPick.openRootScope();
HeavyService? ref;
{
final sub = root.openSubScope('s');
sub.installModules([HeavyModule()]);
ref = sub.resolve<HeavyService>();
ref.registerFinalizer();
expect(HeavyService.instanceCount, 1);
await root.closeSubScope('s');
}
await Future.delayed(const Duration(seconds: 2));
expect(HeavyService.instanceCount, 0);
});
}

View File

@@ -12,6 +12,7 @@ class DummyModule extends Module {
} }
class A {} class A {}
class B {} class B {}
class CyclicModule extends Module { class CyclicModule extends Module {
@@ -52,10 +53,13 @@ void main() {
throwsA(isA<CircularDependencyException>()), throwsA(isA<CircularDependencyException>()),
); );
// Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles // Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles
final foundInErrors = observer.errors.any((m) => m.contains('cycle detected')); final foundInErrors =
final foundInDiagnostics = observer.diagnostics.any((m) => m.contains('cycle detected')); observer.errors.any((m) => m.contains('cycle detected'));
final foundInDiagnostics =
observer.diagnostics.any((m) => m.contains('cycle detected'));
final foundCycleNotified = observer.cycles.isNotEmpty; final foundCycleNotified = observer.cycles.isNotEmpty;
expect(foundInErrors || foundInDiagnostics || foundCycleNotified, isTrue, expect(foundInErrors || foundInDiagnostics || foundCycleNotified, isTrue,
reason: 'Ожидаем хотя бы один лог о цикле! errors: ${observer.errors}\ndiag: ${observer.diagnostics}\ncycles: ${observer.cycles}'); reason:
'Ожидаем хотя бы один лог о цикле! errors: ${observer.errors}\ndiag: ${observer.diagnostics}\ncycles: ${observer.cycles}');
}); });
} }

View File

@@ -15,8 +15,7 @@ class MockObserver implements CherryPickObserver {
void onWarning(String message, {Object? details}) => warnings.add(message); void onWarning(String message, {Object? details}) => warnings.add(message);
@override @override
void onError(String message, Object? error, StackTrace? stackTrace) => void onError(String message, Object? error, StackTrace? stackTrace) => errors.add(
errors.add(
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}'); '$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
@override @override
@@ -30,9 +29,11 @@ class MockObserver implements CherryPickObserver {
@override @override
void onInstanceRequested(String name, Type type, {String? scopeName}) {} void onInstanceRequested(String name, Type type, {String? scopeName}) {}
@override @override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {} void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) {}
@override @override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {} void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) {}
@override @override
void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {} void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {}
@override @override

View File

@@ -46,7 +46,9 @@ void main() {
); );
}); });
test('current implementation limitation - may not detect cross-scope cycles', () { test(
'current implementation limitation - may not detect cross-scope cycles',
() {
// Этот тест демонстрирует ограничение текущей реализации // Этот тест демонстрирует ограничение текущей реализации
final parentScope = CherryPick.openRootScope(); final parentScope = CherryPick.openRootScope();
parentScope.enableCycleDetection(); parentScope.enableCycleDetection();

View File

@@ -52,8 +52,7 @@ void main() {
throwsA(predicate((e) => throwsA(predicate((e) =>
e is CircularDependencyException && e is CircularDependencyException &&
e.dependencyChain.contains('String') && e.dependencyChain.contains('String') &&
e.dependencyChain.length > 1 e.dependencyChain.length > 1)),
)),
); );
}); });
@@ -161,14 +160,16 @@ class ServiceB {
class CircularModuleA extends Module { class CircularModuleA extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<ServiceA>().toProvide(() => ServiceA(currentScope.resolve<ServiceB>())); bind<ServiceA>()
.toProvide(() => ServiceA(currentScope.resolve<ServiceB>()));
} }
} }
class CircularModuleB extends Module { class CircularModuleB extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<ServiceB>().toProvide(() => ServiceB(currentScope.resolve<ServiceA>())); bind<ServiceB>()
.toProvide(() => ServiceB(currentScope.resolve<ServiceA>()));
} }
} }

View File

@@ -37,7 +37,9 @@ void main() {
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isFalse); expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isFalse);
}); });
test('should automatically enable global cycle detection for new root scope', () { test(
'should automatically enable global cycle detection for new root scope',
() {
CherryPick.enableGlobalCrossScopeCycleDetection(); CherryPick.enableGlobalCrossScopeCycleDetection();
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
@@ -45,7 +47,9 @@ void main() {
expect(scope.isGlobalCycleDetectionEnabled, isTrue); expect(scope.isGlobalCycleDetectionEnabled, isTrue);
}); });
test('should automatically enable global cycle detection for existing root scope', () { test(
'should automatically enable global cycle detection for existing root scope',
() {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
expect(scope.isGlobalCycleDetectionEnabled, isFalse); expect(scope.isGlobalCycleDetectionEnabled, isFalse);
@@ -56,15 +60,18 @@ void main() {
}); });
group('Global Safe Scope Creation', () { group('Global Safe Scope Creation', () {
test('should create global safe root scope with both detections enabled', () { test('should create global safe root scope with both detections enabled',
() {
final scope = CherryPick.openGlobalSafeRootScope(); final scope = CherryPick.openGlobalSafeRootScope();
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
expect(scope.isGlobalCycleDetectionEnabled, isTrue); expect(scope.isGlobalCycleDetectionEnabled, isTrue);
}); });
test('should create global safe sub-scope with both detections enabled', () { test('should create global safe sub-scope with both detections enabled',
final scope = CherryPick.openGlobalSafeScope(scopeName: 'feature.global'); () {
final scope =
CherryPick.openGlobalSafeScope(scopeName: 'feature.global');
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
expect(scope.isGlobalCycleDetectionEnabled, isTrue); expect(scope.isGlobalCycleDetectionEnabled, isTrue);

View File

@@ -39,7 +39,9 @@ void main() {
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse); expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
}); });
test('should automatically enable cycle detection for new root scope when global is enabled', () { test(
'should automatically enable cycle detection for new root scope when global is enabled',
() {
CherryPick.enableGlobalCycleDetection(); CherryPick.enableGlobalCycleDetection();
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
@@ -47,7 +49,9 @@ void main() {
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
}); });
test('should automatically enable cycle detection for existing root scope when global is enabled', () { test(
'should automatically enable cycle detection for existing root scope when global is enabled',
() {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
expect(scope.isCycleDetectionEnabled, isFalse); expect(scope.isCycleDetectionEnabled, isFalse);
@@ -56,7 +60,9 @@ void main() {
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
}); });
test('should automatically disable cycle detection for existing root scope when global is disabled', () { test(
'should automatically disable cycle detection for existing root scope when global is disabled',
() {
CherryPick.enableGlobalCycleDetection(); CherryPick.enableGlobalCycleDetection();
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
@@ -99,21 +105,25 @@ void main() {
final scopeName = 'feature.auth'; final scopeName = 'feature.auth';
CherryPick.openScope(scopeName: scopeName); CherryPick.openScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse); expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isFalse);
CherryPick.enableCycleDetectionForScope(scopeName: scopeName); CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue); expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isTrue);
}); });
test('should disable cycle detection for specific scope', () { test('should disable cycle detection for specific scope', () {
final scopeName = 'feature.auth'; final scopeName = 'feature.auth';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName); CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue); expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isTrue);
CherryPick.disableCycleDetectionForScope(scopeName: scopeName); CherryPick.disableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse); expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isFalse);
}); });
}); });
@@ -134,14 +144,17 @@ void main() {
// Глобальная настройка отключена // Глобальная настройка отключена
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse); expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
final scope = CherryPick.openSafeScope(scopeName: 'feature.independent'); final scope =
CherryPick.openSafeScope(scopeName: 'feature.independent');
expect(scope.isCycleDetectionEnabled, isTrue); expect(scope.isCycleDetectionEnabled, isTrue);
}); });
}); });
group('Resolution Chain Tracking', () { group('Resolution Chain Tracking', () {
test('should return empty resolution chain for scope without cycle detection', () { test(
'should return empty resolution chain for scope without cycle detection',
() {
CherryPick.openRootScope(); CherryPick.openRootScope();
final chain = CherryPick.getCurrentResolutionChain(); final chain = CherryPick.getCurrentResolutionChain();
@@ -149,7 +162,9 @@ void main() {
expect(chain, isEmpty); expect(chain, isEmpty);
}); });
test('should return empty resolution chain for scope with cycle detection but no active resolution', () { test(
'should return empty resolution chain for scope with cycle detection but no active resolution',
() {
CherryPick.enableCycleDetectionForScope(); CherryPick.enableCycleDetectionForScope();
final chain = CherryPick.getCurrentResolutionChain(); final chain = CherryPick.getCurrentResolutionChain();
@@ -161,14 +176,17 @@ void main() {
final scopeName = 'feature.tracking'; final scopeName = 'feature.tracking';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName); CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
final chain = CherryPick.getCurrentResolutionChain(scopeName: scopeName); final chain =
CherryPick.getCurrentResolutionChain(scopeName: scopeName);
expect(chain, isEmpty); // Пустая, так как нет активного разрешения expect(chain, isEmpty); // Пустая, так как нет активного разрешения
}); });
}); });
group('Integration with Circular Dependencies', () { group('Integration with Circular Dependencies', () {
test('should detect circular dependency with global cycle detection enabled', () { test(
'should detect circular dependency with global cycle detection enabled',
() {
CherryPick.enableGlobalCycleDetection(); CherryPick.enableGlobalCycleDetection();
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
@@ -190,7 +208,9 @@ void main() {
); );
}); });
test('should not detect circular dependency when cycle detection is disabled', () { test(
'should not detect circular dependency when cycle detection is disabled',
() {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
scope.installModules([CircularTestModule()]); scope.installModules([CircularTestModule()]);
@@ -205,7 +225,8 @@ void main() {
test('should handle empty scope name as root scope', () { test('should handle empty scope name as root scope', () {
CherryPick.enableCycleDetectionForScope(scopeName: ''); CherryPick.enableCycleDetectionForScope(scopeName: '');
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: ''), isTrue); expect(
CherryPick.isCycleDetectionEnabledForScope(scopeName: ''), isTrue);
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue); expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
}); });
@@ -213,14 +234,21 @@ void main() {
final complexScopeName = 'app.feature.auth.login'; final complexScopeName = 'app.feature.auth.login';
CherryPick.enableCycleDetectionForScope(scopeName: complexScopeName); CherryPick.enableCycleDetectionForScope(scopeName: complexScopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: complexScopeName), isTrue); expect(
CherryPick.isCycleDetectionEnabledForScope(
scopeName: complexScopeName),
isTrue);
}); });
test('should handle custom separator', () { test('should handle custom separator', () {
final scopeName = 'app/feature/auth'; final scopeName = 'app/feature/auth';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName, separator: '/'); CherryPick.enableCycleDetectionForScope(
scopeName: scopeName, separator: '/');
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName, separator: '/'), isTrue); expect(
CherryPick.isCycleDetectionEnabledForScope(
scopeName: scopeName, separator: '/'),
isTrue);
}); });
}); });
}); });
@@ -240,7 +268,9 @@ class CircularServiceB {
class CircularTestModule extends Module { class CircularTestModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<CircularServiceA>().toProvide(() => CircularServiceA(currentScope.resolve<CircularServiceB>())); bind<CircularServiceA>().toProvide(
bind<CircularServiceB>().toProvide(() => CircularServiceB(currentScope.resolve<CircularServiceA>())); () => CircularServiceA(currentScope.resolve<CircularServiceB>()));
bind<CircularServiceB>().toProvide(
() => CircularServiceB(currentScope.resolve<CircularServiceA>()));
} }
} }

View File

@@ -1,4 +1,5 @@
import 'package:cherrypick/cherrypick.dart' show Disposable, Module, Scope, CherryPick; import 'package:cherrypick/cherrypick.dart'
show Disposable, Module, Scope, CherryPick;
import 'dart:async'; import 'dart:async';
import 'package:test/test.dart'; import 'package:test/test.dart';
import '../mock_logger.dart'; import '../mock_logger.dart';
@@ -18,7 +19,9 @@ class AsyncExampleDisposable implements Disposable {
class AsyncExampleModule extends Module { class AsyncExampleModule extends Module {
@override @override
void builder(Scope scope) { void builder(Scope scope) {
bind<AsyncExampleDisposable>().toProvide(() => AsyncExampleDisposable()).singleton(); bind<AsyncExampleDisposable>()
.toProvide(() => AsyncExampleDisposable())
.singleton();
} }
} }
@@ -49,7 +52,9 @@ class CountingDisposable implements Disposable {
class ModuleCountingDisposable extends Module { class ModuleCountingDisposable extends Module {
@override @override
void builder(Scope scope) { void builder(Scope scope) {
bind<CountingDisposable>().toProvide(() => CountingDisposable()).singleton(); bind<CountingDisposable>()
.toProvide(() => CountingDisposable())
.singleton();
} }
} }
@@ -99,8 +104,7 @@ class AsyncModule extends Module {
.toProvideAsync(() async { .toProvideAsync(() async {
await Future.delayed(Duration(milliseconds: 10)); await Future.delayed(Duration(milliseconds: 10));
return AsyncCreatedDisposable(); return AsyncCreatedDisposable();
}) }).singleton();
.singleton();
} }
} }
@@ -119,7 +123,8 @@ void main() {
final scope = Scope(null, observer: observer); final scope = Scope(null, observer: observer);
expect(Scope(scope, observer: observer), isNotNull); // эквивалент expect(Scope(scope, observer: observer), isNotNull); // эквивалент
}); });
test('closeSubScope removes subscope so next openSubScope returns new', () async { test('closeSubScope removes subscope so next openSubScope returns new',
() async {
final observer = MockObserver(); final observer = MockObserver();
final scope = Scope(null, observer: observer); final scope = Scope(null, observer: observer);
final subScope = scope.openSubScope("child"); final subScope = scope.openSubScope("child");
@@ -181,7 +186,8 @@ void main() {
}); });
test("After dropModules resolves fail", () { test("After dropModules resolves fail", () {
final observer = MockObserver(); final observer = MockObserver();
final scope = Scope(null, observer: observer)..installModules([TestModule<int>(value: 5)]); final scope = Scope(null, observer: observer)
..installModules([TestModule<int>(value: 5)]);
expect(scope.resolve<int>(), 5); expect(scope.resolve<int>(), 5);
scope.dropModules(); scope.dropModules();
expect(() => scope.resolve<int>(), throwsA(isA<StateError>())); expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
@@ -294,7 +300,8 @@ void main() {
await scope.dispose(); await scope.dispose();
expect(t.disposed, isTrue); expect(t.disposed, isTrue);
}); });
test('scope.disposeAsync calls dispose on all unique disposables', () async { test('scope.disposeAsync calls dispose on all unique disposables',
() async {
final scope = Scope(null, observer: MockObserver()); final scope = Scope(null, observer: MockObserver());
scope.installModules([ModuleWithDisposable()]); scope.installModules([ModuleWithDisposable()]);
final t1 = scope.resolve<TestDisposable>(); final t1 = scope.resolve<TestDisposable>();
@@ -305,7 +312,8 @@ void main() {
expect(t1.disposed, isTrue); expect(t1.disposed, isTrue);
expect(t2.disposed, isTrue); expect(t2.disposed, isTrue);
}); });
test('calling disposeAsync twice does not throw and not call twice', () async { test('calling disposeAsync twice does not throw and not call twice',
() async {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
scope.installModules([ModuleWithDisposable()]); scope.installModules([ModuleWithDisposable()]);
final t = scope.resolve<TestDisposable>(); final t = scope.resolve<TestDisposable>();
@@ -313,7 +321,8 @@ void main() {
await scope.dispose(); await scope.dispose();
expect(t.disposed, isTrue); expect(t.disposed, isTrue);
}); });
test('Non-disposable dependency is ignored by scope.disposeAsync', () async { test('Non-disposable dependency is ignored by scope.disposeAsync',
() async {
final scope = CherryPick.openRootScope(); final scope = CherryPick.openRootScope();
scope.installModules([ModuleWithDisposable()]); scope.installModules([ModuleWithDisposable()]);
final s = scope.resolve<String>(); final s = scope.resolve<String>();
@@ -327,7 +336,8 @@ void main() {
group('Scope/subScope dispose edge cases', () { group('Scope/subScope dispose edge cases', () {
test('Dispose called in closed subScope only', () async { test('Dispose called in closed subScope only', () async {
final root = CherryPick.openRootScope(); final root = CherryPick.openRootScope();
final sub = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]); final sub = root.openSubScope('feature')
..installModules([ModuleCountingDisposable()]);
final d = sub.resolve<CountingDisposable>(); final d = sub.resolve<CountingDisposable>();
expect(d.disposeCount, 0); expect(d.disposeCount, 0);
@@ -339,7 +349,8 @@ void main() {
expect(d.disposeCount, 1); expect(d.disposeCount, 1);
// Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова) // Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова)
final sub2 = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]); final sub2 = root.openSubScope('feature')
..installModules([ModuleCountingDisposable()]);
final d2 = sub2.resolve<CountingDisposable>(); final d2 = sub2.resolve<CountingDisposable>();
expect(identical(d, d2), isFalse); expect(identical(d, d2), isFalse);
await root.closeSubScope('feature'); await root.closeSubScope('feature');
@@ -347,8 +358,14 @@ void main() {
}); });
test('Dispose for all nested subScopes on root disposeAsync', () async { test('Dispose for all nested subScopes on root disposeAsync', () async {
final root = CherryPick.openRootScope(); final root = CherryPick.openRootScope();
root.openSubScope('a').openSubScope('b').installModules([ModuleCountingDisposable()]); root
final d = root.openSubScope('a').openSubScope('b').resolve<CountingDisposable>(); .openSubScope('a')
.openSubScope('b')
.installModules([ModuleCountingDisposable()]);
final d = root
.openSubScope('a')
.openSubScope('b')
.resolve<CountingDisposable>();
await root.dispose(); await root.dispose();
expect(d.disposeCount, 1); expect(d.disposeCount, 1);
}); });
@@ -357,7 +374,8 @@ void main() {
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
group('Async disposable (Future test)', () { group('Async disposable (Future test)', () {
test('Async Disposable is awaited on disposeAsync', () async { test('Async Disposable is awaited on disposeAsync', () async {
final scope = CherryPick.openRootScope()..installModules([AsyncExampleModule()]); final scope = CherryPick.openRootScope()
..installModules([AsyncExampleModule()]);
final d = scope.resolve<AsyncExampleDisposable>(); final d = scope.resolve<AsyncExampleDisposable>();
expect(d.disposed, false); expect(d.disposed, false);
await scope.dispose(); await scope.dispose();

View File

@@ -1,3 +1,39 @@
## 4.0.0-dev.0
> Note: This release has breaking changes.
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
## 3.0.3
## 3.0.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.2-dev.0
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.0
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
## 1.1.2-dev.2
- **DOCS**(annotations): improve API documentation and usage example.
## 1.1.2-dev.1
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 1.1.2-dev.0 ## 1.1.2-dev.0
- **DOCS**(annotations): unify and improve English DartDoc for all DI annotations. - **DOCS**(annotations): unify and improve English DartDoc for all DI annotations.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# cherrypick_annotations # cherrypick_annotations
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)

View File

@@ -0,0 +1,111 @@
// ignore: dangling_library_doc_comments
/// Example using cherrypick_annotations together with cherrypick (core) and cherrypick_generator.
///
/// Steps to use this example:
/// 1. Make sure your example/pubspec.yaml contains:
/// - cherrypick_annotations (this package)
/// - cherrypick (core DI engine)
/// - cherrypick_generator (as a dev_dependency)
/// - build_runner (as a dev_dependency)
/// 2. Run code generation to produce DI injectors and mixins:
/// ```sh
/// dart run build_runner build
/// ```
/// 3. The `_$ApiScreen` mixin will be generated automatically.
/// 4. In your app/bootstrap code, install modules and use the generated features.
///
/// See documentation and advanced details at:
/// https://pub.dev/packages/cherrypick_annotations
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
// In a real project, use this import:
// import 'package:cherrypick/cherrypick.dart';
// Temporary stub for demonstration purposes only.
// In real usage, import 'Module' from `package:cherrypick/cherrypick.dart`.
class Module {}
/// This mixin is a stub for documentation and IDE hints only.
/// In a real project, it will be generated by cherrypick_generator after running build_runner.
///
/// Do not implement or edit this by hand!
mixin _$ApiScreen {}
/// Example UI/service class with dependencies to be injected.
///
/// The [@injectable] annotation tells the generator to create an injector mixin for this class.
/// Fields marked with [@inject] will be automatically filled by the code generator (using DI).
@injectable()
class ApiScreen with _$ApiScreen {
/// The default (main) implementation of the API service.
@inject()
late final ApiService apiService;
/// An alternate API (mock) implementation, injected by name using @named.
@inject()
@named('mock')
late final ApiService mockApiService;
/// Logger injected from another scope (e.g., global singleton).
@inject()
@scope('global')
late final Logger logger;
}
/// Example DI module using CherryPick annotations.
///
/// The [@module] annotation tells the generator to treat this class as a source of bindings.
/// Methods annotated with [@singleton], [@named], [@provide], [@instance] will be registered into the DI container.
@module()
abstract class AppModule extends Module {
/// Global singleton logger available throughout the app.
@singleton()
Logger provideLogger() => Logger();
/// Main API implementation, identified with the name 'main'.
@named('main')
ApiService createApi() => ApiService();
/// Mock API implementation, identified as 'mock'.
@named('mock')
ApiService createMockApi() => MockApiService();
/// UserManager is created with runtime parameters, such as per-user session.
@provide()
UserManager createManager(@params() Map<String, dynamic> runtimeParams) {
return UserManager(runtimeParams['id'] as String);
}
}
// ---------------------------------------------------------------------------
// Example implementations for demonstration only.
// In a real project, these would contain application/service logic.
/// The main API service.
class ApiService {}
/// A mock API implementation (for development or testing).
class MockApiService extends ApiService {}
/// Manages user operations, created using dynamic (runtime) parameters.
class UserManager {
final String id;
UserManager(this.id);
}
/// Global logger service.
class Logger {}
void main() {
// After running code generation, injectors and mixins will be ready to use.
// Example integration (pseudo-code):
//
// import 'package:cherrypick/cherrypick.dart';
//
// final scope = CherryPick.openRootScope()..installModules([$AppModule()]);
// final screen = ApiScreen()..injectFields();
// print(screen.apiService); // <-- injected!
//
// This main() is provided for reference only.
}

View File

@@ -1,5 +1,3 @@
library;
// //
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com) // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,6 +11,24 @@ library;
// limitations under the License. // limitations under the License.
// //
/// Annotations for use with the CherryPick dependency injection generator.
///
/// These annotations are used on classes, methods, fields or parameters to
/// describe how they should participate in dependency injection.
/// See: https://pub.dev/packages/cherrypick
///
/// Example:
/// ```dart
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
///
/// @injectable()
/// class MyService {
/// @inject()
/// late final Logger logger;
/// }
/// ```
library;
export 'src/module.dart'; export 'src/module.dart';
export 'src/provide.dart'; export 'src/provide.dart';
export 'src/instance.dart'; export 'src/instance.dart';

View File

@@ -38,5 +38,6 @@ import 'package:meta/meta.dart';
/// ``` /// ```
@experimental @experimental
final class inject { final class inject {
/// Creates an [inject] annotation for field injection.
const inject(); const inject();
} }

View File

@@ -39,5 +39,6 @@ import 'package:meta/meta.dart';
/// After running the generator, the mixin (`_\$ProfileScreen`) will be available to help auto-inject all [@inject] fields in your widget/service/controller. /// After running the generator, the mixin (`_\$ProfileScreen`) will be available to help auto-inject all [@inject] fields in your widget/service/controller.
@experimental @experimental
final class injectable { final class injectable {
/// Creates an [injectable] annotation for classes.
const injectable(); const injectable();
} }

View File

@@ -45,5 +45,6 @@ import 'package:meta/meta.dart';
/// See also: [@singleton] /// See also: [@singleton]
@experimental @experimental
final class instance { final class instance {
/// Creates an [instance] annotation for classes or providers.
const instance(); const instance();
} }

View File

@@ -39,6 +39,6 @@ import 'package:meta/meta.dart';
/// See also: [@singleton], [@instance], [@params], [@named] /// See also: [@singleton], [@instance], [@params], [@named]
@experimental @experimental
final class provide { final class provide {
/// Creates a [provide] annotation. /// Creates a [provide] annotation for marking provider methods/classes in DI modules.
const provide(); const provide();
} }

View File

@@ -49,5 +49,7 @@ import 'package:meta/meta.dart';
final class scope { final class scope {
/// The name/key of the DI scope from which to resolve this dependency. /// The name/key of the DI scope from which to resolve this dependency.
final String? name; final String? name;
/// Creates a [scope] annotation specifying which DI scope to use for the dependency resolution.
const scope(this.name); const scope(this.name);
} }

View File

@@ -1,8 +1,9 @@
name: cherrypick_annotations name: cherrypick_annotations
description: | description: |
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects. Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
version: 1.1.2-dev.0 version: 4.0.0-dev.0
documentation: https://github.com/pese-git/cherrypick/wiki homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
topics: topics:
@@ -13,7 +14,7 @@ topics:
- inversion-of-control - inversion-of-control
environment: environment:
sdk: ">=3.5.2 <4.0.0" sdk: ">=3.9.0 <4.0.0"
# Add regular dependencies here. # Add regular dependencies here.
dependencies: dependencies:
@@ -21,5 +22,5 @@ dependencies:
# path: ^1.8.0 # path: ^1.8.0
dev_dependencies: dev_dependencies:
lints: ^5.0.0 lints: ^6.0.0
test: ^1.25.8 test: ^1.25.8

View File

@@ -1,3 +1,35 @@
## 3.0.2
- Update a dependency to the latest release.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.1
- Update a dependency to the latest release.
## 3.0.0-dev.0
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
## 1.1.3-dev.12
- Update a dependency to the latest release.
## 1.1.3-dev.11
- Update a dependency to the latest release.
## 1.1.3-dev.10
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 1.1.3-dev.9 ## 1.1.3-dev.9
- **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration. - **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick Flutter # CherryPick Flutter
`cherrypick_flutter` offers a Flutter integration to access and manage dependency injection scopes using the `CherryPickProvider`. This setup facilitates accessing the root scope directly from the widget tree, providing a straightforward mechanism for dependences management within Flutter applications. `cherrypick_flutter` offers a Flutter integration to access and manage dependency injection scopes using the `CherryPickProvider`. This setup facilitates accessing the root scope directly from the widget tree, providing a straightforward mechanism for dependences management within Flutter applications.

View File

@@ -1,8 +1,8 @@
name: cherrypick_flutter name: cherrypick_flutter
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`." description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
version: 1.1.3-dev.9 version: 3.0.2
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://cherrypick-di.netlify.app
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
topics: topics:
@@ -13,19 +13,19 @@ topics:
- inversion-of-control - inversion-of-control
environment: environment:
sdk: ">=3.5.2 <4.0.0" sdk: '>=3.2.0 <4.0.0'
flutter: ">=3.24.0" flutter: ">=3.16.0"
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
cherrypick: ^3.0.0-dev.9 cherrypick: ^3.0.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
flutter_lints: ^5.0.0 flutter_lints: ^4.0.0
test: ^1.25.7 test: ^1.25.6
melos: ^6.3.2 melos: ^6.3.2
# For information on the generic Dart part of this file, see the # For information on the generic Dart part of this file, see the

View File

@@ -1,3 +1,39 @@
## 4.0.0-dev.0
> Note: This release has breaking changes.
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
## 3.0.3
## 3.0.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.2-dev.0
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.0
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
## 2.0.0-dev.2
- Update a dependency to the latest release.
## 2.0.0-dev.1
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 2.0.0-dev.0 ## 2.0.0-dev.0
> Note: This release has breaking changes. > Note: This release has breaking changes.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# Cherrypick Generator # Cherrypick Generator
**Cherrypick Generator** is a Dart code generation library for automating dependency injection (DI) boilerplate. It processes classes and fields annotated with [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations) and generates registration code for services, modules, and field injection for classes marked as `@injectable`. It supports advanced DI features such as scopes, named bindings, parameters, and asynchronous dependencies. **Cherrypick Generator** is a Dart code generation library for automating dependency injection (DI) boilerplate. It processes classes and fields annotated with [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations) and generates registration code for services, modules, and field injection for classes marked as `@injectable`. It supports advanced DI features such as scopes, named bindings, parameters, and asynchronous dependencies.

View File

@@ -32,3 +32,4 @@ include: package:lints/recommended.yaml
analyzer: analyzer:
errors: errors:
deprecated_member_use: ignore deprecated_member_use: ignore
unintended_html_in_doc_comment: ignore

View File

@@ -11,15 +11,17 @@
// limitations under the License. // limitations under the License.
// //
import 'dart:async'; import 'package:analyzer/dart/element/element2.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
import 'src/annotation_validator.dart';
import 'src/code_builder_emitters.dart';
import 'src/type_parser.dart';
/// CherryPick DI field injector generator for codegen. /// CherryPick DI field injector generator for codegen.
/// ///
/// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`) /// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`)
@@ -100,12 +102,12 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// } /// }
/// ``` /// ```
@override @override
FutureOr<String> generateForAnnotatedElement( dynamic generateForAnnotatedElement(
Element element, Element2 element,
ConstantReader annotation, ConstantReader annotation,
BuildStep buildStep, BuildStep buildStep,
) { ) {
if (element is! ClassElement) { if (element is! ClassElement2) {
throw InvalidGenerationSourceError( throw InvalidGenerationSourceError(
'@injectable() can only be applied to classes.', '@injectable() can only be applied to classes.',
element: element, element: element,
@@ -113,33 +115,64 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
} }
final classElement = element; final classElement = element;
final className = classElement.name; final className = classElement.firstFragment.name2;
final mixinName = '_\$$className'; final mixinName = '_\$$className';
final buffer = StringBuffer() AnnotationValidator.validateClassAnnotations(classElement);
..writeln('mixin $mixinName {')
..writeln(' void _inject($className instance) {');
// Collect and process all @inject fields final classType = TypeParser.parseType(classElement.thisType, classElement);
final injectFields =
classElement.fields.where(_isInjectField).map(_parseInjectField);
for (final parsedField in injectFields) { final injectFields = classElement.fields2
buffer.writeln(_generateInjectionLine(parsedField)); .where((f) => _isInjectField(f))
.map(_parseInjectField)
.toList();
final injectMethod = Method((b) {
b
..name = '_inject'
..returns = refer('void')
..requiredParameters.add(
Parameter((p) {
p
..name = 'instance'
..type = CodeBuilderEmitters.resolveTypeRef(classType);
}),
)
..body = Block((body) {
for (final field in injectFields) {
final scopeExpr = CodeBuilderEmitters.openScope(
scopeName: field.scopeName,
);
final resolveExpr = CodeBuilderEmitters.resolveCall(
scopeExpr: scopeExpr,
parsedType: field.parsedType,
named: field.namedValue,
);
body.statements.add(
refer(
'instance',
).property(field.fieldName).assign(resolveExpr).statement,
);
} }
});
});
buffer final mixin = Mixin((b) {
..writeln(' }') b
..writeln('}'); ..name = mixinName
..methods.add(injectMethod);
});
return buffer.toString(); final library = Library((b) => b..body.add(mixin));
final emitter = DartEmitter(useNullSafetySyntax: true);
return '${library.accept(emitter)}';
} }
/// Returns true if a field is annotated with `@inject`. /// Returns true if a field is annotated with `@inject`.
/// ///
/// Used to detect which fields should be processed for injection. /// Used to detect which fields should be processed for injection.
static bool _isInjectField(FieldElement field) { static bool _isInjectField(FieldElement2 field) {
return field.metadata.any( return field.firstFragment.metadata2.annotations.any(
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject', (m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
); );
} }
@@ -149,12 +182,14 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// ///
/// Converts Dart field declaration and all parameterizing injection-related /// Converts Dart field declaration and all parameterizing injection-related
/// annotations into a [_ParsedInjectField] which is used for codegen. /// annotations into a [_ParsedInjectField] which is used for codegen.
static _ParsedInjectField _parseInjectField(FieldElement field) { static _ParsedInjectField _parseInjectField(FieldElement2 field) {
AnnotationValidator.validateFieldAnnotations(field);
String? scopeName; String? scopeName;
String? namedValue; String? namedValue;
for (final meta in field.metadata) { for (final meta in field.firstFragment.metadata2.annotations) {
final DartObject? obj = meta.computeConstantValue(); final obj = meta.computeConstantValue();
final type = obj?.type?.getDisplayString(); final type = obj?.type?.getDisplayString();
if (type == 'scope') { if (type == 'scope') {
scopeName = obj?.getField('name')?.toStringValue(); scopeName = obj?.getField('name')?.toStringValue();
@@ -164,65 +199,15 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
} }
final DartType dartType = field.type; final DartType dartType = field.type;
String coreTypeName; final parsedType = TypeParser.parseType(dartType, field);
bool isFuture;
if (dartType.isDartAsyncFuture) {
final ParameterizedType paramType = dartType as ParameterizedType;
coreTypeName = paramType.typeArguments.first.getDisplayString();
isFuture = true;
} else {
coreTypeName = dartType.getDisplayString();
isFuture = false;
}
// Determine nullability for field types like T? or Future<T?>
bool isNullable = dartType.nullabilitySuffix ==
NullabilitySuffix.question ||
(dartType is ParameterizedType &&
(dartType)
.typeArguments
.any((t) => t.nullabilitySuffix == NullabilitySuffix.question));
return _ParsedInjectField( return _ParsedInjectField(
fieldName: field.name, fieldName: field.firstFragment.name2 ?? '',
coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий parsedType: parsedType,
isFuture: isFuture,
isNullable: isNullable,
scopeName: scopeName, scopeName: scopeName,
namedValue: namedValue, namedValue: namedValue,
); );
} }
/// Generates Dart code for a single dependency-injected field based on its metadata.
///
/// This code will resolve the field from the CherryPick DI container and assign it to the class instance.
/// Correctly dispatches to resolve, tryResolve, resolveAsync, or tryResolveAsync methods,
/// and applies container scoping or named resolution where required.
///
/// Returns literal Dart code as string (1 line).
///
/// Example output:
/// `instance.logger = CherryPick.openRootScope().resolve<Logger>();`
String _generateInjectionLine(_ParsedInjectField field) {
final resolveMethod = field.isFuture
? (field.isNullable
? 'tryResolveAsync<${field.coreType}>'
: 'resolveAsync<${field.coreType}>')
: (field.isNullable
? 'tryResolve<${field.coreType}>'
: 'resolve<${field.coreType}>');
final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty)
? "CherryPick.openScope(scopeName: '${field.scopeName}')"
: "CherryPick.openRootScope()";
final params = (field.namedValue != null && field.namedValue!.isNotEmpty)
? "(named: '${field.namedValue}')"
: '()';
return " instance.${field.fieldName} = $openCall.$resolveMethod$params;";
}
} }
/// Internal structure: describes all required information for generating the injection /// Internal structure: describes all required information for generating the injection
@@ -233,14 +218,8 @@ class _ParsedInjectField {
/// The name of the field to be injected. /// The name of the field to be injected.
final String fieldName; final String fieldName;
/// The Dart type to resolve (e.g. `Logger` from `Logger` or `Future<Logger>`). /// Parsed type info for the field.
final String coreType; final ParsedType parsedType;
/// True if the field is an async dependency (Future<...>), otherwise false.
final bool isFuture;
/// True if the field accepts null (T?), otherwise false.
final bool isNullable;
/// The scoping for DI resolution, or null to use root scope. /// The scoping for DI resolution, or null to use root scope.
final String? scopeName; final String? scopeName;
@@ -248,12 +227,9 @@ class _ParsedInjectField {
/// Name qualifier for named resolution, or null if not set. /// Name qualifier for named resolution, or null if not set.
final String? namedValue; final String? namedValue;
_ParsedInjectField({ _ParsedInjectField({
required this.fieldName, required this.fieldName,
required this.coreType, required this.parsedType,
required this.isFuture,
required this.isNullable,
this.scopeName, this.scopeName,
this.namedValue, this.namedValue,
}); });

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element2.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
@@ -79,12 +79,12 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
/// ///
/// See file-level docs for usage and generated output example. /// See file-level docs for usage and generated output example.
@override @override
String generateForAnnotatedElement( dynamic generateForAnnotatedElement(
Element element, Element2 element,
ConstantReader annotation, ConstantReader annotation,
BuildStep buildStep, BuildStep buildStep,
) { ) {
if (element is! ClassElement) { if (element is! ClassElement2) {
throw InvalidGenerationSourceError( throw InvalidGenerationSourceError(
'@module() can only be applied to classes.', '@module() can only be applied to classes.',
element: element, element: element,

View File

@@ -12,6 +12,7 @@
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'exceptions.dart'; import 'exceptions.dart';
import 'metadata_utils.dart'; import 'metadata_utils.dart';
@@ -52,8 +53,10 @@ class AnnotationValidator {
/// - Parameter validation for method arguments. /// - Parameter validation for method arguments.
/// ///
/// Throws [AnnotationValidationException] on any violation. /// Throws [AnnotationValidationException] on any violation.
static void validateMethodAnnotations(MethodElement method) { static void validateMethodAnnotations(MethodElement2 method) {
final annotations = _getAnnotationNames(method.metadata); final annotations = _getAnnotationNames(
method.firstFragment.metadata2.annotations,
);
_validateMutuallyExclusiveAnnotations(method, annotations); _validateMutuallyExclusiveAnnotations(method, annotations);
_validateAnnotationCombinations(method, annotations); _validateAnnotationCombinations(method, annotations);
@@ -68,8 +71,10 @@ class AnnotationValidator {
/// - Correct scope naming if present. /// - Correct scope naming if present.
/// ///
/// Throws [AnnotationValidationException] if checks fail. /// Throws [AnnotationValidationException] if checks fail.
static void validateFieldAnnotations(FieldElement field) { static void validateFieldAnnotations(FieldElement2 field) {
final annotations = _getAnnotationNames(field.metadata); final annotations = _getAnnotationNames(
field.firstFragment.metadata2.annotations,
);
_validateInjectFieldAnnotations(field, annotations); _validateInjectFieldAnnotations(field, annotations);
} }
@@ -82,8 +87,10 @@ class AnnotationValidator {
/// - Provides helpful context for error/warning reporting. /// - Provides helpful context for error/warning reporting.
/// ///
/// Throws [AnnotationValidationException] if checks fail. /// Throws [AnnotationValidationException] if checks fail.
static void validateClassAnnotations(ClassElement classElement) { static void validateClassAnnotations(ClassElement2 classElement) {
final annotations = _getAnnotationNames(classElement.metadata); final annotations = _getAnnotationNames(
classElement.firstFragment.metadata2.annotations,
);
_validateModuleClassAnnotations(classElement, annotations); _validateModuleClassAnnotations(classElement, annotations);
_validateInjectableClassAnnotations(classElement, annotations); _validateInjectableClassAnnotations(classElement, annotations);
@@ -104,7 +111,7 @@ class AnnotationValidator {
/// ///
/// For example, `@instance` and `@provide` cannot both be present. /// For example, `@instance` and `@provide` cannot both be present.
static void _validateMutuallyExclusiveAnnotations( static void _validateMutuallyExclusiveAnnotations(
MethodElement method, MethodElement2 method,
List<String> annotations, List<String> annotations,
) { ) {
// @instance and @provide are mutually exclusive // @instance and @provide are mutually exclusive
@@ -127,7 +134,7 @@ class AnnotationValidator {
/// - One of `@instance` or `@provide` must be present for a registration method /// - One of `@instance` or `@provide` must be present for a registration method
/// - Validates singleton usage /// - Validates singleton usage
static void _validateAnnotationCombinations( static void _validateAnnotationCombinations(
MethodElement method, MethodElement2 method,
List<String> annotations, List<String> annotations,
) { ) {
// @params can only be used with @provide // @params can only be used with @provide
@@ -165,7 +172,7 @@ class AnnotationValidator {
/// Singleton-specific method annotation checks. /// Singleton-specific method annotation checks.
static void _validateSingletonUsage( static void _validateSingletonUsage(
MethodElement method, MethodElement2 method,
List<String> annotations, List<String> annotations,
) { ) {
// Singleton with params might not make sense in some contexts // Singleton with params might not make sense in some contexts
@@ -181,18 +188,17 @@ class AnnotationValidator {
'Singleton methods cannot return void', 'Singleton methods cannot return void',
element: method, element: method,
suggestion: 'Remove @singleton annotation or change return type', suggestion: 'Remove @singleton annotation or change return type',
context: { context: {'method_name': method.displayName, 'return_type': returnType},
'method_name': method.displayName,
'return_type': returnType,
},
); );
} }
} }
/// Validates extra requirements or syntactic rules for annotation arguments, like @named. /// Validates extra requirements or syntactic rules for annotation arguments, like @named.
static void _validateAnnotationParameters(MethodElement method) { static void _validateAnnotationParameters(MethodElement2 method) {
// Validate @named annotation parameters // Validate @named annotation parameters
final namedValue = MetadataUtils.getNamedValue(method.metadata); final namedValue = MetadataUtils.getNamedValue(
method.firstFragment.metadata2.annotations,
);
if (namedValue != null) { if (namedValue != null) {
if (namedValue.isEmpty) { if (namedValue.isEmpty) {
throw AnnotationValidationException( throw AnnotationValidationException(
@@ -222,8 +228,10 @@ class AnnotationValidator {
} }
// Validate method parameters for @params usage // Validate method parameters for @params usage
for (final param in method.parameters) { for (final param in method.formalParameters) {
final paramAnnotations = _getAnnotationNames(param.metadata); final paramAnnotations = _getAnnotationNames(
param.firstFragment.metadata2.annotations,
);
if (paramAnnotations.contains('params')) { if (paramAnnotations.contains('params')) {
_validateParamsParameter(param, method); _validateParamsParameter(param, method);
} }
@@ -232,7 +240,9 @@ class AnnotationValidator {
/// Checks that @params is used with compatible parameter type. /// Checks that @params is used with compatible parameter type.
static void _validateParamsParameter( static void _validateParamsParameter(
ParameterElement param, MethodElement method) { FormalParameterElement param,
MethodElement2 method,
) {
// @params parameter should typically be dynamic or Map<String, dynamic> // @params parameter should typically be dynamic or Map<String, dynamic>
final paramType = param.type.getDisplayString(); final paramType = param.type.getDisplayString();
if (paramType != 'dynamic' && if (paramType != 'dynamic' &&
@@ -256,7 +266,7 @@ class AnnotationValidator {
/// Checks field-level annotation for valid injectable fields. /// Checks field-level annotation for valid injectable fields.
static void _validateInjectFieldAnnotations( static void _validateInjectFieldAnnotations(
FieldElement field, FieldElement2 field,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('inject')) { if (!annotations.contains('inject')) {
@@ -270,15 +280,12 @@ class AnnotationValidator {
'Cannot inject void type', 'Cannot inject void type',
element: field, element: field,
suggestion: 'Use a concrete type instead of void', suggestion: 'Use a concrete type instead of void',
context: { context: {'field_name': field.displayName, 'field_type': fieldType},
'field_name': field.displayName,
'field_type': fieldType,
},
); );
} }
// Validate scope annotation if present // Validate scope annotation if present
for (final meta in field.metadata) { for (final meta in field.firstFragment.metadata2.annotations) {
final obj = meta.computeConstantValue(); final obj = meta.computeConstantValue();
final type = obj?.type?.getDisplayString(); final type = obj?.type?.getDisplayString();
if (type == 'scope') { if (type == 'scope') {
@@ -290,7 +297,7 @@ class AnnotationValidator {
/// Checks @module usage: must have at least one DI method, each with DI-annotation. /// Checks @module usage: must have at least one DI method, each with DI-annotation.
static void _validateModuleClassAnnotations( static void _validateModuleClassAnnotations(
ClassElement classElement, ClassElement2 classElement,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('module')) { if (!annotations.contains('module')) {
@@ -298,8 +305,9 @@ class AnnotationValidator {
} }
// Check if class has public methods // Check if class has public methods
final publicMethods = final publicMethods = classElement.methods2
classElement.methods.where((m) => m.isPublic).toList(); .where((m) => m.isPublic)
.toList();
if (publicMethods.isEmpty) { if (publicMethods.isEmpty) {
throw AnnotationValidationException( throw AnnotationValidationException(
'Module class must have at least one public method', 'Module class must have at least one public method',
@@ -314,7 +322,9 @@ class AnnotationValidator {
// Validate that public methods have appropriate annotations // Validate that public methods have appropriate annotations
for (final method in publicMethods) { for (final method in publicMethods) {
final methodAnnotations = _getAnnotationNames(method.metadata); final methodAnnotations = _getAnnotationNames(
method.firstFragment.metadata2.annotations,
);
if (!methodAnnotations.contains('instance') && if (!methodAnnotations.contains('instance') &&
!methodAnnotations.contains('provide')) { !methodAnnotations.contains('provide')) {
throw AnnotationValidationException( throw AnnotationValidationException(
@@ -332,7 +342,7 @@ class AnnotationValidator {
/// Checks @injectable usage on classes and their fields. /// Checks @injectable usage on classes and their fields.
static void _validateInjectableClassAnnotations( static void _validateInjectableClassAnnotations(
ClassElement classElement, ClassElement2 classElement,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('injectable')) { if (!annotations.contains('injectable')) {
@@ -340,8 +350,10 @@ class AnnotationValidator {
} }
// Check if class has injectable fields // Check if class has injectable fields
final injectFields = classElement.fields.where((f) { final injectFields = classElement.fields2.where((f) {
final fieldAnnotations = _getAnnotationNames(f.metadata); final fieldAnnotations = _getAnnotationNames(
f.firstFragment.metadata2.annotations,
);
return fieldAnnotations.contains('inject'); return fieldAnnotations.contains('inject');
}).toList(); }).toList();

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element2.dart';
import 'bind_parameters_spec.dart'; import 'bind_parameters_spec.dart';
import 'metadata_utils.dart'; import 'metadata_utils.dart';
@@ -23,8 +23,9 @@ import 'annotation_validator.dart';
enum BindingType { enum BindingType {
/// Direct instance returned from the method (@instance). /// Direct instance returned from the method (@instance).
instance, instance,
/// Provider/factory function (@provide). /// Provider/factory function (@provide).
provide; provide,
} }
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -154,7 +155,8 @@ class BindSpec {
switch (bindingType) { switch (bindingType) {
case BindingType.instance: case BindingType.instance:
throw StateError( throw StateError(
'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.'); 'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.',
);
//return isAsyncInstance //return isAsyncInstance
// ? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))' // ? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))'
// : '.toInstance(($fnArgs) => $methodName($fnArgs))'; // : '.toInstance(($fnArgs) => $methodName($fnArgs))';
@@ -188,20 +190,24 @@ class BindSpec {
case BindingType.provide: case BindingType.provide:
if (isAsyncProvide) { if (isAsyncProvide) {
if (needsMultiline) { if (needsMultiline) {
final lambdaIndent = final lambdaIndent = (isSingleton || named != null)
(isSingleton || named != null) ? indent + 6 : indent + 2; ? indent + 6
final closingIndent = : indent + 2;
(isSingleton || named != null) ? indent + 4 : indent; final closingIndent = (isSingleton || named != null)
? indent + 4
: indent;
return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})'; return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
} else { } else {
return '.toProvideAsync(() => $methodName($argsStr))'; return '.toProvideAsync(() => $methodName($argsStr))';
} }
} else { } else {
if (needsMultiline) { if (needsMultiline) {
final lambdaIndent = final lambdaIndent = (isSingleton || named != null)
(isSingleton || named != null) ? indent + 6 : indent + 2; ? indent + 6
final closingIndent = : indent + 2;
(isSingleton || named != null) ? indent + 4 : indent; final closingIndent = (isSingleton || named != null)
? indent + 4
: indent;
return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})'; return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
} else { } else {
return '.toProvide(() => $methodName($argsStr))'; return '.toProvide(() => $methodName($argsStr))';
@@ -245,7 +251,7 @@ class BindSpec {
/// print(bindSpec.returnType); // e.g., 'Logger' /// print(bindSpec.returnType); // e.g., 'Logger'
/// ``` /// ```
/// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid. /// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid.
static BindSpec fromMethod(MethodElement method) { static BindSpec fromMethod(MethodElement2 method) {
try { try {
// Validate method annotations // Validate method annotations
AnnotationValidator.validateMethodAnnotations(method); AnnotationValidator.validateMethodAnnotations(method);
@@ -253,28 +259,44 @@ class BindSpec {
// Parse return type using improved type parser // Parse return type using improved type parser
final parsedReturnType = TypeParser.parseType(method.returnType, method); final parsedReturnType = TypeParser.parseType(method.returnType, method);
final methodName = method.displayName; final methodName = method.firstFragment.name2 ?? '';
// Check for @singleton annotation. // Check for @singleton annotation.
final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton'); final isSingleton = MetadataUtils.anyMeta(
method.firstFragment.metadata2.annotations,
'singleton',
);
// Get @named value if present. // Get @named value if present.
final named = MetadataUtils.getNamedValue(method.metadata); final named = MetadataUtils.getNamedValue(
method.firstFragment.metadata2.annotations,
);
// Parse each method parameter. // Parse each method parameter.
final params = <BindParameterSpec>[]; final params = <BindParameterSpec>[];
bool hasParams = false; bool hasParams = false;
for (final p in method.parameters) { for (final p in method.formalParameters) {
final typeStr = p.type.getDisplayString(); final typeStr = p.type.getDisplayString();
final paramNamed = MetadataUtils.getNamedValue(p.metadata); final paramNamed = MetadataUtils.getNamedValue(
final isParams = MetadataUtils.anyMeta(p.metadata, 'params'); p.firstFragment.metadata2.annotations,
);
final isParams = MetadataUtils.anyMeta(
p.firstFragment.metadata2.annotations,
'params',
);
if (isParams) hasParams = true; if (isParams) hasParams = true;
params.add(BindParameterSpec(typeStr, paramNamed, isParams: isParams)); params.add(BindParameterSpec(typeStr, paramNamed, isParams: isParams));
} }
// Determine bindingType: @instance or @provide. // Determine bindingType: @instance or @provide.
final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance'); final hasInstance = MetadataUtils.anyMeta(
final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide'); method.firstFragment.metadata2.annotations,
'instance',
);
final hasProvide = MetadataUtils.anyMeta(
method.firstFragment.metadata2.annotations,
'provide',
);
if (!hasInstance && !hasProvide) { if (!hasInstance && !hasProvide) {
throw AnnotationValidationException( throw AnnotationValidationException(
@@ -289,8 +311,9 @@ class BindSpec {
); );
} }
final bindingType = final bindingType = hasInstance
hasInstance ? BindingType.instance : BindingType.provide; ? BindingType.instance
: BindingType.provide;
// PROHIBIT @params with @instance bindings! // PROHIBIT @params with @instance bindings!
if (bindingType == BindingType.instance && hasParams) { if (bindingType == BindingType.instance && hasParams) {

View File

@@ -0,0 +1,80 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'package:code_builder/code_builder.dart';
import 'type_parser.dart';
/// Small helpers for building code_builder AST nodes used by generators.
class CodeBuilderEmitters {
/// Builds a CherryPick scope opener expression.
///
/// - If [scopeName] is empty or null, uses openRootScope().
/// - Otherwise uses openScope(scopeName: ...).
static Expression openScope({String? scopeName}) {
if (scopeName == null || scopeName.isEmpty) {
return refer('CherryPick').property('openRootScope').call([]);
}
return refer(
'CherryPick',
).property('openScope').call([], {'scopeName': literalString(scopeName)});
}
/// Builds a TypeReference appropriate for resolving a dependency.
///
/// For Future<T>, it returns the inner type reference (T).
/// Nullability and generic arguments are preserved.
static TypeReference resolveTypeRef(ParsedType parsedType) {
final target = parsedType.isFuture && parsedType.innerType != null
? parsedType.innerType!
: parsedType;
return _typeRefFromParsedType(target, stripNullability: true);
}
/// Builds a DI resolve call on [scopeExpr] using [parsedType] and [named].
///
/// The method name is derived from [ParsedType.resolveMethodName].
static Expression resolveCall({
required Expression scopeExpr,
required ParsedType parsedType,
String? named,
}) {
final typeRef = resolveTypeRef(parsedType);
final method = parsedType.resolveMethodName;
final args = <Expression>[];
final namedArgs = <String, Expression>{};
if (named != null && named.isNotEmpty) {
namedArgs['named'] = literalString(named);
}
return scopeExpr.property(method).call(args, namedArgs, [typeRef]);
}
static TypeReference _typeRefFromParsedType(
ParsedType parsedType, {
required bool stripNullability,
}) {
return TypeReference((b) {
b
..symbol = parsedType.coreType
..isNullable = stripNullability ? false : parsedType.isNullable;
if (parsedType.typeArguments.isNotEmpty) {
b.types.addAll(
parsedType.typeArguments.map(
(arg) =>
_typeRefFromParsedType(arg, stripNullability: stripNullability),
),
);
}
});
}
}

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element2.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -48,7 +48,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
CherryPickGeneratorException( CherryPickGeneratorException(
String message, { String message, {
required Element element, required Element2 element,
required this.category, required this.category,
this.suggestion, this.suggestion,
this.context, this.context,
@@ -62,9 +62,11 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
String category, String category,
String? suggestion, String? suggestion,
Map<String, dynamic>? context, Map<String, dynamic>? context,
Element element, Element2 element,
) { ) {
final buffer = StringBuffer(); final buffer = StringBuffer();
final location = _safeLocation(element);
final enclosing = _safeEnclosingDisplayName(element);
// Header with category // Header with category
buffer.writeln('[$category] $message'); buffer.writeln('[$category] $message');
@@ -74,16 +76,11 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
buffer.writeln('Context:'); buffer.writeln('Context:');
buffer.writeln(' Element: ${element.displayName}'); buffer.writeln(' Element: ${element.displayName}');
buffer.writeln(' Type: ${element.runtimeType}'); buffer.writeln(' Type: ${element.runtimeType}');
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}'); buffer.writeln(' Location: $location');
// Try to show enclosing element info for extra context // Try to show enclosing element info for extra context
try {
final enclosing = (element as dynamic).enclosingElement;
if (enclosing != null) { if (enclosing != null) {
buffer.writeln(' Enclosing: ${enclosing.displayName}'); buffer.writeln(' Enclosing: $enclosing');
}
} catch (e) {
// Ignore if enclosingElement is not available
} }
// Arbitrary user context // Arbitrary user context
@@ -103,6 +100,34 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
return buffer.toString(); return buffer.toString();
} }
/// Best-effort extraction of element location for diagnostics.
///
/// Some tests use lightweight mocks for [Element2] that don't implement
/// analyzer fragment APIs, so this method must never throw.
static String _safeLocation(Element2 element) {
try {
return element.firstFragment.libraryFragment?.source.fullName ??
'unknown';
} catch (_) {
return 'unknown';
}
}
/// Best-effort extraction of enclosing element display name.
///
/// Accessed via dynamic to stay compatible with analyzer API differences.
static String? _safeEnclosingDisplayName(Element2 element) {
try {
final enclosing = (element as dynamic).enclosingElement;
if (enclosing == null) return null;
final name = enclosing.displayName;
if (name is String && name.isNotEmpty) return name;
return enclosing.toString();
} catch (_) {
return null;
}
}
} }
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------

View File

@@ -12,6 +12,7 @@
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'bind_spec.dart'; import 'bind_spec.dart';
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -75,14 +76,11 @@ class GeneratedClass {
/// final gen = GeneratedClass.fromClassElement(classElement); /// final gen = GeneratedClass.fromClassElement(classElement);
/// print(gen.generatedClassName); // e.g. $AppModule /// print(gen.generatedClassName); // e.g. $AppModule
/// ``` /// ```
static GeneratedClass fromClassElement(ClassElement element) { static GeneratedClass fromClassElement(ClassElement2 element) {
final className = element.displayName; final className = element.firstFragment.name2 ?? '';
// Generated class name with '$' prefix (standard for generated Dart code).
final generatedClassName = r'$' + className; final generatedClassName = r'$' + className;
// Get source file name final sourceFile = element.firstFragment.libraryFragment.source.shortName;
final sourceFile = element.source.shortName; final binds = element.methods2
// Collect bindings for all non-abstract methods.
final binds = element.methods
.where((m) => !m.isAbstract) .where((m) => !m.isAbstract)
.map(BindSpec.fromMethod) .map(BindSpec.fromMethod)
.toList(); .toList();

View File

@@ -41,14 +41,16 @@ class MetadataUtils {
/// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata, 'singleton'); /// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata, 'singleton');
/// ``` /// ```
static bool anyMeta(List<ElementAnnotation> meta, String typeName) { static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
return meta.any((m) => return meta.any(
(m) =>
m m
.computeConstantValue() .computeConstantValue()
?.type ?.type
?.getDisplayString() ?.getDisplayString()
.toLowerCase() .toLowerCase()
.contains(typeName.toLowerCase()) ?? .contains(typeName.toLowerCase()) ??
false); false,
);
} }
/// Extracts the string value from a `@named('value')` annotation if present in [meta]. /// Extracts the string value from a `@named('value')` annotation if present in [meta].

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element2.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/type.dart';
import 'exceptions.dart'; import 'exceptions.dart';
@@ -45,7 +45,7 @@ class TypeParser {
/// final parsed = TypeParser.parseType(field.type, field); /// final parsed = TypeParser.parseType(field.type, field);
/// if (parsed.isNullable) print('Field is nullable'); /// if (parsed.isNullable) print('Field is nullable');
/// ``` /// ```
static ParsedType parseType(DartType dartType, Element context) { static ParsedType parseType(DartType dartType, Element2 context) {
try { try {
return _parseTypeInternal(dartType, context); return _parseTypeInternal(dartType, context);
} catch (e) { } catch (e) {
@@ -61,7 +61,7 @@ class TypeParser {
} }
} }
static ParsedType _parseTypeInternal(DartType dartType, Element context) { static ParsedType _parseTypeInternal(DartType dartType, Element2 context) {
final displayString = dartType.getDisplayString(); final displayString = dartType.getDisplayString();
final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question; final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question;
@@ -87,7 +87,10 @@ class TypeParser {
} }
static ParsedType _parseFutureType( static ParsedType _parseFutureType(
DartType dartType, Element context, bool isNullable) { DartType dartType,
Element2 context,
bool isNullable,
) {
if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) { if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) {
throw TypeParsingException( throw TypeParsingException(
'Future type must have a type argument', 'Future type must have a type argument',
@@ -112,7 +115,10 @@ class TypeParser {
} }
static ParsedType _parseGenericType( static ParsedType _parseGenericType(
ParameterizedType dartType, Element context, bool isNullable) { ParameterizedType dartType,
Element2 context,
bool isNullable,
) {
final typeArguments = dartType.typeArguments final typeArguments = dartType.typeArguments
.map((arg) => _parseTypeInternal(arg, context)) .map((arg) => _parseTypeInternal(arg, context))
.toList(); .toList();
@@ -138,7 +144,7 @@ class TypeParser {
/// final parsed = TypeParser.parseType(field.type, field); /// final parsed = TypeParser.parseType(field.type, field);
/// TypeParser.validateInjectableType(parsed, field); /// TypeParser.validateInjectableType(parsed, field);
/// ``` /// ```
static void validateInjectableType(ParsedType parsedType, Element context) { static void validateInjectableType(ParsedType parsedType, Element2 context) {
// Check for void type // Check for void type
if (parsedType.coreType == 'void') { if (parsedType.coreType == 'void') {
throw TypeParsingException( throw TypeParsingException(

View File

@@ -2,8 +2,9 @@ name: cherrypick_generator
description: | description: |
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects. Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
version: 2.0.0-dev.0 version: 4.0.0-dev.0
documentation: https://github.com/pese-git/cherrypick/wiki homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_generator repository: https://github.com/pese-git/cherrypick/cherrypick_generator
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
topics: topics:
@@ -14,20 +15,21 @@ topics:
- inversion-of-control - inversion-of-control
environment: environment:
sdk: ">=3.5.2 <4.0.0" sdk: ">=3.9.0 <4.0.0"
# Add regular dependencies here. # Add regular dependencies here.
dependencies: dependencies:
cherrypick_annotations: ^1.1.2-dev.0 cherrypick_annotations: ^4.0.0-dev.0
analyzer: ^7.0.0 analyzer: ">=8.2.9 <10.0.1"
dart_style: ^3.0.0 dart_style: ^3.0.0
build: ^2.4.1 code_builder: ^4.10.1
source_gen: ^2.0.0 build: ^3.0.0
source_gen: ^4.2.0
collection: ^1.18.0 collection: ^1.18.0
dev_dependencies: dev_dependencies:
lints: ^4.0.0 lints: ^6.0.0
mockito: ^5.4.4 mockito: ^5.4.5
test: ^1.25.8 test: ^1.25.8
build_test: ^2.1.7 build_test: ^3.0.0
build_runner: ^2.4.13 build_runner: ^2.5.0

View File

@@ -244,8 +244,7 @@ void main() {
final result = bindSpec.generateBind(4); final result = bindSpec.generateBind(4);
expect( expect(
result, result,
equals( equals(" bind<ApiClient>()\n"
" bind<ApiClient>()\n"
" .toProvideAsync(() => createApiClient())\n" " .toProvideAsync(() => createApiClient())\n"
" .withName('mainApi')\n" " .withName('mainApi')\n"
" .singleton();")); " .singleton();"));

View File

@@ -1,32 +0,0 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'package:test/test.dart';
// Import working test suites
import 'simple_test.dart' as simple_tests;
import 'bind_spec_test.dart' as bind_spec_tests;
import 'metadata_utils_test.dart' as metadata_utils_tests;
// Import integration test suites (now working!)
import 'module_generator_test.dart' as module_generator_tests;
import 'inject_generator_test.dart' as inject_generator_tests;
void main() {
group('CherryPick Generator Tests', () {
group('Simple Tests', simple_tests.main);
group('BindSpec Tests', bind_spec_tests.main);
group('MetadataUtils Tests', metadata_utils_tests.main);
group('ModuleGenerator Tests', module_generator_tests.main);
group('InjectGenerator Tests', inject_generator_tests.main);
});
}

View File

@@ -11,9 +11,13 @@
// limitations under the License. // limitations under the License.
// //
import 'dart:isolate';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:build_test/build_test.dart'; import 'package:build_test/build_test.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:cherrypick_generator/inject_generator.dart'; import 'package:cherrypick_generator/inject_generator.dart';
import 'package:package_config/package_config.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@@ -40,8 +44,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -75,8 +79,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -113,8 +117,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -124,9 +128,8 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = CherryPick.openRootScope().resolve<MyService>( instance.service =
named: 'myService', CherryPick.openRootScope().resolve<MyService>(named: 'myService');
);
} }
} }
'''; ''';
@@ -151,8 +154,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -162,9 +165,8 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = CherryPick.openRootScope().tryResolve<MyService>( instance.service =
named: 'myService', CherryPick.openRootScope().tryResolve<MyService>(named: 'myService');
);
} }
} }
'''; ''';
@@ -191,8 +193,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -229,8 +231,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -240,9 +242,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = CherryPick.openScope( instance.service =
scopeName: 'userScope', CherryPick.openScope(scopeName: 'userScope')
).resolve<MyService>(named: 'myService'); .resolve<MyService>(named: 'myService');
} }
} }
'''; ''';
@@ -268,8 +270,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -303,8 +305,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -339,8 +341,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -350,9 +352,8 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = CherryPick.openRootScope().resolveAsync<MyService>( instance.service =
named: 'myService', CherryPick.openRootScope().resolveAsync<MyService>(named: 'myService');
);
} }
} }
'''; ''';
@@ -391,8 +392,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -403,13 +404,11 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.apiService = CherryPick.openRootScope().resolve<ApiService>(); instance.apiService = CherryPick.openRootScope().resolve<ApiService>();
instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>( instance.cacheService =
named: 'cache', CherryPick.openRootScope().tryResolve<CacheService>(named: 'cache');
);
instance.dbService = instance.dbService =
CherryPick.openScope( CherryPick.openScope(scopeName: 'dbScope')
scopeName: 'dbScope', .resolveAsync<DatabaseService>();
).resolveAsync<DatabaseService>();
} }
} }
'''; ''';
@@ -439,8 +438,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -480,7 +479,8 @@ void notAClass() {}
); );
}); });
test('should generate empty mixin for class without @inject fields', test(
'should generate empty mixin for class without @inject fields',
() async { () async {
const input = ''' const input = '''
import 'package:cherrypick_annotations/cherrypick_annotations.dart'; import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@@ -495,8 +495,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -510,7 +510,8 @@ mixin _\$TestWidget {
'''; ''';
await _testGeneration(input, expectedOutput); await _testGeneration(input, expectedOutput);
}); },
);
}); });
group('Edge Cases', () { group('Edge Cases', () {
@@ -531,8 +532,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -567,8 +568,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -591,14 +592,41 @@ mixin _\$TestWidget {
/// Helper function to test code generation /// Helper function to test code generation
Future<void> _testGeneration(String input, String expectedOutput) async { Future<void> _testGeneration(String input, String expectedOutput) async {
await testBuilder( final readerWriter = TestReaderWriter(rootPackage: 'a');
await readerWriter.testing.loadIsolateSources();
final packageConfig = await loadPackageConfigUri(
(await Isolate.packageConfig)!,
);
final outputs = expectedOutput.isEmpty
? null
: {
'a|lib/test_widget.inject.cherrypick.g.dart':
decodedMatches(_normalizedEquals(expectedOutput)),
};
final result = await testBuilder(
injectBuilder(BuilderOptions.empty), injectBuilder(BuilderOptions.empty),
{ {'a|lib/test_widget.dart': input},
'a|lib/test_widget.dart': input, outputs: outputs,
}, readerWriter: readerWriter,
outputs: { rootPackage: 'a',
'a|lib/test_widget.inject.cherrypick.g.dart': expectedOutput, packageConfig: packageConfig,
}, );
reader: await PackageAssetReader.currentIsolate(), if (expectedOutput.isEmpty && result.buildResult.status == BuildStatus.failure) {
throw InvalidGenerationSourceError('Build failed');
}
}
Matcher _normalizedEquals(String expected) {
return predicate<String>(
(actual) => _normalize(actual) == _normalize(expected),
'matches after normalization',
); );
} }
String _normalize(String input) {
return input
.replaceAll(RegExp(r'\s+'), '')
.replaceAll(RegExp(r',\)'), ')')
.replaceAll(RegExp(r',\]'), ']')
.replaceAll(RegExp(r',\}'), '}');
}

View File

@@ -11,12 +11,16 @@
// limitations under the License. // limitations under the License.
// //
import 'package:test/test.dart'; import 'dart:isolate';
import 'package:build_test/build_test.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:package_config/package_config.dart';
import 'package:test/test.dart';
import 'package:cherrypick_generator/module_generator.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_generator/module_generator.dart';
void main() { void main() {
group('ModuleGenerator Tests', () { group('ModuleGenerator Tests', () {
@@ -40,8 +44,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -75,8 +79,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -113,8 +117,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -149,8 +153,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -187,8 +191,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -224,8 +228,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -264,8 +268,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -299,8 +303,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -334,8 +338,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -374,8 +378,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -414,8 +418,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -453,8 +457,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -488,8 +492,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -541,8 +545,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80
part of 'test_module.dart'; part of 'test_module.dart';
@@ -590,7 +594,8 @@ void notAClass() {}
); );
}); });
test('should throw error for method without @instance or @provide', test(
'should throw error for method without @instance or @provide',
() async { () async {
const input = ''' const input = '''
import 'package:cherrypick_annotations/cherrypick_annotations.dart'; import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@@ -608,7 +613,8 @@ abstract class TestModule extends Module {
() => _testGeneration(input, ''), () => _testGeneration(input, ''),
throwsA(isA<InvalidGenerationSourceError>()), throwsA(isA<InvalidGenerationSourceError>()),
); );
}); },
);
test('should throw error for @params with @instance', () async { test('should throw error for @params with @instance', () async {
const input = ''' const input = '''
@@ -635,14 +641,41 @@ abstract class TestModule extends Module {
/// Helper function to test code generation /// Helper function to test code generation
Future<void> _testGeneration(String input, String expectedOutput) async { Future<void> _testGeneration(String input, String expectedOutput) async {
await testBuilder( final readerWriter = TestReaderWriter(rootPackage: 'a');
await readerWriter.testing.loadIsolateSources();
final packageConfig = await loadPackageConfigUri(
(await Isolate.packageConfig)!,
);
final outputs = expectedOutput.isEmpty
? null
: {
'a|lib/test_module.module.cherrypick.g.dart':
decodedMatches(_normalizedEquals(expectedOutput)),
};
final result = await testBuilder(
moduleBuilder(BuilderOptions.empty), moduleBuilder(BuilderOptions.empty),
{ {'a|lib/test_module.dart': input},
'a|lib/test_module.dart': input, outputs: outputs,
}, readerWriter: readerWriter,
outputs: { rootPackage: 'a',
'a|lib/test_module.module.cherrypick.g.dart': expectedOutput, packageConfig: packageConfig,
}, );
reader: await PackageAssetReader.currentIsolate(), if (expectedOutput.isEmpty && result.buildResult.status == BuildStatus.failure) {
throw InvalidGenerationSourceError('Build failed');
}
}
Matcher _normalizedEquals(String expected) {
return predicate<String>(
(actual) => _normalize(actual) == _normalize(expected),
'matches after normalization',
); );
} }
String _normalize(String input) {
return input
.replaceAll(RegExp(r'\s+'), '')
.replaceAll(RegExp(r',\)'), ')')
.replaceAll(RegExp(r',\]'), ']')
.replaceAll(RegExp(r',\}'), '}');
}

View File

@@ -1,7 +1,6 @@
import 'package:analyzer/dart/element/element2.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/source/source.dart';
import 'package:cherrypick_generator/src/type_parser.dart'; import 'package:cherrypick_generator/src/type_parser.dart';
import 'package:cherrypick_generator/src/exceptions.dart'; import 'package:cherrypick_generator/src/exceptions.dart';
@@ -42,7 +41,9 @@ void main() {
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(
parsedType, _createMockElement()), parsedType,
_createMockElement(),
),
throwsA(isA<TypeParsingException>()), throwsA(isA<TypeParsingException>()),
); );
}); });
@@ -59,7 +60,9 @@ void main() {
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(
parsedType, _createMockElement()), parsedType,
_createMockElement(),
),
throwsA(isA<TypeParsingException>()), throwsA(isA<TypeParsingException>()),
); );
}); });
@@ -76,7 +79,9 @@ void main() {
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(
parsedType, _createMockElement()), parsedType,
_createMockElement(),
),
returnsNormally, returnsNormally,
); );
}); });
@@ -159,7 +164,8 @@ void main() {
expect(parsedType.resolveMethodName, equals('resolveAsync')); expect(parsedType.resolveMethodName, equals('resolveAsync'));
}); });
test('should return correct resolveMethodName for nullable async types', test(
'should return correct resolveMethodName for nullable async types',
() { () {
final parsedType = ParsedType( final parsedType = ParsedType(
displayString: 'Future<String?>', displayString: 'Future<String?>',
@@ -171,7 +177,8 @@ void main() {
); );
expect(parsedType.resolveMethodName, equals('tryResolveAsync')); expect(parsedType.resolveMethodName, equals('tryResolveAsync'));
}); },
);
test('should implement equality correctly', () { test('should implement equality correctly', () {
final parsedType1 = ParsedType( final parsedType1 = ParsedType(
@@ -216,19 +223,19 @@ void main() {
} }
// Mock element for testing // Mock element for testing
Element _createMockElement() { Element2 _createMockElement() {
return _MockElement(); return _MockElement();
} }
class _MockElement implements Element { class _MockElement implements Element2 {
@override @override
String get displayName => 'MockElement'; String get displayName => 'MockElement';
@override //@override
String get name => 'MockElement'; //String get name => 'MockElement';
//
@override //@override
Source? get source => null; //Source? get source => null;
@override @override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

View File

@@ -44,6 +44,46 @@ final setupFuture = loadEnvironment();
bind<Environment>().toInstanceAsync(setupFuture); bind<Environment>().toInstanceAsync(setupFuture);
``` ```
> ⚠️ **Important note about using toInstance in Module**
>
> If you register a chain of dependencies via `toInstance` inside the `builder` method of your `Module`, you must NOT call `scope.resolve<T>()` for a type that you have just bound—at this moment.
>
> CherryPick initializes all bindings inside `builder` sequentially: at the time of a new binding, not all other dependencies are registered yet in the DI container. If you try to use `scope.resolve<T>()` for an object you have just added in the same `builder`, it will result in an error (`Can't resolve dependency ...`).
>
> **Correct way:**
> Manually construct the entire object chain before registering:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies only to `toInstance`. For providers (`toProvide`/`toProvideAsync`) and other strategies, you can freely use `scope.resolve<T>()` inside `builder`.
- **toProvide** — regular sync factory - **toProvide** — regular sync factory
- **toProvideAsync** — async factory (if you need to await a Future) - **toProvideAsync** — async factory (if you need to await a Future)
- **toProvideWithParams / toProvideAsyncWithParams** — factories with runtime parameters - **toProvideWithParams / toProvideAsyncWithParams** — factories with runtime parameters
@@ -67,6 +107,14 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — single instance per Scope lifetime - `.singleton()` — single instance per Scope lifetime
- By default, every resolve creates a new object - By default, every resolve creates a new object
> **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
### Parameterized bindings ### Parameterized bindings
Allows you to create dependencies with runtime parameters, e.g., a service for a user with a given ID: Allows you to create dependencies with runtime parameters, e.g., a service for a user with a given ID:
@@ -78,6 +126,26 @@ bind<UserService>().toProvideWithParams((userId) => UserService(userId));
final userService = scope.resolve<UserService>(params: '123'); final userService = scope.resolve<UserService>(params: '123');
``` ```
> ⚠️ **Special note on using `.singleton()` after `toProvideWithParams` or `toProvideAsyncWithParams`:**
>
> If you declare a binding using `.toProvideWithParams((params) => ...)` (or its async variant) and then call `.singleton()`, the DI container will create and cache **only one instance** on the first `resolve` call—with the initial parameters. All subsequent calls to `resolve<T>(params: ...)` will return that same (cached) instance, **regardless of the new parameters**.
>
> **Example:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
>
> final a = scope.resolve<Service>(params: 1); // Creates Service(1)
> final b = scope.resolve<Service>(params: 2); // Returns Service(1)
> print(identical(a, b)); // true
> ```
>
> In other words:
> - The provider function receives parameters only on its first call,
> - After that, no matter what parameters are passed, the same instance is always returned.
>
> **Recommendation:**
> Use `.singleton()` with parameterized providers only if you are sure all parameters should always be identical, or you intentionally want a “master” instance. Otherwise, omit `.singleton()` to ensure a new object is constructed for every unique `params` value.
--- ---
## Scope management: dependency hierarchy ## Scope management: dependency hierarchy

View File

@@ -45,6 +45,48 @@ bind<Environment>().toInstanceAsync(setupFuture);
``` ```
> ⚠️ **Важное примечание по использованию toInstance в Module**
>
> Если вы регистрируете цепочку зависимостей через `toInstance` внутри метода `builder` вашего `Module`, нельзя в это же время вызывать `scope.resolve<T>()` для только что объявленного типа.
>
> CherryPick инициализирует биндинги последовательно внутри builder: в этот момент ещё не все зависимости зарегистрированы в DI-контейнере. Попытка воспользоваться `scope.resolve<T>()` для только что добавленного объекта приведёт к ошибке (`Can't resolve dependency ...`).
>
> **Как правильно:**
> Складывайте всю цепочку вручную до регистрации:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Ошибка! В этот момент A ещё не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Ошибка! В этот момент A ещё не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Примечание:** Это ограничение касается только `toInstance`. Для провайдеров (`toProvide`/`toProvideAsync`) и других стратегий вы можете использовать `scope.resolve<T>()` внутри builder без ограничений.
- **toProvide** — обычная синхронная фабрика. - **toProvide** — обычная синхронная фабрика.
- **toProvideAsync** — асинхронная фабрика (например, если нужно дожидаться Future). - **toProvideAsync** — асинхронная фабрика (например, если нужно дожидаться Future).
- **toProvideWithParams / toProvideAsyncWithParams** — фабрики с параметрами. - **toProvideWithParams / toProvideAsyncWithParams** — фабрики с параметрами.
@@ -68,6 +110,15 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — один инстанс на всё время жизни Scope. - `.singleton()` — один инстанс на всё время жизни Scope.
- По умолчанию каждый resolve создаёт новый объект. - По умолчанию каждый resolve создаёт новый объект.
> **Примечание о `.singleton()` и `.toInstance()`:**
>
> Вызов `.singleton()` после `.toInstance()` не изменяет поведения биндинга: объект, переданный через `toInstance()`, и так всегда будет "единственным" (single instance), возвращаемым при каждом resolve.
>
> Применять `.singleton()` к уже существующему объекту нет необходимости — этот вызов ничего не меняет.
>
> `.singleton()` нужен только для провайдеров (например, `toProvide`/`toProvideAsync`), чтобы зафиксировать единственный экземпляр, создаваемый фабрикой.
### Параметрические биндинги ### Параметрические биндинги
Позволяют создавать зависимости с runtime-параметрами — например, сервис для пользователя с ID: Позволяют создавать зависимости с runtime-параметрами — например, сервис для пользователя с ID:
@@ -79,6 +130,26 @@ bind<UserService>().toProvideWithParams((userId) => UserService(userId));
final userService = scope.resolve<UserService>(params: '123'); final userService = scope.resolve<UserService>(params: '123');
``` ```
> ⚠️ **Особенности использования `.singleton()` после `toProvideWithParams` или `toProvideAsyncWithParams`:**
>
> Если вы объявляете биндинг через `.toProvideWithParams((params) => ...)` (или асинхронный вариант) и затем вызываете `.singleton()`, DI-контейнер создаст и закэширует **только один экземпляр** при первом вызове `resolve` — с первыми переданными параметрами. Все последующие вызовы `resolve<T>(params: ...)` вернут этот же (кэшированный) объект **независимо от новых параметров**.
>
> **Пример:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
>
> final a = scope.resolve<Service>(params: 1); // Создаётся Service(1)
> final b = scope.resolve<Service>(params: 2); // Возвращается уже Service(1)
> print(identical(a, b)); // true
> ```
>
> То есть:
> - параметры работают только для первого вызова,
> - дальше всегда возвращается экземпляр, созданный при первом обращении.
>
> **Рекомендация:**
> Используйте `.singleton()` совместно с провайдерами с параметрами только тогда, когда вы точно уверены, что все параметры всегда должны совпадать, или нужны именно “мастер”-экземпляры. В противном случае не используйте `.singleton()`, чтобы каждый вызов с новыми parameters создавал новый объект.
--- ---
## Управление Scope'ами: иерархия зависимостей ## Управление Scope'ами: иерархия зависимостей

View File

@@ -0,0 +1,178 @@
# Release - CherryPick 3.x
> **CherryPick** — a lightweight and modular DI framework for Dart and Flutter that solves dependency injection through strong typing, code generation, and dependency control.
Version **3.x** was recently released with significant improvements.
## Main Changes in 3.x
* **O(1) dependency resolution** — thanks to Map indexing of bindings, performance does not depend on the size of the scope in the DI graph. This provides noticeable speedup in large projects.
* **Protection against circular dependencies** — checking works both within a single scope and across the entire hierarchy. When a cycle is detected, an informative exception with the dependency chain is thrown.
* **Integration with Talker** — all DI events (registration, creation, deletion, errors) are logged and can be displayed in the console or UI.
* **Automatic resource cleanup** — objects implementing `Disposable` are properly released when the scope is closed.
* **Stabilized declarative approach support** — annotations and code generation now work more reliably and are more convenient for use in projects.
## Resource Cleanup Example
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket closed!');
}
}
class AppModule extends Module {
@override
void builder(Scope currentScope) {
// singleton Api
bind<MyServiceWithSocket>()
.toProvide(() => MyServiceWithSocket())
.singleton();
}
}
scope.installModules([AppModule()]);
await CherryPick.closeRootScope(); // will wait for async dispose to complete
```
## Circular Dependency Checking
One of the new features in CherryPick 3.x is built-in cycle protection.
This helps catch situations early where services start depending on each other recursively.
### How to Enable Checking
For checking within a single scope:
```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
For global checking across the entire hierarchy:
```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
### How a Cycle Can Occur
Suppose we have two services that depend on each other:
```dart
class UserService {
final OrderService orderService;
UserService(this.orderService);
}
class OrderService {
final UserService userService;
OrderService(this.userService);
}
```
If we register them in the same scope:
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(scope.resolve()));
bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
}
}
final scope = CherryPick.openRootScope()
..enableCycleDetection()
..installModules([AppModule()]);
scope.resolve<UserService>();
```
Then when trying to resolve the dependency, an exception will be thrown:
```bash
❌ Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
This way, the error is detected immediately, not "somewhere in runtime".
## Integration with Talker
CherryPick 3.x allows logging all DI events through [Talker](https://pub.dev/packages/talker): registration, object creation, deletion, and errors. This is convenient for debugging and diagnosing the dependency graph.
Connection example:
```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```
After this, DI events will be displayed in the console or UI:
```bash
┌───────────────────────────────────────────────────────────────
[info] 9:41:33 | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
[verbose] 9:41:33 | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```
In the log, you can see when scopes are created, which objects are registered and deleted, and catch errors and cycles in real time.
## Declarative Approach with Annotations
In addition to fully programmatic module descriptions, CherryPick supports **declarative DI style through annotations**.
This allows minimizing manual code and automatically generating modules and mixins for automatic dependency injection.
Example of a declarative module:
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
````
After code generation, you can automatically inject dependencies into widgets or services:
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
This way you can choose an approach in development: **programmatic (imperative) with explicit dependency registration** or **declarative through annotations**.
## Who Might Find CherryPick Useful?
* Projects where it's important to guarantee **no cycles in the dependency graph**;
* Teams that want to **minimize manual DI code** and use a declarative style with annotations;
* Applications that require **automatic resource cleanup** (sockets, controllers, streams).
## Useful Links
* 📦 Package: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Code: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Documentation: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)

View File

@@ -0,0 +1,180 @@
# Release - CherryPick 3.x
> **CherryPick** — лёгкий и модульный DI-фреймворк для Dart и Flutter, который решает задачу через строгую типизацию, кодогенерацию и контроль за зависимостями.
Недавно вышла версия **3.x**, где появились заметные улучшения.
## Основные изменения в 3.x
* **O(1) разрешение зависимостей** — благодаря Map-индексации биндингов производительность не зависит от размера скоупа в DI графе. На больших проектах это даёт ощутимое ускорение.
* **Защита от циклических зависимостей** — проверка работает как внутри одного scope, так и во всей иерархии. При обнаружении цикла выбрасывается информативное исключение с цепочкой зависимостей.
* **Интеграция с Talker** — все события DI (регистрация, создание, удаление, ошибки) логируются и могут выводиться в консоль или UI.
* **Автоматическая очистка ресурсов** — объекты, реализующие `Disposable`, корректно освобождаются при закрытии scope.
* **Стабилизирована поддержка декларативного подхода** — аннотации и генерация кода теперь работают надёжнее и удобнее для использования в проектах.
## Пример с очисткой ресурсов
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket закрыт!');
}
}
class AppModule extends Module {
@override
void builder(Scope currentScope) {
// singleton Api
bind<MyServiceWithSocket>()
.toProvide(() => MyServiceWithSocket())
.singleton();
}
}
scope.installModules([AppModule()]);
await CherryPick.closeRootScope(); // дождётся завершения async dispose
```
## Проверка циклических зависимостей
Одна из новинок CherryPick 3.x — встроенная защита от циклов.
Это помогает на раннем этапе отлавливать ситуации, когда сервисы начинают зависеть друг от друга рекурсивно.
### Как включить проверку
Для проверки внутри одного scope:
```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
Для глобальной проверки во всей иерархии:
```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
### Как может возникнуть цикл
Предположим, у нас есть два сервиса, которые зависят друг от друга:
```dart
class UserService {
final OrderService orderService;
UserService(this.orderService);
}
class OrderService {
final UserService userService;
OrderService(this.userService);
}
```
Если зарегистрировать их в одном scope:
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(scope.resolve());
bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
}
}
final scope = CherryPick.openRootScope()
..enableCycleDetection()
..installModules([AppModule()]);
scope.resolve<UserService>();
```
То при попытке разрешить зависимость будет выброшено исключение:
```bash
❌ Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
Таким образом, ошибка выявляется сразу, а не «где-то в runtime».
## Интеграция с Talker
CherryPick 3.x позволяет логировать все события DI через [Talker](https://pub.dev/packages/talker): регистрацию, создание объектов, удаление и ошибки. Это удобно для отладки и диагностики графа зависимостей.
Пример подключения:
```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```
После этого в консоли или UI будут отображаться события DI:
```bash
┌───────────────────────────────────────────────────────────────
[info] 9:41:33 | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
[verbose] 9:41:33 | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```
В логе можно увидеть, когда scope создаётся, какие объекты регистрируются и удаляются, а также отлавливать ошибки и циклы в реальном времени.
## Декларативный подход с аннотациями
Помимо полностью программного описания модулей, CherryPick поддерживает **декларативный стиль DI через аннотации**.
Это позволяет минимизировать ручной код и автоматически генерировать модули и mixin для автоподстановки зависимостей.
Пример декларативного модуля:
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
````
После генерации кода можно автоматически подтягивать зависимости в виджеты или сервисы:
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
Таким образом можно выбрать подход в разработке: **программный (императивный) с явной регистрацией зависимостей** или **декларативный через аннотации**.
## Кому может быть полезен CherryPick?
* проектам, где важно гарантировать **отсутствие циклов в графе зависимостей**;
* командам, которые хотят **минимизировать ручной DI-код** и использовать декларативный стиль с аннотациями;
* приложениям, где требуется **автоматическое освобождение ресурсов** (сокеты, контроллеры, потоки).
## Полезные ссылки
* 📦 Пакет: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Код: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Документация: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)

244
doc/presentation_ru.md Normal file
View File

@@ -0,0 +1,244 @@
---
marp: true
---
<!--
#backgroundImage: url('./doc/assets/image.png')
backgroundSize: cover
-->
# CherryPick 3.x
### Быстро. Безопасно. Просто.
Современный DI-framework для Dart и Flutter
Автор: Сергей Пеньковский
---
<!--
backgroundImage: none
-->
## Что такое CherryPick?
- Лёгкий и модульный framework для внедрения зависимостей (DI)
- Фокус: производительность, безопасность и лаконичный код
- Применяется во frontend, backend, CLI
---
## Эволюция: что нового в 3.x?
- Оптимизация скорости разрешения зависимостей
- Интеграция с Talker для наглядного логирования DI-событий
- Защита от циклических зависимостей на уровне ядра
- Полностью декларативное описание DI через аннотации и генерацию кода
- Автоматическая очистка ресурсов
---
## Быстро
* Мгновенное разрешение зависимостей
---
### Мгновенное разрешение зависимостей
- Операция resolve<T> теперь выполняется за O(1)
- Используется Map-индексация всех биндингов в каждом скоупе (в среднем ускорение в 10x+ на крупных графах)
- Производительность не зависит от размера приложения
---
## Безопасно
* Циклические зависимости больше не страшны
* Интеграция с Talker и расширенное логирование
---
### Циклические зависимости больше не страшны
- CherryPick 3.x автоматически выявляет циклы при разрешении зависимостей.
- Возможна проверка как внутри отдельного scope, так и во всём DI-графе (глобально).
---
#### Как включить проверку циклов
- Для защиты только внутри одного scope:
```dart
// 1. Для текущего scope (локальная проверка)
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
- Для защиты всей иерархии скоупов:
```dart
// 2. Для всей иерархии скоупов (глобальная проверка)
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
---
#### Пример обработки ошибки
При обнаружении цикла будет выброшено исключение с подробной трассировкой:
```dart
try {
scope.resolve<A>();
} on CircularDependencyException catch(e) {
print(e.dependencyChain);
}
```
```bash
=== Circular Dependency Detection Example ===
1. Attempt to create a scope with circular dependencies:
❌ Circular dependency detected: CircularDependencyException: Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
---
### Интеграция с Talker и расширенное логирование
- Всё, что происходит в DI: регистрация, создание, удаление, ошибки ― теперь логируется!
- Достаточно подключить observer:
```dart
final talker = Talker();
final talkerLogger = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(talkerLogger);
```
- Логи сразу видны в консоли, UI
```bash
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────
[info] | 9:41:33 89ms | [scope opened][CherryPick] scope_1757054493089_7072
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────
[verbose] | 9:41:33 90ms | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────
```
---
## Просто
* Декларативный DI
* Автоматическая очистка ресурсов
---
### Декларативный DI: аннотации и генерация кода
- Описывайте зависимости с помощью аннотаций
- Автоматически генерируется модуль DI и mixin для автоподстановки зависимостей
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
```
Регистрация модуля
```dart
final scope = openRootScope()
..installModules([$AppModule()]);
```
---
### Field injection: минимум кода — максимум удобства
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
- После генерации mixin и вызова `screen._inject()` — зависимости готовы
- Сильная типизация, никаких ручных вызовов resolve
---
## Автоматическая очистка ресурсов
Автоматическая очистка ресурсов (контроллеры, потоки, сокеты, файлы и др.).
Если вы регистрируете объект, реализующий Disposable, через DI-контейнер, CherryPick вызовет его метод dispose() при закрытии скоупа.
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket закрыт!');
}
}
scope.installModules([
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
]);
await CherryPick.closeRootScope(); // дождётся завершения async очистки
```
---
## Почему это удобно?
### Сравнение с ручным DI
|| Аннотации | Ручной DI |
|:---|:-----------|:------------|
|Гибко|✅|✅|
|Кратко|✅|❌|
|Безопасно|✅|❌ (легко ошибиться)|
---
## CherryPick 3.x: ваш DI-фреймворк
- Быстрое разрешение зависимостей
- Гарантия безопасности и тестируемости
- Интеграция с логированием
- Максимально простой и декларативный код
---
<!--
#backgroundImage: url('./doc/assets/image.png')
backgroundSize: cover
-->
## Спасибо за внимание
---
## Вопросы?
- Try CherryPick - [https://pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
- Contributing — [https://github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
- Документация и примеры — [https://cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)
- Готов помочь — пишите, пробуйте, внедряйте!

View File

@@ -9,11 +9,7 @@ void main() {
// Создаем модуль, который будет предоставлять UseCase // Создаем модуль, который будет предоставлять UseCase
]); ]);
runApp( runApp(const CherryPickProvider(child: MyApp()));
const CherryPickProvider(
child: MyApp(),
),
);
} }
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
@@ -21,10 +17,6 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return CherryPickProvider( return CherryPickProvider(child: MaterialApp(home: MyHomePage()));
child: MaterialApp(
home: MyHomePage(),
),
);
} }
} }

View File

@@ -11,12 +11,8 @@ class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
//_inject(context); // Make sure this function is called in context //_inject(context); // Make sure this function is called in context
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(title: const Text('Example App')),
title: const Text('Example App'), body: Center(child: Text(useCase.fetchData())),
),
body: Center(
child: Text(useCase.fetchData()),
),
); );
} }
} }

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: _fe_analyzer_shared name: _fe_analyzer_shared
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "82.0.0" version: "91.0.0"
analyzer: analyzer:
dependency: transitive dependency: transitive
description: description:
name: analyzer name: analyzer
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0" sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.4.5" version: "8.4.1"
args: args:
dependency: transitive dependency: transitive
description: description:
@@ -29,10 +29,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: async name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.12.0" version: "2.13.0"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:
@@ -45,50 +45,50 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: build name: build
sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.2" version: "3.1.0"
build_config: build_config:
dependency: transitive dependency: transitive
description: description:
name: build_config name: build_config
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1 sha256: "4f64382b97504dc2fcdf487d5aae33418e08b4703fc21249e4db6d804a4d0187"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.1" version: "1.2.0"
build_daemon: build_daemon:
dependency: transitive dependency: transitive
description: description:
name: build_daemon name: build_daemon
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9" sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.0.2" version: "4.1.1"
build_resolvers: build_resolvers:
dependency: transitive dependency: transitive
description: description:
name: build_resolvers name: build_resolvers
sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0 sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.4" version: "3.0.3"
build_runner: build_runner:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: build_runner name: build_runner
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99" sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.15" version: "2.7.1"
build_runner_core: build_runner_core:
dependency: transitive dependency: transitive
description: description:
name: build_runner_core name: build_runner_core
sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021" sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.0.0" version: "9.3.1"
built_collection: built_collection:
dependency: transitive dependency: transitive
description: description:
@@ -101,10 +101,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: built_value name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4 sha256: "7931c90b84bc573fef103548e354258ae4c9d28d140e41961df6843c5d60d4d8"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.9.5" version: "8.12.3"
characters: characters:
dependency: transitive dependency: transitive
description: description:
@@ -117,38 +117,38 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: checked_yaml name: checked_yaml
sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.3" version: "2.0.4"
cherrypick: cherrypick:
dependency: "direct main" dependency: "direct main"
description: description:
path: "../../cherrypick" path: "../../cherrypick"
relative: true relative: true
source: path source: path
version: "3.0.0-dev.8" version: "3.0.2"
cherrypick_annotations: cherrypick_annotations:
dependency: "direct main" dependency: "direct main"
description: description:
path: "../../cherrypick_annotations" path: "../../cherrypick_annotations"
relative: true relative: true
source: path source: path
version: "1.1.1" version: "4.0.0-dev.0"
cherrypick_flutter: cherrypick_flutter:
dependency: "direct main" dependency: "direct main"
description: description:
path: "../../cherrypick_flutter" path: "../../cherrypick_flutter"
relative: true relative: true
source: path source: path
version: "1.1.3-dev.8" version: "3.0.2"
cherrypick_generator: cherrypick_generator:
dependency: "direct dev" dependency: "direct dev"
description: description:
path: "../../cherrypick_generator" path: "../../cherrypick_generator"
relative: true relative: true
source: path source: path
version: "1.1.1" version: "4.0.0-dev.0"
clock: clock:
dependency: transitive dependency: transitive
description: description:
@@ -161,10 +161,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: code_builder name: code_builder
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.10.1" version: "4.11.1"
collection: collection:
dependency: transitive dependency: transitive
description: description:
@@ -185,10 +185,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: crypto name: crypto
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.6" version: "3.0.7"
cupertino_icons: cupertino_icons:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -201,18 +201,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: dart_style name: dart_style
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac" sha256: a9c30492da18ff84efe2422ba2d319a89942d93e58eb0b73d32abe822ef54b7b
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.1" version: "3.1.3"
fake_async: fake_async:
dependency: transitive dependency: transitive
description: description:
name: fake_async name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.3.2" version: "1.3.3"
file: file:
dependency: transitive dependency: transitive
description: description:
@@ -238,10 +238,10 @@ packages:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: flutter_lints name: flutter_lints
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.0.0" version: "6.0.0"
flutter_test: flutter_test:
dependency: "direct dev" dependency: "direct dev"
description: flutter description: flutter
@@ -271,14 +271,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.3.2" version: "2.3.2"
http:
dependency: transitive
description:
name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
http_multi_server: http_multi_server:
dependency: transitive dependency: transitive
description: description:
@@ -291,10 +283,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: http_parser name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.0.2" version: "4.1.2"
io: io:
dependency: transitive dependency: transitive
description: description:
@@ -303,54 +295,46 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.5" version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf
url: "https://pub.dev"
source: hosted
version: "0.7.1"
json_annotation: json_annotation:
dependency: transitive dependency: transitive
description: description:
name: json_annotation name: json_annotation
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.9.0" version: "4.10.0"
leak_tracker: leak_tracker:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "10.0.8" version: "11.0.2"
leak_tracker_flutter_testing: leak_tracker_flutter_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_flutter_testing name: leak_tracker_flutter_testing
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.9" version: "3.0.10"
leak_tracker_testing: leak_tracker_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_testing name: leak_tracker_testing
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.1" version: "3.0.2"
lints: lints:
dependency: transitive dependency: transitive
description: description:
name: lints name: lints
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413" sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.0.0" version: "6.0.0"
logging: logging:
dependency: transitive dependency: transitive
description: description:
@@ -379,10 +363,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.16.0" version: "1.17.0"
mime: mime:
dependency: transitive dependency: transitive
description: description:
@@ -411,10 +395,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: pool name: pool
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.5.1" version: "1.5.2"
pub_semver: pub_semver:
dependency: transitive dependency: transitive
description: description:
@@ -427,26 +411,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: pubspec_parse name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0" sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.0" version: "1.5.0"
shelf: shelf:
dependency: transitive dependency: transitive
description: description:
name: shelf name: shelf
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.1" version: "1.4.2"
shelf_web_socket: shelf_web_socket:
dependency: transitive dependency: transitive
description: description:
name: shelf_web_socket name: shelf_web_socket
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67 sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.1" version: "3.0.0"
sky_engine: sky_engine:
dependency: transitive dependency: transitive
description: flutter description: flutter
@@ -456,10 +440,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: source_gen name: source_gen
sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" sha256: "1d562a3c1f713904ebbed50d2760217fd8a51ca170ac4b05b0db490699dbac17"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" version: "4.2.0"
source_span: source_span:
dependency: transitive dependency: transitive
description: description:
@@ -512,10 +496,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.4" version: "0.7.7"
timing: timing:
dependency: transitive dependency: transitive
description: description:
@@ -536,26 +520,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.4" version: "2.2.0"
vm_service: vm_service:
dependency: transitive dependency: transitive
description: description:
name: vm_service name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "14.3.1" version: "15.0.2"
watcher: watcher:
dependency: transitive dependency: transitive
description: description:
name: watcher name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.1" version: "1.2.1"
web: web:
dependency: transitive dependency: transitive
description: description:
@@ -589,5 +573,5 @@ packages:
source: hosted source: hosted
version: "3.1.3" version: "3.1.3"
sdks: sdks:
dart: ">=3.7.0-0 <4.0.0" dart: ">=3.9.0 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54" flutter: ">=3.18.0-18.0.pre.54"

View File

@@ -5,7 +5,7 @@ publish_to: 'none'
version: 1.0.0+1 version: 1.0.0+1
environment: environment:
sdk: ">=3.5.2 <4.0.0" sdk: ">=3.9.0 <4.0.0"
dependencies: dependencies:
@@ -25,11 +25,11 @@ dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
flutter_lints: ^5.0.0 flutter_lints: ^6.0.0
cherrypick_generator: cherrypick_generator:
path: ../../cherrypick_generator path: ../../cherrypick_generator
build_runner: ^2.4.15 build_runner: ^2.5.0
# For information on the generic Dart part of this file, see the # For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec # following page: https://dart.dev/tools/pub/pubspec

View File

@@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:talker_flutter/talker_flutter.dart'; import 'package:talker_flutter/talker_flutter.dart';
import 'domain/repository/post_repository.dart'; import 'domain/repository/post_repository.dart';
import 'presentation/bloc/post_bloc.dart'; import 'presentation/bloc/post_bloc.dart';
import 'router/app_router.dart'; import 'router/app_router.dart';
@@ -14,9 +13,11 @@ part 'app.inject.cherrypick.g.dart';
class TalkerProvider extends InheritedWidget { class TalkerProvider extends InheritedWidget {
final Talker talker; final Talker talker;
const TalkerProvider({required this.talker, required super.child, super.key}); const TalkerProvider({required this.talker, required super.child, super.key});
static Talker of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<TalkerProvider>()!.talker; static Talker of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<TalkerProvider>()!.talker;
@override @override
bool updateShouldNotify(TalkerProvider oldWidget) => oldWidget.talker != talker; bool updateShouldNotify(TalkerProvider oldWidget) =>
oldWidget.talker != talker;
} }
@injectable() @injectable()

View File

@@ -4,7 +4,7 @@ part 'post_model.freezed.dart';
part 'post_model.g.dart'; part 'post_model.g.dart';
@freezed @freezed
class PostModel with _$PostModel { abstract class PostModel with _$PostModel {
const factory PostModel({ const factory PostModel({
required int id, required int id,
required String title, required String title,

View File

@@ -12,9 +12,9 @@ class PostRepositoryImpl implements PostRepository {
Future<Either<Exception, List<Post>>> getPosts() async { Future<Either<Exception, List<Post>>> getPosts() async {
try { try {
final posts = await api.getPosts(); final posts = await api.getPosts();
return Right(posts return Right(
.map((e) => Post(id: e.id, title: e.title, body: e.body)) posts.map((e) => Post(id: e.id, title: e.title, body: e.body)).toList(),
.toList()); );
} catch (e) { } catch (e) {
return Left(Exception(e.toString())); return Left(Exception(e.toString()));
} }

View File

@@ -22,7 +22,10 @@ abstract class AppModule extends Module {
@provide() @provide()
@singleton() @singleton()
TalkerDioLogger talkerDioLogger(Talker talker, TalkerDioLoggerSettings settings) => TalkerDioLogger(talker: talker, settings: settings); TalkerDioLogger talkerDioLogger(
Talker talker,
TalkerDioLoggerSettings settings,
) => TalkerDioLogger(talker: talker, settings: settings);
@instance() @instance()
int timeout() => 1000; int timeout() => 1000;
@@ -73,12 +76,14 @@ abstract class AppModule extends Module {
@provide() @provide()
@named('TestProvideWithParams1') @named('TestProvideWithParams1')
String testProvideWithParams1( String testProvideWithParams1(
@named('baseUrl') String baseUrl, @params() dynamic params) => @named('baseUrl') String baseUrl,
"hello $params"; @params() dynamic params,
) => "hello $params";
@provide() @provide()
@named('TestProvideAsyncWithParams1') @named('TestProvideAsyncWithParams1')
Future<String> testProvideAsyncWithParams1( Future<String> testProvideAsyncWithParams1(
@named('baseUrl') String baseUrl, @params() dynamic params) async => @named('baseUrl') String baseUrl,
"hello $params"; @params() dynamic params,
) async => "hello $params";
} }

Some files were not shown because too many files have changed in this diff Show More