Compare commits

...

61 Commits

Author SHA1 Message Date
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
Sergey Penkovsky
99e662124f chore(release): publish packages
- talker_cherrypick_logger@1.1.0-dev.3
2025-08-13 15:27:51 +03:00
Sergey Penkovsky
03f54981f3 chore(talker_cherrypick_logger): update package description in pubspec.yaml 2025-08-13 15:26:53 +03:00
159 changed files with 32214 additions and 1113 deletions

2
.fvmrc
View File

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

View File

@@ -3,6 +3,376 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 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
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`talker_cherrypick_logger` - `v1.1.0-dev.3`](#talker_cherrypick_logger---v110-dev3)
---
#### `talker_cherrypick_logger` - `v1.1.0-dev.3`
## 2025-08-13
### Changes

View File

@@ -1,4 +1,5 @@
# Contributors
- Sergey Penkovsky <sergey.penkovsky@gmail.com>
- Klim Yaroshevich <yarashevich_kv@st.by>
- [Sergey Penkovsky](https://github.com/pese-git)
- [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 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.
@@ -142,4 +147,4 @@ Please see:
---
**Happy Cherry Picking! 🍒**
**Happy Cherry Picking! 🍒**

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
@@ -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 |
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|------------------|------------|--------|----------|-------|----------|
| chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
| chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
| register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
| named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
| override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
| 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 |
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
## Peak Memory Usage (Peak RSS, Kb)
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|------------------|------------|--------|----------|--------|----------|
| chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
| chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
| register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
| 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
- **get_it** is the absolute leader in all scenarios, especially under deep/nested chains and async.
- **cherrypick** is highly competitive and much faster than riverpod on any complex graph.
- **riverpod** is only suitable for small/simple DI graphs due to major slowdowns with depth, async, or override.
- **get_it** remains the clear leader for both speed and memory usage (lowest latency across most scenarios; excellent memory efficiency even on deep chains).
- **kiwi** shows the lowest memory footprint in chainSingleton, but is unavailable for async chains.
- **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
- Use **get_it** for performance-critical and deeply nested graphs.
- Use **cherrypick** for scalable/testable apps if a small speed loss is acceptable.
- Use **riverpod** only if you rely on Flutter integration and your DI chains are simple.
- **get_it** (and often **kiwi**, if you don't need async): best for ultra-fast deep graphs and minimum peak memory.
- **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-резолвинг.
3. **ChainFactory** — все элементы цепочки — фабрики. Stateless построение графа.
4. **AsyncChain** — асинхронная цепочка (async factory). Тестирует async/await граф.
3. **ChainFactory** — все элементы цепочки — factory. Stateless построение графа.
4. **AsyncChain** — асинхронная цепочка (async factory). Тест async/await графа.
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 |
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|------------------|------------|--------|----------|-------|----------|
| chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
| chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
| register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
| named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
| override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
| 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 |
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
## Пиковое потребление памяти (Peak RSS, Кб)
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|------------------|------------|--------|----------|--------|----------|
| chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
| chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
| register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
| 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** всегда лидер, особенно на глубине/асинхронных графах.
- **cherrypick** заметно быстрее riverpod на сложных сценариях, опережая его в разы.
- **riverpod** подходит только для простых/небольших графов — при росте глубины или async/override резко проигрывает по скорости.
- **get_it** — абсолютный лидер по скорости и памяти на всех графах (минимальная задержка, небольшой peak RSS в любых цепочках).
- **kiwi** — минимальное потребление памяти в chainSingleton/Factory, но не для асинхронности.
- **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** для критичных к скорости приложений/сложных графов зависимостей.
- Выбирайте **cherrypick** для масштабируемых, тестируемых архитектур, если микросекундная разница не критична.
- **riverpod** уместен только для реактивного UI или простых графов DI.
- Используйте **get_it** (или **kiwi**, если не нужен async) для максимальной производительности и минимального пикового использования памяти.
- **yx_scope** — идеально для production-графов с миксом sync/async.
- **cherrypick** — хорошо для модульных и тестируемых приложений, если не требуется абсолютная “микросекундная” производительность.
- **riverpod** — только если граф плоский или нужно DI только для UI во Flutter.
---
_Обновлено: 8 августа 2025_
_Обновлено: 20 августа 2025._

View File

@@ -2,4 +2,4 @@ import 'package:benchmark_di/cli/benchmark_cli.dart';
Future<void> main(List<String> args) async {
await BenchmarkCliRunner().run(args);
}
}

View File

@@ -73,7 +73,8 @@ class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
_childDi!.resolve<UniversalService>();
break;
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 '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:cherrypick/cherrypick.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/get_it_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.
///
@@ -36,8 +40,11 @@ class BenchmarkCliRunner {
if (config.di == 'getit') {
final di = GetItAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<GetIt>(di,
chainCount: c, nestingDepth: d, mode: mode,
final benchAsync = UniversalChainAsyncBenchmark<GetIt>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
);
benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync,
@@ -45,8 +52,41 @@ class BenchmarkCliRunner {
repeats: config.repeats,
);
} else {
final benchSync = UniversalChainBenchmark<GetIt>(di,
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
final benchSync = UniversalChainBenchmark<GetIt>(
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(
benchmark: benchSync,
@@ -57,8 +97,12 @@ class BenchmarkCliRunner {
} else if (config.di == 'riverpod') {
final di = RiverpodAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
chainCount: c, nestingDepth: d, mode: mode,
final benchAsync = UniversalChainAsyncBenchmark<
Map<String, rp.ProviderBase<Object?>>>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
);
benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync,
@@ -66,8 +110,43 @@ class BenchmarkCliRunner {
repeats: config.repeats,
);
} else {
final benchSync = UniversalChainBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
final benchSync = UniversalChainBenchmark<
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(
benchmark: benchSync,
@@ -78,8 +157,11 @@ class BenchmarkCliRunner {
} else {
final di = CherrypickDIAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<Scope>(di,
chainCount: c, nestingDepth: d, mode: mode,
final benchAsync = UniversalChainAsyncBenchmark<Scope>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
);
benchResult = await BenchmarkRunner.runAsync(
benchmark: benchAsync,
@@ -87,8 +169,12 @@ class BenchmarkCliRunner {
repeats: config.repeats,
);
} else {
final benchSync = UniversalChainBenchmark<Scope>(di,
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
final benchSync = UniversalChainBenchmark<Scope>(
di,
chainCount: c,
nestingDepth: d,
mode: mode,
scenario: scenario,
);
benchResult = await BenchmarkRunner.runSync(
benchmark: benchSync,
@@ -103,7 +189,11 @@ class BenchmarkCliRunner {
var median = timings[timings.length ~/ 2];
var minVal = timings.first;
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({
'benchmark': 'Universal_$bench',
'chainCount': c,
@@ -128,6 +218,7 @@ class BenchmarkCliRunner {
'json': JsonReport(),
'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 {
/// Simple singleton registration benchmark
registerSingleton,
/// Chain of singleton dependencies
chainSingleton,
/// Chain using factories
chainFactory,
/// Async chain resolution
chainAsync,
/// Named registration benchmark
named,
/// Override/child-scope benchmark
override,
}
@@ -65,23 +70,32 @@ T parseEnum<T>(String value, List<T> values, T defaultValue) {
}
/// Parses comma-separated integer list from [s].
List<int> parseIntList(String s) =>
s.split(',').map((e) => int.tryParse(e.trim()) ?? 0).where((x) => x > 0).toList();
List<int> parseIntList(String s) => s
.split(',')
.map((e) => int.tryParse(e.trim()) ?? 0)
.where((x) => x > 0)
.toList();
/// CLI config describing what and how to benchmark.
class BenchmarkCliConfig {
/// Benchmarks enabled to run (scenarios).
final List<UniversalBenchmark> benchesToRun;
/// List of chain counts (parallel, per test).
final List<int> chainCounts;
/// List of nesting depths (max chain length, per test).
final List<int> nestDepths;
/// How many times to repeat each trial.
final int repeats;
/// How many times to warm-up before measuring.
final int warmups;
/// Output report format.
final String format;
/// Name of DI implementation ("cherrypick" or "getit")
final String di;
BenchmarkCliConfig({
@@ -105,7 +119,9 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
..addOption('repeat', abbr: 'r', defaultsTo: '2')
..addOption('warmup', abbr: 'w', defaultsTo: '1')
..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');
final result = parser.parse(args);
if (result['help'] == true) {
@@ -127,4 +143,4 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
format: result['format'] as String,
di: result['di'] as String? ?? 'cherrypick',
);
}
}

View File

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

View File

@@ -5,9 +5,10 @@ class JsonReport extends ReportGenerator {
/// No specific keys; outputs all fields in raw map.
@override
List<String> get keys => [];
/// Renders all result rows as a pretty-printed JSON array.
@override
String render(List<Map<String, dynamic>> rows) {
return '[\n${rows.map((r) => ' $r').join(',\n')}\n]';
}
}
}

View File

@@ -7,25 +7,46 @@ class MarkdownReport extends ReportGenerator {
/// List of columns (keys) to show in the Markdown table.
@override
final List<String> keys = [
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
'benchmark',
'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.
static const nameMap = {
'Universal_UniversalBenchmark.registerSingleton':'RegisterSingleton',
'Universal_UniversalBenchmark.chainSingleton':'ChainSingleton',
'Universal_UniversalBenchmark.chainFactory':'ChainFactory',
'Universal_UniversalBenchmark.chainAsync':'AsyncChain',
'Universal_UniversalBenchmark.named':'Named',
'Universal_UniversalBenchmark.override':'Override',
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
'Universal_UniversalBenchmark.named': 'Named',
'Universal_UniversalBenchmark.override': 'Override',
};
/// Renders all results as a formatted Markdown table with aligned columns and a legend.
@override
String render(List<Map<String, dynamic>> rows) {
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 readableName = nameMap[r['benchmark']] ?? r['benchmark'];
@@ -73,6 +94,6 @@ class MarkdownReport extends ReportGenerator {
> `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,25 +7,46 @@ class PrettyReport extends ReportGenerator {
/// List of columns to output in the pretty report.
@override
final List<String> keys = [
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
'benchmark',
'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.
static const nameMap = {
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
'Universal_UniversalBenchmark.named': 'Named',
'Universal_UniversalBenchmark.override': 'Override',
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
'Universal_UniversalBenchmark.named': 'Named',
'Universal_UniversalBenchmark.override': 'Override',
};
/// Renders the results as a header + tab-separated value table.
@override
String render(List<Map<String, dynamic>> rows) {
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 lines = rows.map((r) {

View File

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

View File

@@ -7,10 +7,13 @@ import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
class BenchmarkResult {
/// List of timings for each run (in microseconds).
final List<num> timings;
/// Difference in memory (RSS, in KB) after running.
final int memoryDiffKb;
/// Difference between peak RSS and initial RSS (in KB).
final int deltaPeakKb;
/// Peak RSS memory observed (in KB).
final int peakRssKb;
BenchmarkResult({
@@ -19,6 +22,7 @@ class BenchmarkResult {
required this.deltaPeakKb,
required this.peakRssKb,
});
/// Computes a BenchmarkResult instance from run timings and memory data.
factory BenchmarkResult.collect({
required List<num> timings,
@@ -64,7 +68,8 @@ class BenchmarkRunner {
rssValues.add(ProcessInfo.currentRss);
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].
@@ -91,6 +96,7 @@ class BenchmarkRunner {
rssValues.add(ProcessInfo.currentRss);
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 'di_adapter.dart';
/// Test module that generates a chain of service bindings for benchmarking.
///
/// Configurable by chain count, nesting depth, binding mode, and scenario
@@ -12,10 +11,13 @@ import 'di_adapter.dart';
class UniversalChainModule extends Module {
/// Number of chains to create.
final int chainCount;
/// Depth of each chain.
final int nestingDepth;
/// How modules are registered (factory/singleton/async).
final UniversalBindingMode bindingMode;
/// Which di scenario to generate (chained, named, etc).
final UniversalScenario scenario;
@@ -38,17 +40,18 @@ class UniversalChainModule extends Module {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
bind<UniversalService>()
.toProvideAsync(() async {
final prev = level > 1
? await currentScope.resolveAsync<UniversalService>(named: prevDepName)
: null;
return UniversalServiceImpl(
value: depName,
dependency: prev,
);
})
.withName(depName)
.singleton();
.toProvideAsync(() async {
final prev = level > 1
? await currentScope.resolveAsync<UniversalService>(
named: prevDepName)
: null;
return UniversalServiceImpl(
value: depName,
dependency: prev,
);
})
.withName(depName)
.singleton();
}
}
return;
@@ -58,13 +61,18 @@ class UniversalChainModule extends Module {
case UniversalScenario.register:
// Simple singleton registration.
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(value: 'reg', dependency: null))
.toProvide(
() => UniversalServiceImpl(value: 'reg', dependency: null))
.singleton();
break;
case UniversalScenario.named:
// Named factory registration for two distinct objects.
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl1')).withName('impl1');
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl2')).withName('impl2');
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(value: 'impl1'))
.withName('impl1');
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(value: 'impl2'))
.withName('impl2');
break;
case UniversalScenario.chain:
// Chain of nested services, with dependency on previous level by name.
@@ -79,7 +87,8 @@ class UniversalChainModule extends Module {
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(
value: depName,
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
dependency: currentScope.tryResolve<UniversalService>(
named: prevDepName),
))
.withName(depName)
.singleton();
@@ -88,7 +97,8 @@ class UniversalChainModule extends Module {
bind<UniversalService>()
.toProvide(() => UniversalServiceImpl(
value: depName,
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
dependency: currentScope.tryResolve<UniversalService>(
named: prevDepName),
))
.withName(depName);
break;
@@ -96,7 +106,9 @@ class UniversalChainModule extends Module {
bind<UniversalService>()
.toProvideAsync(() async => UniversalServiceImpl(
value: depName,
dependency: await currentScope.resolveAsync<UniversalService>(named: prevDepName),
dependency:
await currentScope.resolveAsync<UniversalService>(
named: prevDepName),
))
.withName(depName)
.singleton();
@@ -107,14 +119,16 @@ class UniversalChainModule extends Module {
// Регистрация алиаса без имени (на последний элемент цепочки)
final depName = '${chainCount}_$nestingDepth';
bind<UniversalService>()
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
.toProvide(
() => currentScope.resolve<UniversalService>(named: depName))
.singleton();
break;
case UniversalScenario.override:
// handled at benchmark level, но алиас нужен прямо в этом scope!
final depName = '${chainCount}_$nestingDepth';
bind<UniversalService>()
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
.toProvide(
() => currentScope.resolve<UniversalService>(named: depName))
.singleton();
break;
case UniversalScenario.asyncChain:
@@ -124,7 +138,6 @@ class UniversalChainModule extends Module {
}
}
class CherrypickDIAdapter extends DIAdapter<Scope> {
Scope? _scope;
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
@@ -170,9 +184,9 @@ class CherrypickDIAdapter extends DIAdapter<Scope> {
_scope!.resolveAsync<T>(named: named);
@override
void teardown() {
Future<void> teardown() async {
if (!_isSubScope) {
CherryPick.closeRootScope();
await CherryPick.closeRootScope();
_scope = null;
}
// SubScope teardown не требуется

View File

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

View File

@@ -80,9 +80,11 @@ class GetItAdapter extends DIAdapter<GetIt> {
getIt.registerSingletonAsync<UniversalService>(
() async {
final prev = level > 1
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
? await getIt.getAsync<UniversalService>(
instanceName: prevDepName)
: null;
return UniversalServiceImpl(value: depName, dependency: prev);
return UniversalServiceImpl(
value: depName, dependency: prev);
},
instanceName: depName,
);
@@ -90,11 +92,16 @@ class GetItAdapter extends DIAdapter<GetIt> {
}
break;
case UniversalScenario.register:
getIt.registerSingleton<UniversalService>(UniversalServiceImpl(value: 'reg', dependency: null));
getIt.registerSingleton<UniversalService>(
UniversalServiceImpl(value: 'reg', dependency: null));
break;
case UniversalScenario.named:
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl1'), instanceName: 'impl1');
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl2'), instanceName: 'impl2');
getIt.registerFactory<UniversalService>(
() => UniversalServiceImpl(value: 'impl1'),
instanceName: 'impl1');
getIt.registerFactory<UniversalService>(
() => UniversalServiceImpl(value: 'impl2'),
instanceName: 'impl2');
break;
case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) {
@@ -107,8 +114,8 @@ class GetItAdapter extends DIAdapter<GetIt> {
UniversalServiceImpl(
value: depName,
dependency: level > 1
? getIt<UniversalService>(instanceName: prevDepName)
: null,
? getIt<UniversalService>(instanceName: prevDepName)
: null,
),
instanceName: depName,
);
@@ -129,8 +136,9 @@ class GetItAdapter extends DIAdapter<GetIt> {
() async => UniversalServiceImpl(
value: depName,
dependency: level > 1
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
: null,
? await getIt.getAsync<UniversalService>(
instanceName: prevDepName)
: null,
),
instanceName: depName,
);
@@ -143,7 +151,8 @@ class GetItAdapter extends DIAdapter<GetIt> {
// handled at benchmark level
break;
}
if (scenario == UniversalScenario.chain || scenario == UniversalScenario.override) {
if (scenario == UniversalScenario.chain ||
scenario == UniversalScenario.override) {
final depName = '${chainCount}_$nestingDepth';
getIt.registerSingleton<UniversalService>(
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;
@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
? rp.ProviderContainer()
: rp.ProviderContainer(parent: _parent);
@@ -76,7 +78,8 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
}
@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 int chainCount,
required int nestingDepth,
@@ -86,25 +89,34 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
return (providers) {
switch (scenario) {
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;
case UniversalScenario.named:
providers['impl1'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl1'));
providers['impl2'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl2'));
providers['impl1'] = rp.Provider<UniversalService>(
(ref) => UniversalServiceImpl(value: 'impl1'));
providers['impl2'] = rp.Provider<UniversalService>(
(ref) => UniversalServiceImpl(value: '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';
providers[depName] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(
value: depName,
dependency: level > 1 ? ref.watch(providers[prevDepName] as rp.ProviderBase<UniversalService>) : null,
));
providers[depName] =
rp.Provider<UniversalService>((ref) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? ref.watch(providers[prevDepName]
as rp.ProviderBase<UniversalService>)
: null,
));
}
}
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;
case UniversalScenario.override:
// handled at benchmark level
@@ -114,24 +126,31 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
providers[depName] = rp.FutureProvider<UniversalService>((ref) async {
providers[depName] =
rp.FutureProvider<UniversalService>((ref) async {
return UniversalServiceImpl(
value: depName,
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,
);
});
}
}
final depName = '${chainCount}_$nestingDepth';
providers['UniversalService'] = rp.FutureProvider<UniversalService>((ref) async {
return await ref.watch((providers[depName] as rp.FutureProvider<UniversalService>).future);
providers['UniversalService'] =
rp.FutureProvider<UniversalService>((ref) async {
return await ref.watch(
(providers[depName] as rp.FutureProvider<UniversalService>)
.future);
});
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 {
/// Single registration.
register,
/// Chain of dependencies.
chain,
/// Named registrations.
named,
/// Child-scope override scenario.
override,
/// Asynchronous chain scenario.
asyncChain,
}

View File

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

View File

@@ -47,7 +47,7 @@ packages:
path: "../cherrypick"
relative: true
source: path
version: "3.0.0-dev.8"
version: "3.0.0"
collection:
dependency: transitive
description:
@@ -72,6 +72,14 @@ packages:
url: "https://pub.dev"
source: hosted
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:
dependency: transitive
description:
@@ -128,5 +136,13 @@ packages:
url: "https://pub.dev"
source: hosted
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:
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)
environment:
sdk: '>=3.0.0 <4.0.0'
sdk: '>=3.2.0 <4.0.0'
dependencies:
cherrypick:
@@ -12,6 +12,8 @@ dependencies:
args: ^2.7.0
get_it: ^8.2.0
riverpod: ^2.6.1
kiwi: ^5.0.1
yx_scope: ^1.1.2
dev_dependencies:
lints: ^5.0.0

View File

@@ -1,3 +1,34 @@
## 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
- **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` 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
```dart
// Provide a direct instance
Binding<String>().toInstance("Hello world");
void builder(Scope scope) {
// Provide a direct instance
bind<String>().toInstance("Hello world");
// Provide an async direct instance
Binding<String>().toInstanceAsync(Future.value("Hello world"));
// Provide an async direct instance
bind<String>().toInstanceAsync(Future.value("Hello world"));
// Provide a lazy sync instance using a factory
Binding<String>().toProvide(() => "Hello world");
// Provide a lazy sync instance using a factory
bind<String>().toProvide(() => "Hello world");
// Provide a lazy async instance using a factory
Binding<String>().toProvideAsync(() async => "Hello async world");
// Provide a lazy async instance using a factory
bind<String>().toProvideAsync(() async => "Hello async world");
// Provide an instance with dynamic parameters (sync)
Binding<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (sync)
bind<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (async)
Binding<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Provide an instance with dynamic parameters (async)
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Named instance for retrieval by name
Binding<String>().toProvide(() => "Hello world").withName("my_string");
// Named instance for retrieval by name
bind<String>().toProvide(() => "Hello world").withName("my_string");
// Mark as singleton (only one instance within the scope)
Binding<String>().toProvide(() => "Hello world").singleton();
// Mark as singleton (only one instance within the scope)
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
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
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -47,19 +47,19 @@ class FeatureModule extends Module {
Future<void> main() async {
try {
final scope = CherryPick.openRootScope().installModules([AppModule()]);
final scope = CherryPick.openRootScope().installModules([AppModule()]);
final subScope = scope
.openSubScope("featureScope")
.installModules([FeatureModule(isMock: true)]);
// Asynchronous instance resolution
final dataBloc = await subScope.resolveAsync<DataBloc>();
dataBloc.data.listen(
(d) => print('Received data: $d'),
onError: (e) => print('Error: $e'),
onDone: () => print('DONE'),
);
// Asynchronous instance resolution
final dataBloc = await subScope.resolveAsync<DataBloc>();
dataBloc.data.listen(
(d) => print('Received data: $d'),
onError: (e) => print('Error: $e'),
onDone: () => print('DONE'),
);
await dataBloc.fetchData();
} catch (e) {

View File

@@ -8,7 +8,7 @@ class DatabaseService {
class ApiService {
final DatabaseService database;
ApiService(this.database);
void fetchData() {
database.connect();
print('📡 Fetching data via API');
@@ -18,7 +18,7 @@ class ApiService {
class UserService {
final ApiService apiService;
UserService(this.apiService);
void getUser(String id) {
apiService.fetchData();
print('👤 Fetching user: $id');
@@ -36,18 +36,16 @@ class DatabaseModule extends Module {
class ApiModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiService>().toProvide(() => ApiService(
currentScope.resolve<DatabaseService>()
));
bind<ApiService>()
.toProvide(() => ApiService(currentScope.resolve<DatabaseService>()));
}
}
class UserModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(
currentScope.resolve<ApiService>()
));
bind<UserService>()
.toProvide(() => UserService(currentScope.resolve<ApiService>()));
}
}
@@ -65,74 +63,75 @@ class CircularServiceB {
class CircularModuleA extends Module {
@override
void builder(Scope currentScope) {
bind<CircularServiceA>().toProvide(() => CircularServiceA(
currentScope.resolve<CircularServiceB>()
));
bind<CircularServiceA>().toProvide(
() => CircularServiceA(currentScope.resolve<CircularServiceB>()));
}
}
class CircularModuleB extends Module {
@override
void builder(Scope currentScope) {
bind<CircularServiceB>().toProvide(() => CircularServiceB(
currentScope.resolve<CircularServiceA>()
));
bind<CircularServiceB>().toProvide(
() => CircularServiceB(currentScope.resolve<CircularServiceA>()));
}
}
void main() {
print('=== Improved CherryPick Helper Demonstration ===\n');
// Example 1: Global enabling of cycle detection
print('1. Globally enable cycle detection:');
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
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
globalScope.installModules([
DatabaseModule(),
ApiModule(),
UserModule(),
]);
final userService = globalScope.resolve<UserService>();
userService.getUser('user123');
print('');
// Example 2: Safe scope creation
print('2. Creating safe scopes:');
CherryPick.closeRootScope(); // Закрываем предыдущий скоуп
CherryPick.disableGlobalCycleDetection(); // Отключаем глобальную настройку
// Создаем безопасный скоуп (с автоматически включенным обнаружением)
final safeScope = CherryPick.openSafeRootScope();
print('✅ Safe scope created with cycle detection: ${safeScope.isCycleDetectionEnabled}');
print(
'✅ Safe scope created with cycle detection: ${safeScope.isCycleDetectionEnabled}');
safeScope.installModules([
DatabaseModule(),
ApiModule(),
UserModule(),
]);
final safeUserService = safeScope.resolve<UserService>();
safeUserService.getUser('safe_user456');
print('');
// Example 3: Detecting cycles
print('3. Detecting circular dependencies:');
final cyclicScope = CherryPick.openSafeRootScope();
cyclicScope.installModules([
CircularModuleA(),
CircularModuleB(),
]);
try {
cyclicScope.resolve<CircularServiceA>();
print('❌ This should not be executed');
@@ -144,87 +143,96 @@ void main() {
}
}
print('');
// Example 4: Managing detection for specific scopes
print('4. Managing detection for specific scopes:');
CherryPick.closeRootScope();
// Создаем скоуп без обнаружения
// ignore: unused_local_variable
final specificScope = CherryPick.openRootScope();
print(' Detection in root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
print(
' Detection in root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
// Включаем обнаружение для конкретного скоупа
CherryPick.enableCycleDetectionForScope();
print('✅ Detection enabled for root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
print(
'✅ Detection enabled for root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
// Создаем дочерний скоуп
// ignore: unused_local_variable
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');
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('');
// Example 5: Creating safe child scopes
print('5. Creating safe child scopes:');
final safeFeatureScope = CherryPick.openSafeScope(scopeName: 'feature.payments');
print('✅ Safe feature scope created: ${safeFeatureScope.isCycleDetectionEnabled}');
final safeFeatureScope =
CherryPick.openSafeScope(scopeName: 'feature.payments');
print(
'✅ Safe feature scope created: ${safeFeatureScope.isCycleDetectionEnabled}');
// 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('');
// Example 6: Tracking resolution chains
print('6. Tracking dependency resolution chains:');
final trackingScope = CherryPick.openSafeRootScope();
trackingScope.installModules([
DatabaseModule(),
ApiModule(),
UserModule(),
]);
print(' Chain before resolve: ${CherryPick.getCurrentResolutionChain()}');
// The chain is populated during resolution, but cleared after completion
// ignore: unused_local_variable
final trackedUserService = trackingScope.resolve<UserService>();
print(' Chain after resolve: ${CherryPick.getCurrentResolutionChain()}');
print('');
// Example 7: Usage recommendations
print('7. Recommended usage:');
print('');
print('🔧 Development mode:');
print(' CherryPick.enableGlobalCycleDetection(); // Enable globally');
print(' or');
print(' final scope = CherryPick.openSafeRootScope(); // Safe scope');
print('');
print('🚀 Production mode:');
print(' CherryPick.disableGlobalCycleDetection(); // Disable for performance');
print(
' CherryPick.disableGlobalCycleDetection(); // Disable for performance');
print(' final scope = CherryPick.openRootScope(); // Regular scope');
print('');
print('🧪 Testing:');
print(' setUp(() => CherryPick.enableGlobalCycleDetection());');
print(' tearDown(() => CherryPick.closeRootScope());');
print('');
print('🎯 Feature-specific:');
print(' CherryPick.enableCycleDetectionForScope(scopeName: "feature.critical");');
print(
' CherryPick.enableCycleDetectionForScope(scopeName: "feature.critical");');
print(' // Enable only for critical features');
// Cleanup
CherryPick.closeRootScope();
CherryPick.disableGlobalCycleDetection();
print('\n=== Demonstration complete ===');
}

View File

@@ -3,9 +3,9 @@ import 'package:cherrypick/cherrypick.dart';
// Пример сервисов с циклической зависимостью
class UserService {
final OrderService orderService;
UserService(this.orderService);
void createUser(String name) {
print('Creating user: $name');
// Пытаемся получить заказы пользователя, что создает циклическую зависимость
@@ -15,9 +15,9 @@ class UserService {
class OrderService {
final UserService userService;
OrderService(this.userService);
void getOrdersForUser(String userName) {
print('Getting orders for user: $userName');
// Пытаемся получить информацию о пользователе, что создает циклическую зависимость
@@ -29,18 +29,16 @@ class OrderService {
class UserModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(
currentScope.resolve<OrderService>()
));
bind<UserService>()
.toProvide(() => UserService(currentScope.resolve<OrderService>()));
}
}
class OrderModule extends Module {
@override
void builder(Scope currentScope) {
bind<OrderService>().toProvide(() => OrderService(
currentScope.resolve<UserService>()
));
bind<OrderService>()
.toProvide(() => OrderService(currentScope.resolve<UserService>()));
}
}
@@ -49,7 +47,7 @@ class UserRepository {
void createUser(String name) {
print('Creating user in repository: $name');
}
String getUserInfo(String name) {
return 'User info for: $name';
}
@@ -59,7 +57,7 @@ class OrderRepository {
void createOrder(String orderId, String userName) {
print('Creating order $orderId for user: $userName');
}
List<String> getOrdersForUser(String userName) {
return ['order1', 'order2', 'order3'];
}
@@ -67,13 +65,13 @@ class OrderRepository {
class ImprovedUserService {
final UserRepository userRepository;
ImprovedUserService(this.userRepository);
void createUser(String name) {
userRepository.createUser(name);
}
String getUserInfo(String name) {
return userRepository.getUserInfo(name);
}
@@ -82,17 +80,17 @@ class ImprovedUserService {
class ImprovedOrderService {
final OrderRepository orderRepository;
final ImprovedUserService userService;
ImprovedOrderService(this.orderRepository, this.userService);
void createOrder(String orderId, String userName) {
// Проверяем, что пользователь существует
final userInfo = userService.getUserInfo(userName);
print('User exists: $userInfo');
orderRepository.createOrder(orderId, userName);
}
List<String> getOrdersForUser(String userName) {
return orderRepository.getOrdersForUser(userName);
}
@@ -103,9 +101,8 @@ class ImprovedUserModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserRepository>().singleton().toProvide(() => UserRepository());
bind<ImprovedUserService>().toProvide(() => ImprovedUserService(
currentScope.resolve<UserRepository>()
));
bind<ImprovedUserService>().toProvide(
() => ImprovedUserService(currentScope.resolve<UserRepository>()));
}
}
@@ -114,81 +111,82 @@ class ImprovedOrderModule extends Module {
void builder(Scope currentScope) {
bind<OrderRepository>().singleton().toProvide(() => OrderRepository());
bind<ImprovedOrderService>().toProvide(() => ImprovedOrderService(
currentScope.resolve<OrderRepository>(),
currentScope.resolve<ImprovedUserService>()
));
currentScope.resolve<OrderRepository>(),
currentScope.resolve<ImprovedUserService>()));
}
}
void main() {
print('=== Circular Dependency Detection Example ===\n');
// Example 1: Demonstrate circular dependency
print('1. Attempt to create a scope with circular dependencies:');
try {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection(); // Включаем обнаружение циклических зависимостей
scope
.enableCycleDetection(); // Включаем обнаружение циклических зависимостей
scope.installModules([
UserModule(),
OrderModule(),
]);
// Это должно выбросить CircularDependencyException
final userService = scope.resolve<UserService>();
print('UserService created: $userService');
} catch (e) {
print('❌ Circular dependency detected: $e\n');
}
// Example 2: Without circular dependency detection (dangerous!)
print('2. Same code without circular dependency detection:');
try {
CherryPick.disableGlobalCrossScopeCycleDetection();
CherryPick.disableGlobalCycleDetection();
final scope = CherryPick.openRootScope();
// НЕ включаем обнаружение циклических зависимостей
scope.installModules([
UserModule(),
OrderModule(),
]);
// Это приведет к StackOverflowError при попытке использования
final userService = scope.resolve<UserService>();
print('UserService создан: $userService');
// Попытка использовать сервис приведет к бесконечной рекурсии
// userService.createUser('John'); // Раскомментируйте для демонстрации StackOverflow
print('⚠️ UserService created, but using it will cause StackOverflow\n');
} catch (e) {
print('❌ Error: $e\n');
}
// Example 3: Correct architecture without circular dependencies
print('3. Correct architecture without circular dependencies:');
try {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection(); // Включаем для безопасности
scope.installModules([
ImprovedUserModule(),
ImprovedOrderModule(),
]);
final userService = scope.resolve<ImprovedUserService>();
final orderService = scope.resolve<ImprovedOrderService>();
print('✅ Services created successfully');
// Демонстрация работы
userService.createUser('John');
orderService.createOrder('ORD-001', 'John');
final orders = orderService.getOrdersForUser('John');
print('✅ Orders for user John: $orders');
} catch (e) {
print('❌ Error: $e');
}
print('\n=== Recommendations ===');
print('1. Always enable circular dependency detection in development mode.');
print('2. Use repositories and services to separate concerns.');

View File

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

Binary file not shown.

View File

@@ -77,7 +77,8 @@ class CycleDetector {
);
if (_resolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
final cycle = _resolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
_observer.onCycleDetected(cycle);
_observer.onError('Cycle detected for $dependencyKey', null, null);
throw CircularDependencyException(
@@ -99,7 +100,8 @@ class CycleDetector {
);
_resolutionStack.remove(dependencyKey);
// Only remove from history if it's the last one
if (_resolutionHistory.isNotEmpty && _resolutionHistory.last == dependencyKey) {
if (_resolutionHistory.isNotEmpty &&
_resolutionHistory.last == dependencyKey) {
_resolutionHistory.removeLast();
}
}
@@ -124,7 +126,8 @@ class CycleDetector {
}
/// 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).
String _createDependencyKey<T>(String? named) {
@@ -200,12 +203,13 @@ mixin CycleDetectionMixin {
return action();
}
final dependencyKey = named != null
? '${dependencyType.toString()}@$named'
final dependencyKey = named != null
? '${dependencyType.toString()}@$named'
: dependencyType.toString();
if (_cycleDetector!._resolutionStack.contains(dependencyKey)) {
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
final cycleStartIndex =
_cycleDetector!._resolutionHistory.indexOf(dependencyKey);
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
observer.onCycleDetected(cycle);
@@ -223,7 +227,7 @@ mixin CycleDetectionMixin {
return action();
} finally {
_cycleDetector!._resolutionStack.remove(dependencyKey);
if (_cycleDetector!._resolutionHistory.isNotEmpty &&
if (_cycleDetector!._resolutionHistory.isNotEmpty &&
_cycleDetector!._resolutionHistory.last == dependencyKey) {
_cycleDetector!._resolutionHistory.removeLast();
}
@@ -231,6 +235,6 @@ mixin CycleDetectionMixin {
}
/// Gets the current active dependency resolution chain.
List<String> get currentResolutionChain =>
List<String> get currentResolutionChain =>
_cycleDetector?.currentResolutionChain ?? [];
}

View File

@@ -14,7 +14,6 @@
import 'dart:collection';
import 'package:cherrypick/cherrypick.dart';
/// GlobalCycleDetector detects and prevents circular dependencies across an entire DI scope hierarchy.
///
/// This is particularly important for modular/feature-based applications
@@ -45,13 +44,16 @@ class GlobalCycleDetector {
final List<String> _globalResolutionHistory = [];
// 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.
static GlobalCycleDetector get instance {
_instance ??= GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
_instance ??=
GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
return _instance!;
}
@@ -70,9 +72,11 @@ class GlobalCycleDetector {
if (_globalResolutionStack.contains(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.onError('Global circular dependency detected for $dependencyKey', null, null);
_observer.onError(
'Global circular dependency detected for $dependencyKey', null, null);
throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey',
cycle,
@@ -88,7 +92,8 @@ class GlobalCycleDetector {
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
_globalResolutionStack.remove(dependencyKey);
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) {
if (_globalResolutionHistory.isNotEmpty &&
_globalResolutionHistory.last == dependencyKey) {
_globalResolutionHistory.removeLast();
}
}
@@ -101,13 +106,16 @@ class GlobalCycleDetector {
String? scopeId,
T Function() action,
) {
final dependencyKey = _createDependencyKeyFromType(dependencyType, named, scopeId);
final dependencyKey =
_createDependencyKeyFromType(dependencyType, named, scopeId);
if (_globalResolutionStack.contains(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.onError('Global circular dependency detected for $dependencyKey', null, null);
_observer.onError(
'Global circular dependency detected for $dependencyKey', null, null);
throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey',
cycle,
@@ -121,7 +129,8 @@ class GlobalCycleDetector {
return action();
} finally {
_globalResolutionStack.remove(dependencyKey);
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) {
if (_globalResolutionHistory.isNotEmpty &&
_globalResolutionHistory.last == dependencyKey) {
_globalResolutionHistory.removeLast();
}
}
@@ -129,7 +138,8 @@ class GlobalCycleDetector {
/// Get per-scope detector (not usually needed by consumers).
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.
@@ -144,7 +154,8 @@ class GlobalCycleDetector {
}
/// 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.
void clear() {
@@ -157,7 +168,8 @@ class GlobalCycleDetector {
void _detectorClear(detector) => detector.clear();
/// 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 namePrefix = named != null ? '@$named' : '';
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:meta/meta.dart';
Scope? _rootScope;
/// Global logger for all [Scope]s managed by [CherryPick].
@@ -80,7 +79,8 @@ class CherryPick {
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
_rootScope!.enableCycleDetection();
}
if (_globalCrossScopeCycleDetectionEnabled && !_rootScope!.isGlobalCycleDetectionEnabled) {
if (_globalCrossScopeCycleDetectionEnabled &&
!_rootScope!.isGlobalCycleDetectionEnabled) {
_rootScope!.enableGlobalCycleDetection();
}
return _rootScope!;
@@ -96,7 +96,8 @@ class CherryPick {
/// ```
static Future<void> closeRootScope() async {
if (_rootScope != null) {
await _rootScope!.dispose(); // Автоматический вызов dispose для rootScope!
await _rootScope!
.dispose(); // Автоматический вызов dispose для rootScope!
_rootScope = null;
}
}
@@ -141,13 +142,15 @@ class CherryPick {
/// ```dart
/// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature');
/// ```
static void enableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
static void enableCycleDetectionForScope(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
scope.enableCycleDetection();
}
/// 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);
scope.disableCycleDetection();
}
@@ -158,7 +161,8 @@ class CherryPick {
/// ```dart
/// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api');
/// ```
static bool isCycleDetectionEnabledForScope({String scopeName = '', String separator = '.'}) {
static bool isCycleDetectionEnabledForScope(
{String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
return scope.isCycleDetectionEnabled;
}
@@ -171,7 +175,8 @@ class CherryPick {
/// ```dart
/// 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);
return scope.currentResolutionChain;
}
@@ -229,14 +234,13 @@ class CherryPick {
if (nameParts.isEmpty) {
throw Exception('Can not open sub scope because scopeName can not split');
}
final scope = nameParts.fold(
openRootScope(),
(Scope previous, String element) => previous.openSubScope(element)
);
final scope = nameParts.fold(openRootScope(),
(Scope previous, String element) => previous.openSubScope(element));
if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) {
scope.enableCycleDetection();
}
if (_globalCrossScopeCycleDetectionEnabled && !scope.isGlobalCycleDetectionEnabled) {
if (_globalCrossScopeCycleDetectionEnabled &&
!scope.isGlobalCycleDetectionEnabled) {
scope.enableGlobalCycleDetection();
}
return scope;
@@ -252,21 +256,21 @@ class CherryPick {
/// CherryPick.closeScope(scopeName: 'network.super.api');
/// ```
@experimental
static Future<void> closeScope({String scopeName = '', String separator = '.'}) async {
static Future<void> closeScope(
{String scopeName = '', String separator = '.'}) async {
if (scopeName.isEmpty) {
await closeRootScope();
return;
}
final nameParts = scopeName.split(separator);
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) {
final lastPart = nameParts.removeLast();
final scope = nameParts.fold(
openRootScope(),
(Scope previous, String element) => previous.openSubScope(element)
);
final scope = nameParts.fold(openRootScope(),
(Scope previous, String element) => previous.openSubScope(element));
await scope.closeSubScope(lastPart);
} else {
await openRootScope().closeSubScope(nameParts.first);
@@ -316,7 +320,8 @@ class CherryPick {
/// 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).
///
@@ -367,10 +372,11 @@ class CherryPick {
/// ```dart
/// 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);
scope.enableCycleDetection();
scope.enableGlobalCycleDetection();
return scope;
}
}
}

View File

@@ -16,13 +16,13 @@ import 'package:cherrypick/src/binding.dart';
import 'package:cherrypick/src/scope.dart';
/// Represents a DI module—a reusable group of dependency bindings.
///
///
/// Extend [Module] to declaratively group related [Binding] definitions,
/// then install your module(s) into a [Scope] for dependency resolution.
///
///
/// Modules make it easier to organize your DI configuration for features, layers,
/// infrastructure, or integration, and support modular app architecture.
///
///
/// Usage example:
/// ```dart
/// class AppModule extends Module {
@@ -33,12 +33,12 @@ import 'package:cherrypick/src/scope.dart';
/// bind<Config>().toInstance(Config.dev());
/// }
/// }
///
///
/// // Installing the module into the root DI scope:
/// final rootScope = CherryPick.openRootScope();
/// rootScope.installModules([AppModule()]);
/// ```
///
///
/// Combine several modules and submodules to implement scalable architectures.
///
abstract class Module {

View File

@@ -49,7 +49,8 @@ abstract class CherryPickObserver {
/// ```dart
/// 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).
///
@@ -57,7 +58,8 @@ abstract class CherryPickObserver {
/// ```dart
/// 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 ===
/// Called when modules are installed into the container.
@@ -157,19 +159,23 @@ class PrintCherryPickObserver implements CherryPickObserver {
print('[request][CherryPick] $name$type (scope: $scopeName)');
@override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) =>
print('[create][CherryPick] $name$type => $instance (scope: $scopeName)');
void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) =>
print(
'[create][CherryPick] $name$type => $instance (scope: $scopeName)');
@override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) =>
print('[dispose][CherryPick] $name$type => $instance (scope: $scopeName)');
void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) =>
print(
'[dispose][CherryPick] $name$type => $instance (scope: $scopeName)');
@override
void onModulesInstalled(List<String> modules, {String? scopeName}) =>
print('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
void onModulesInstalled(List<String> modules, {String? scopeName}) => print(
'[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
@override
void onModulesRemoved(List<String> modules, {String? scopeName}) =>
print('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
void onModulesRemoved(List<String> modules, {String? scopeName}) => print(
'[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
@override
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');
@override
void onCycleDetected(List<String> chain, {String? scopeName}) =>
print('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
void onCycleDetected(List<String> chain, {String? scopeName}) => print(
'[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
@override
void onCacheHit(String name, Type type, {String? scopeName}) =>
@@ -210,9 +216,11 @@ class SilentCherryPickObserver implements CherryPickObserver {
@override
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
@override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) {}
@override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) {}
@override
void onModulesInstalled(List<String> modules, {String? scopeName}) {}
@override

View File

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

View File

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

View File

@@ -12,6 +12,7 @@ class DummyModule extends Module {
}
class A {}
class B {}
class CyclicModule extends Module {
@@ -52,10 +53,13 @@ void main() {
throwsA(isA<CircularDependencyException>()),
);
// Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles
final foundInErrors = observer.errors.any((m) => m.contains('cycle detected'));
final foundInDiagnostics = observer.diagnostics.any((m) => m.contains('cycle detected'));
final foundInErrors =
observer.errors.any((m) => m.contains('cycle detected'));
final foundInDiagnostics =
observer.diagnostics.any((m) => m.contains('cycle detected'));
final foundCycleNotified = observer.cycles.isNotEmpty;
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,9 +15,8 @@ class MockObserver implements CherryPickObserver {
void onWarning(String message, {Object? details}) => warnings.add(message);
@override
void onError(String message, Object? error, StackTrace? stackTrace) =>
errors.add(
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
void onError(String message, Object? error, StackTrace? stackTrace) => errors.add(
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
@override
void onCycleDetected(List<String> chain, {String? scopeName}) =>
@@ -30,9 +29,11 @@ class MockObserver implements CherryPickObserver {
@override
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
@override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) {}
@override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) {}
@override
void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {}
@override

View File

@@ -30,7 +30,7 @@ void main() {
final rootScope = CherryPick.openSafeRootScope();
final level1Scope = rootScope.openSubScope('level1');
final level2Scope = level1Scope.openSubScope('level2');
level1Scope.enableCycleDetection();
level2Scope.enableCycleDetection();
@@ -46,14 +46,16 @@ 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();
parentScope.enableCycleDetection();
final childScope = parentScope.openSubScope('child');
// НЕ включаем cycle detection для дочернего скоупа
parentScope.installModules([ParentScopeModule()]);
childScope.installModules([ChildScopeModule()]);

View File

@@ -18,7 +18,7 @@ void main() {
test('should detect simple circular dependency', () {
detector.startResolving<String>();
expect(
() => detector.startResolving<String>(),
throwsA(isA<CircularDependencyException>()),
@@ -27,7 +27,7 @@ void main() {
test('should detect circular dependency with named bindings', () {
detector.startResolving<String>(named: 'test');
expect(
() => detector.startResolving<String>(named: 'test'),
throwsA(isA<CircularDependencyException>()),
@@ -37,7 +37,7 @@ void main() {
test('should allow different types to be resolved simultaneously', () {
detector.startResolving<String>();
detector.startResolving<int>();
expect(() => detector.finishResolving<int>(), returnsNormally);
expect(() => detector.finishResolving<String>(), returnsNormally);
});
@@ -46,32 +46,31 @@ void main() {
detector.startResolving<String>();
detector.startResolving<int>();
detector.startResolving<bool>();
expect(
() => detector.startResolving<String>(),
throwsA(predicate((e) =>
e is CircularDependencyException &&
e.dependencyChain.contains('String') &&
e.dependencyChain.length > 1
)),
throwsA(predicate((e) =>
e is CircularDependencyException &&
e.dependencyChain.contains('String') &&
e.dependencyChain.length > 1)),
);
});
test('should clear state properly', () {
detector.startResolving<String>();
detector.clear();
expect(() => detector.startResolving<String>(), returnsNormally);
});
test('should track resolution history correctly', () {
detector.startResolving<String>();
detector.startResolving<int>();
expect(detector.currentResolutionChain, contains('String'));
expect(detector.currentResolutionChain, contains('int'));
expect(detector.currentResolutionChain.length, equals(2));
detector.finishResolving<int>();
expect(detector.currentResolutionChain.length, equals(1));
expect(detector.currentResolutionChain, contains('String'));
@@ -82,7 +81,7 @@ void main() {
test('should detect circular dependency in real scenario', () {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
// Создаем циклическую зависимость: A зависит от B, B зависит от A
scope.installModules([
CircularModuleA(),
@@ -98,7 +97,7 @@ void main() {
test('should work normally without cycle detection enabled', () {
final scope = CherryPick.openRootScope();
// Не включаем обнаружение циклических зависимостей
scope.installModules([
SimpleModule(),
]);
@@ -111,7 +110,7 @@ void main() {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
expect(scope.isCycleDetectionEnabled, isTrue);
scope.disableCycleDetection();
expect(scope.isCycleDetectionEnabled, isFalse);
});
@@ -119,7 +118,7 @@ void main() {
test('should handle named dependencies in cycle detection', () {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
scope.installModules([
NamedCircularModule(),
]);
@@ -133,7 +132,7 @@ void main() {
test('should detect cycles in async resolution', () async {
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
scope.installModules([
AsyncCircularModule(),
]);
@@ -161,14 +160,16 @@ class ServiceB {
class CircularModuleA extends Module {
@override
void builder(Scope currentScope) {
bind<ServiceA>().toProvide(() => ServiceA(currentScope.resolve<ServiceB>()));
bind<ServiceA>()
.toProvide(() => ServiceA(currentScope.resolve<ServiceB>()));
}
}
class CircularModuleB extends Module {
@override
void builder(Scope currentScope) {
bind<ServiceB>().toProvide(() => ServiceB(currentScope.resolve<ServiceA>()));
bind<ServiceB>()
.toProvide(() => ServiceB(currentScope.resolve<ServiceA>()));
}
}
@@ -210,7 +211,7 @@ class AsyncCircularModule extends Module {
final serviceB = await currentScope.resolveAsync<AsyncServiceB>();
return AsyncServiceA(serviceB);
});
// ignore: deprecated_member_use_from_same_package
bind<AsyncServiceB>().toProvideAsync(() async {
final serviceA = await currentScope.resolveAsync<AsyncServiceA>();

View File

@@ -22,50 +22,57 @@ void main() {
group('Global Cross-Scope Cycle Detection', () {
test('should enable global cross-scope cycle detection', () {
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isFalse);
CherryPick.enableGlobalCrossScopeCycleDetection();
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isTrue);
});
test('should disable global cross-scope cycle detection', () {
CherryPick.enableGlobalCrossScopeCycleDetection();
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isTrue);
CherryPick.disableGlobalCrossScopeCycleDetection();
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();
final scope = CherryPick.openRootScope();
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();
expect(scope.isGlobalCycleDetectionEnabled, isFalse);
CherryPick.enableGlobalCrossScopeCycleDetection();
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
});
});
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();
expect(scope.isCycleDetectionEnabled, isTrue);
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
});
test('should create global safe sub-scope with both detections enabled', () {
final scope = CherryPick.openGlobalSafeScope(scopeName: 'feature.global');
test('should create global safe sub-scope with both detections enabled',
() {
final scope =
CherryPick.openGlobalSafeScope(scopeName: 'feature.global');
expect(scope.isCycleDetectionEnabled, isTrue);
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
});
@@ -104,7 +111,7 @@ void main() {
test('should provide detailed global resolution chain in exception', () {
final scope = CherryPick.openGlobalSafeRootScope();
scope.installModules([GlobalParentModule()]);
final childScope = scope.openSubScope('child');
childScope.installModules([GlobalChildModule()]);
@@ -114,11 +121,11 @@ void main() {
} catch (e) {
expect(e, isA<CircularDependencyException>());
final circularError = e as CircularDependencyException;
// Проверяем, что цепочка содержит информацию о скоупах
expect(circularError.dependencyChain, isNotEmpty);
expect(circularError.dependencyChain.length, greaterThan(1));
// Цепочка должна содержать оба сервиса
final chainString = circularError.dependencyChain.join(' -> ');
expect(chainString, contains('GlobalServiceA'));
@@ -144,11 +151,11 @@ void main() {
CherryPick.enableGlobalCrossScopeCycleDetection();
// ignore: unused_local_variable
final scope = CherryPick.openGlobalSafeRootScope();
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
CherryPick.clearGlobalCycleDetector();
// После очистки детектор должен быть сброшен
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
});
@@ -157,10 +164,10 @@ void main() {
group('Inheritance of Global Settings', () {
test('should inherit global cycle detection in child scopes', () {
CherryPick.enableGlobalCrossScopeCycleDetection();
final parentScope = CherryPick.openRootScope();
final childScope = parentScope.openSubScope('child');
expect(parentScope.isGlobalCycleDetectionEnabled, isTrue);
expect(childScope.isGlobalCycleDetectionEnabled, isTrue);
});
@@ -168,9 +175,9 @@ void main() {
test('should inherit both local and global cycle detection', () {
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final scope = CherryPick.openScope(scopeName: 'feature.test');
expect(scope.isCycleDetectionEnabled, isTrue);
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
});

View File

@@ -24,53 +24,59 @@ void main() {
group('Global Cycle Detection', () {
test('should enable global cycle detection', () {
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
CherryPick.enableGlobalCycleDetection();
expect(CherryPick.isGlobalCycleDetectionEnabled, isTrue);
});
test('should disable global cycle detection', () {
CherryPick.enableGlobalCycleDetection();
expect(CherryPick.isGlobalCycleDetectionEnabled, isTrue);
CherryPick.disableGlobalCycleDetection();
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();
final scope = CherryPick.openRootScope();
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();
expect(scope.isCycleDetectionEnabled, isFalse);
CherryPick.enableGlobalCycleDetection();
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();
final scope = CherryPick.openRootScope();
expect(scope.isCycleDetectionEnabled, isTrue);
CherryPick.disableGlobalCycleDetection();
expect(scope.isCycleDetectionEnabled, isFalse);
});
test('should apply global setting to sub-scopes', () {
CherryPick.enableGlobalCycleDetection();
final scope = CherryPick.openScope(scopeName: 'test.subscope');
expect(scope.isCycleDetectionEnabled, isTrue);
});
});
@@ -79,9 +85,9 @@ void main() {
test('should enable cycle detection for root scope', () {
final scope = CherryPick.openRootScope();
expect(scope.isCycleDetectionEnabled, isFalse);
CherryPick.enableCycleDetectionForScope();
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
expect(scope.isCycleDetectionEnabled, isTrue);
});
@@ -89,91 +95,103 @@ void main() {
test('should disable cycle detection for root scope', () {
CherryPick.enableCycleDetectionForScope();
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
CherryPick.disableCycleDetectionForScope();
expect(CherryPick.isCycleDetectionEnabledForScope(), isFalse);
});
test('should enable cycle detection for specific scope', () {
final scopeName = 'feature.auth';
CherryPick.openScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isFalse);
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isTrue);
});
test('should disable cycle detection for specific scope', () {
final scopeName = 'feature.auth';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isTrue);
CherryPick.disableCycleDetectionForScope(scopeName: scopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName),
isFalse);
});
});
group('Safe Scope Creation', () {
test('should create safe root scope with cycle detection enabled', () {
final scope = CherryPick.openSafeRootScope();
expect(scope.isCycleDetectionEnabled, isTrue);
});
test('should create safe sub-scope with cycle detection enabled', () {
final scope = CherryPick.openSafeScope(scopeName: 'feature.safe');
expect(scope.isCycleDetectionEnabled, isTrue);
});
test('safe scope should work independently of global setting', () {
// Глобальная настройка отключена
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
final scope = CherryPick.openSafeScope(scopeName: 'feature.independent');
final scope =
CherryPick.openSafeScope(scopeName: 'feature.independent');
expect(scope.isCycleDetectionEnabled, isTrue);
});
});
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();
final chain = CherryPick.getCurrentResolutionChain();
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();
final chain = CherryPick.getCurrentResolutionChain();
expect(chain, isEmpty);
});
test('should track resolution chain for specific scope', () {
final scopeName = 'feature.tracking';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
final chain = CherryPick.getCurrentResolutionChain(scopeName: scopeName);
final chain =
CherryPick.getCurrentResolutionChain(scopeName: scopeName);
expect(chain, isEmpty); // Пустая, так как нет активного разрешения
});
});
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();
final scope = CherryPick.openRootScope();
scope.installModules([CircularTestModule()]);
expect(
() => scope.resolve<CircularServiceA>(),
throwsA(isA<CircularDependencyException>()),
@@ -183,44 +201,54 @@ void main() {
test('should detect circular dependency with safe scope', () {
final scope = CherryPick.openSafeRootScope();
scope.installModules([CircularTestModule()]);
expect(
() => scope.resolve<CircularServiceA>(),
throwsA(isA<CircularDependencyException>()),
);
});
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();
scope.installModules([CircularTestModule()]);
// Без обнаружения циклических зависимостей не будет выброшено CircularDependencyException,
// но может произойти StackOverflowError при попытке создания объекта
expect(() => scope.resolve<CircularServiceA>(),
throwsA(isA<StackOverflowError>()));
expect(() => scope.resolve<CircularServiceA>(),
throwsA(isA<StackOverflowError>()));
});
});
group('Scope Name Handling', () {
test('should handle empty scope name as root scope', () {
CherryPick.enableCycleDetectionForScope(scopeName: '');
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: ''), isTrue);
expect(
CherryPick.isCycleDetectionEnabledForScope(scopeName: ''), isTrue);
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
});
test('should handle complex scope names', () {
final complexScopeName = 'app.feature.auth.login';
CherryPick.enableCycleDetectionForScope(scopeName: complexScopeName);
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: complexScopeName), isTrue);
expect(
CherryPick.isCycleDetectionEnabledForScope(
scopeName: complexScopeName),
isTrue);
});
test('should handle custom separator', () {
final scopeName = 'app/feature/auth';
CherryPick.enableCycleDetectionForScope(scopeName: scopeName, separator: '/');
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName, separator: '/'), isTrue);
CherryPick.enableCycleDetectionForScope(
scopeName: scopeName, separator: '/');
expect(
CherryPick.isCycleDetectionEnabledForScope(
scopeName: scopeName, separator: '/'),
isTrue);
});
});
});
@@ -240,7 +268,9 @@ class CircularServiceB {
class CircularTestModule extends Module {
@override
void builder(Scope currentScope) {
bind<CircularServiceA>().toProvide(() => CircularServiceA(currentScope.resolve<CircularServiceB>()));
bind<CircularServiceB>().toProvide(() => CircularServiceB(currentScope.resolve<CircularServiceA>()));
bind<CircularServiceA>().toProvide(
() => 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 'package:test/test.dart';
import '../mock_logger.dart';
@@ -18,7 +19,9 @@ class AsyncExampleDisposable implements Disposable {
class AsyncExampleModule extends Module {
@override
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 {
@override
void builder(Scope scope) {
bind<CountingDisposable>().toProvide(() => CountingDisposable()).singleton();
bind<CountingDisposable>()
.toProvide(() => CountingDisposable())
.singleton();
}
}
@@ -97,10 +102,9 @@ class AsyncModule extends Module {
bind<AsyncCreatedDisposable>()
// ignore: deprecated_member_use_from_same_package
.toProvideAsync(() async {
await Future.delayed(Duration(milliseconds: 10));
return AsyncCreatedDisposable();
})
.singleton();
await Future.delayed(Duration(milliseconds: 10));
return AsyncCreatedDisposable();
}).singleton();
}
}
@@ -119,7 +123,8 @@ void main() {
final scope = Scope(null, observer: observer);
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 scope = Scope(null, observer: observer);
final subScope = scope.openSubScope("child");
@@ -181,7 +186,8 @@ void main() {
});
test("After dropModules resolves fail", () {
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);
scope.dropModules();
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
@@ -294,7 +300,8 @@ void main() {
await scope.dispose();
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());
scope.installModules([ModuleWithDisposable()]);
final t1 = scope.resolve<TestDisposable>();
@@ -305,7 +312,8 @@ void main() {
expect(t1.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();
scope.installModules([ModuleWithDisposable()]);
final t = scope.resolve<TestDisposable>();
@@ -313,7 +321,8 @@ void main() {
await scope.dispose();
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();
scope.installModules([ModuleWithDisposable()]);
final s = scope.resolve<String>();
@@ -327,7 +336,8 @@ void main() {
group('Scope/subScope dispose edge cases', () {
test('Dispose called in closed subScope only', () async {
final root = CherryPick.openRootScope();
final sub = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
final sub = root.openSubScope('feature')
..installModules([ModuleCountingDisposable()]);
final d = sub.resolve<CountingDisposable>();
expect(d.disposeCount, 0);
@@ -339,7 +349,8 @@ void main() {
expect(d.disposeCount, 1);
// Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова)
final sub2 = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
final sub2 = root.openSubScope('feature')
..installModules([ModuleCountingDisposable()]);
final d2 = sub2.resolve<CountingDisposable>();
expect(identical(d, d2), isFalse);
await root.closeSubScope('feature');
@@ -347,8 +358,14 @@ void main() {
});
test('Dispose for all nested subScopes on root disposeAsync', () async {
final root = CherryPick.openRootScope();
root.openSubScope('a').openSubScope('b').installModules([ModuleCountingDisposable()]);
final d = root.openSubScope('a').openSubScope('b').resolve<CountingDisposable>();
root
.openSubScope('a')
.openSubScope('b')
.installModules([ModuleCountingDisposable()]);
final d = root
.openSubScope('a')
.openSubScope('b')
.resolve<CountingDisposable>();
await root.dispose();
expect(d.disposeCount, 1);
});
@@ -357,11 +374,12 @@ void main() {
// --------------------------------------------------------------------------
group('Async disposable (Future test)', () {
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>();
expect(d.disposed, false);
await scope.dispose();
expect(d.disposed, true);
});
});
}
}

View File

@@ -1,3 +1,23 @@
## 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
- **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
[![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)
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,6 +11,24 @@ library;
// 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/provide.dart';
export 'src/instance.dart';

View File

@@ -38,5 +38,6 @@ import 'package:meta/meta.dart';
/// ```
@experimental
final class inject {
/// Creates an [inject] annotation for field injection.
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.
@experimental
final class injectable {
/// Creates an [injectable] annotation for classes.
const injectable();
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,3 +1,31 @@
## 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
- **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` 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

@@ -21,7 +21,7 @@ import 'package:flutter/widgets.dart';
/// Place `CherryPickProvider` at the top of your widget subtree to make a
/// [Scope] (or its descendants) available via `CherryPickProvider.of(context)`.
///
/// This is the recommended entry point for connecting CherryPick DI to your
/// This is the recommended entry point for connecting CherryPick DI to your
/// Flutter app or feature area, enabling context-based scope management and
/// DI resolution in child widgets.
///
@@ -36,7 +36,7 @@ import 'package:flutter/widgets.dart';
/// ),
/// );
/// }
///
///
/// // In any widget:
/// final provider = CherryPickProvider.of(context);
/// final scope = provider.openRootScope();

View File

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

View File

@@ -1,3 +1,23 @@
## 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
> 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** 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

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

View File

@@ -248,7 +248,6 @@ class _ParsedInjectField {
/// Name qualifier for named resolution, or null if not set.
final String? namedValue;
_ParsedInjectField({
required this.fieldName,
required this.coreType,

View File

@@ -23,6 +23,7 @@ import 'annotation_validator.dart';
enum BindingType {
/// Direct instance returned from the method (@instance).
instance,
/// Provider/factory function (@provide).
provide;
}

View File

@@ -2,8 +2,9 @@ name: cherrypick_generator
description: |
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
documentation: https://github.com/pese-git/cherrypick/wiki
version: 3.0.1
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
@@ -14,20 +15,20 @@ topics:
- inversion-of-control
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: ">=3.6.0 <4.0.0"
# Add regular dependencies here.
dependencies:
cherrypick_annotations: ^1.1.2-dev.0
analyzer: ^7.0.0
cherrypick_annotations: ^3.0.1
analyzer: ^7.7.1
dart_style: ^3.0.0
build: ^2.4.1
source_gen: ^2.0.0
collection: ^1.18.0
dev_dependencies:
lints: ^4.0.0
mockito: ^5.4.4
lints: ^5.1.1
mockito: ^5.4.5
test: ^1.25.8
build_test: ^2.1.7
build_runner: ^2.4.13

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

View File

@@ -44,6 +44,46 @@ final setupFuture = loadEnvironment();
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
- **toProvideAsync** — async factory (if you need to await a Future)
- **toProvideWithParams / toProvideAsyncWithParams** — factories with runtime parameters
@@ -67,6 +107,14 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — single instance per Scope lifetime
- 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
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');
```
> ⚠️ **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

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** — обычная синхронная фабрика.
- **toProvideAsync** — асинхронная фабрика (например, если нужно дожидаться Future).
- **toProvideWithParams / toProvideAsyncWithParams** — фабрики с параметрами.
@@ -68,6 +110,15 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — один инстанс на всё время жизни Scope.
- По умолчанию каждый resolve создаёт новый объект.
> **Примечание о `.singleton()` и `.toInstance()`:**
>
> Вызов `.singleton()` после `.toInstance()` не изменяет поведения биндинга: объект, переданный через `toInstance()`, и так всегда будет "единственным" (single instance), возвращаемым при каждом resolve.
>
> Применять `.singleton()` к уже существующему объекту нет необходимости — этот вызов ничего не меняет.
>
> `.singleton()` нужен только для провайдеров (например, `toProvide`/`toProvideAsync`), чтобы зафиксировать единственный экземпляр, создаваемый фабрикой.
### Параметрические биндинги
Позволяют создавать зависимости с runtime-параметрами — например, сервис для пользователя с ID:
@@ -79,6 +130,26 @@ bind<UserService>().toProvideWithParams((userId) => UserService(userId));
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'ами: иерархия зависимостей

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

@@ -5,18 +5,18 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
url: "https://pub.dev"
source: hosted
version: "82.0.0"
version: "85.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0"
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
url: "https://pub.dev"
source: hosted
version: "7.4.5"
version: "7.7.1"
args:
dependency: transitive
description:
@@ -29,18 +29,18 @@ packages:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev"
source: hosted
version: "2.12.0"
version: "2.11.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
version: "2.1.1"
build:
dependency: transitive
description:
@@ -53,18 +53,18 @@ packages:
dependency: transitive
description:
name: build_config
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.2"
build_daemon:
dependency: transitive
description:
name: build_daemon
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9"
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.0.4"
build_resolvers:
dependency: transitive
description:
@@ -101,18 +101,18 @@ packages:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
url: "https://pub.dev"
source: hosted
version: "8.9.5"
version: "8.12.0"
characters:
dependency: transitive
description:
name: characters
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.3.0"
checked_yaml:
dependency: transitive
description:
@@ -127,36 +127,36 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.8"
version: "3.0.0"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.1"
version: "3.0.0"
cherrypick_flutter:
dependency: "direct main"
description:
path: "../../cherrypick_flutter"
relative: true
source: path
version: "1.1.3-dev.8"
version: "3.0.0"
cherrypick_generator:
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "1.1.1"
version: "3.0.0"
clock:
dependency: transitive
description:
name: clock
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev"
source: hosted
version: "1.1.2"
version: "1.1.1"
code_builder:
dependency: transitive
description:
@@ -169,10 +169,10 @@ packages:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf
url: "https://pub.dev"
source: hosted
version: "1.19.1"
version: "1.19.0"
convert:
dependency: transitive
description:
@@ -209,10 +209,10 @@ packages:
dependency: transitive
description:
name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.1"
file:
dependency: transitive
description:
@@ -275,10 +275,10 @@ packages:
dependency: transitive
description:
name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
http_multi_server:
dependency: transitive
description:
@@ -291,10 +291,10 @@ packages:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.1.2"
io:
dependency: transitive
description:
@@ -323,18 +323,18 @@ packages:
dependency: transitive
description:
name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06"
url: "https://pub.dev"
source: hosted
version: "10.0.8"
version: "10.0.7"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379"
url: "https://pub.dev"
source: hosted
version: "3.0.9"
version: "3.0.8"
leak_tracker_testing:
dependency: transitive
description:
@@ -347,10 +347,10 @@ packages:
dependency: transitive
description:
name: lints
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "5.0.0"
version: "5.1.1"
logging:
dependency: transitive
description:
@@ -363,10 +363,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "0.12.16+1"
material_color_utilities:
dependency: transitive
description:
@@ -379,10 +379,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.dev"
source: hosted
version: "1.16.0"
version: "1.15.0"
mime:
dependency: transitive
description:
@@ -403,10 +403,10 @@ packages:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
version: "1.9.0"
pool:
dependency: transitive
description:
@@ -427,26 +427,26 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.4.2"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "3.0.0"
sky_engine:
dependency: transitive
description: flutter
@@ -464,26 +464,26 @@ packages:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev"
source: hosted
version: "1.10.1"
version: "1.10.0"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377"
url: "https://pub.dev"
source: hosted
version: "1.12.1"
version: "1.12.0"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.1.2"
stream_transform:
dependency: transitive
description:
@@ -496,26 +496,26 @@ packages:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.3.0"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
url: "https://pub.dev"
source: hosted
version: "1.2.2"
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c"
url: "https://pub.dev"
source: hosted
version: "0.7.4"
version: "0.7.3"
timing:
dependency: transitive
description:
@@ -544,18 +544,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b
url: "https://pub.dev"
source: hosted
version: "14.3.1"
version: "14.3.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.3"
web:
dependency: transitive
description:
@@ -589,5 +589,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.7.0-0 <4.0.0"
dart: ">=3.6.0 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"

View File

@@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:talker_flutter/talker_flutter.dart';
import 'domain/repository/post_repository.dart';
import 'presentation/bloc/post_bloc.dart';
import 'router/app_router.dart';
@@ -14,9 +13,11 @@ part 'app.inject.cherrypick.g.dart';
class TalkerProvider extends InheritedWidget {
final Talker talker;
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
bool updateShouldNotify(TalkerProvider oldWidget) => oldWidget.talker != talker;
bool updateShouldNotify(TalkerProvider oldWidget) =>
oldWidget.talker != talker;
}
@injectable()

View File

@@ -15,14 +15,16 @@ abstract class AppModule extends Module {
@provide()
@singleton()
TalkerDioLoggerSettings talkerDioLoggerSettings() => TalkerDioLoggerSettings(
printRequestHeaders: true,
printResponseHeaders: true,
printResponseMessage: true,
);
printRequestHeaders: true,
printResponseHeaders: true,
printResponseMessage: true,
);
@provide()
@singleton()
TalkerDioLogger talkerDioLogger(Talker talker, TalkerDioLoggerSettings settings) => TalkerDioLogger(talker: talker, settings: settings);
TalkerDioLogger talkerDioLogger(
Talker talker, TalkerDioLoggerSettings settings) =>
TalkerDioLogger(talker: talker, settings: settings);
@instance()
int timeout() => 1000;

View File

@@ -5,9 +5,9 @@ class CoreModule extends Module {
final Talker _talker;
CoreModule({required Talker talker}) : _talker = talker;
@override
void builder(Scope currentScope) {
bind<Talker>().toProvide(() => _talker).singleton();
}
}
}

View File

@@ -13,7 +13,6 @@ void main() {
final talker = Talker();
final talkerLogger = TalkerCherryPickObserver(talker);
Bloc.observer = TalkerBlocObserver(talker: talker);
CherryPick.setGlobalObserver(talkerLogger);
@@ -24,7 +23,10 @@ void main() {
}
// Используем safe root scope для гарантии защиты
CherryPick.openRootScope().installModules([CoreModule(talker: talker), $AppModule()]);
CherryPick.openRootScope()
.installModules([CoreModule(talker: talker), $AppModule()]);
runApp(MyApp(talker: talker,));
runApp(MyApp(
talker: talker,
));
}

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
url: "https://pub.dev"
source: hosted
version: "82.0.0"
version: "85.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0"
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
url: "https://pub.dev"
source: hosted
version: "7.4.5"
version: "7.7.1"
ansi_styles:
dependency: transitive
description:
@@ -45,26 +45,26 @@ packages:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev"
source: hosted
version: "2.12.0"
version: "2.11.0"
auto_route:
dependency: "direct main"
description:
name: auto_route
sha256: "1d1bd908a1fec327719326d5d0791edd37f16caff6493c01003689fb03315ad7"
sha256: b8c036fa613a98a759cf0fdcba26e62f4985dcbff01a5e760ab411e8554bbaf0
url: "https://pub.dev"
source: hosted
version: "9.3.0+1"
version: "10.1.0+1"
auto_route_generator:
dependency: "direct main"
dependency: "direct dev"
description:
name: auto_route_generator
sha256: c2e359d8932986d4d1bcad7a428143f81384ce10fef8d4aa5bc29e1f83766a46
sha256: "8e622d26dc6be4bf496d47969e3e9ba555c3abcf2290da6abfa43cbd4f57fa52"
url: "https://pub.dev"
source: hosted
version: "9.3.1"
version: "10.0.1"
bloc:
dependency: transitive
description:
@@ -77,10 +77,10 @@ packages:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
version: "2.1.1"
build:
dependency: transitive
description:
@@ -93,18 +93,18 @@ packages:
dependency: transitive
description:
name: build_config
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.2"
build_daemon:
dependency: transitive
description:
name: build_daemon
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9"
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.0.4"
build_resolvers:
dependency: transitive
description:
@@ -114,7 +114,7 @@ packages:
source: hosted
version: "2.4.4"
build_runner:
dependency: "direct main"
dependency: "direct dev"
description:
name: build_runner
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
@@ -141,18 +141,18 @@ packages:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
url: "https://pub.dev"
source: hosted
version: "8.9.5"
version: "8.12.0"
characters:
dependency: transitive
description:
name: characters
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.3.0"
charcode:
dependency: transitive
description:
@@ -175,21 +175,21 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.8"
version: "3.0.0"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.1"
version: "3.0.0"
cherrypick_generator:
dependency: "direct main"
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "1.1.1"
version: "3.0.0"
cli_launcher:
dependency: transitive
description:
@@ -210,10 +210,10 @@ packages:
dependency: transitive
description:
name: clock
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev"
source: hosted
version: "1.1.2"
version: "1.1.1"
code_builder:
dependency: transitive
description:
@@ -226,10 +226,10 @@ packages:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf
url: "https://pub.dev"
source: hosted
version: "1.19.1"
version: "1.19.0"
conventional_commit:
dependency: transitive
description:
@@ -274,10 +274,10 @@ packages:
dependency: transitive
description:
name: dart_style
sha256: "5b236382b47ee411741447c1f1e111459c941ea1b3f2b540dde54c210a3662af"
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
version: "3.0.1"
dartz:
dependency: "direct main"
description:
@@ -290,10 +290,10 @@ packages:
dependency: "direct main"
description:
name: dio
sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9"
sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9
url: "https://pub.dev"
source: hosted
version: "5.8.0+1"
version: "5.9.0"
dio_web_adapter:
dependency: transitive
description:
@@ -306,18 +306,18 @@ packages:
dependency: transitive
description:
name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.1"
ffi:
dependency: transitive
description:
name: ffi
sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.1.3"
file:
dependency: transitive
description:
@@ -348,7 +348,7 @@ packages:
source: hosted
version: "9.1.1"
flutter_lints:
dependency: "direct main"
dependency: "direct dev"
description:
name: flutter_lints
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
@@ -356,7 +356,7 @@ packages:
source: hosted
version: "5.0.0"
flutter_test:
dependency: "direct main"
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
@@ -366,7 +366,7 @@ packages:
source: sdk
version: "0.0.0"
freezed:
dependency: "direct main"
dependency: "direct dev"
description:
name: freezed
sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c"
@@ -417,10 +417,10 @@ packages:
dependency: transitive
description:
name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
http_multi_server:
dependency: transitive
description:
@@ -433,10 +433,10 @@ packages:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.1.2"
intl:
dependency: transitive
description:
@@ -470,7 +470,7 @@ packages:
source: hosted
version: "4.9.0"
json_serializable:
dependency: "direct main"
dependency: "direct dev"
description:
name: json_serializable
sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c
@@ -481,18 +481,18 @@ packages:
dependency: transitive
description:
name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06"
url: "https://pub.dev"
source: hosted
version: "10.0.8"
version: "10.0.7"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379"
url: "https://pub.dev"
source: hosted
version: "3.0.9"
version: "3.0.8"
leak_tracker_testing:
dependency: transitive
description:
@@ -505,10 +505,10 @@ packages:
dependency: transitive
description:
name: lints
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "5.0.0"
version: "5.1.1"
logging:
dependency: transitive
description:
@@ -521,10 +521,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "0.12.16+1"
material_color_utilities:
dependency: transitive
description:
@@ -545,10 +545,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.dev"
source: hosted
version: "1.16.0"
version: "1.15.0"
mime:
dependency: transitive
description:
@@ -585,10 +585,10 @@ packages:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
version: "1.9.0"
path_provider:
dependency: transitive
description:
@@ -697,10 +697,10 @@ packages:
dependency: transitive
description:
name: provider
sha256: "4abbd070a04e9ddc287673bf5a030c7ca8b685ff70218720abab8b092f53dd84"
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
url: "https://pub.dev"
source: hosted
version: "6.1.5"
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
@@ -721,58 +721,58 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
retrofit:
dependency: "direct main"
description:
name: retrofit
sha256: c6cc9ad3374e6d07008343140a67afffaaa34cdf6bf08d4847d91417a99dcf45
sha256: "84d70114a5b6bae5f4c1302335f9cb610ebeb1b02023d5e7e87697aaff52926a"
url: "https://pub.dev"
source: hosted
version: "4.4.2"
version: "4.6.0"
retrofit_generator:
dependency: "direct main"
dependency: "direct dev"
description:
name: retrofit_generator
sha256: "65d28d3a7b4db485f1c73fee8ee32f552ef23ee4ecb68ba491f39d80b73bdcbf"
sha256: e48c5a7ac362621b74976c64c540500dc7a54b8b5b074616a96a4854a2e5bb5b
url: "https://pub.dev"
source: hosted
version: "9.2.0"
version: "9.6.0"
share_plus:
dependency: transitive
description:
name: share_plus
sha256: b2961506569e28948d75ec346c28775bb111986bb69dc6a20754a457e3d97fa0
sha256: d7dc0630a923883c6328ca31b89aa682bacbf2f8304162d29f7c6aaff03a27a1
url: "https://pub.dev"
source: hosted
version: "11.0.0"
version: "11.1.0"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: "1032d392bc5d2095a77447a805aa3f804d2ae6a4d5eef5e6ebb3bd94c1bc19ef"
sha256: "88023e53a13429bd65d8e85e11a9b484f49d4c190abbd96c7932b74d6927cc9a"
url: "https://pub.dev"
source: hosted
version: "6.0.0"
version: "6.1.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.4.2"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "3.0.0"
sky_engine:
dependency: transitive
description: flutter
@@ -790,18 +790,18 @@ packages:
dependency: transitive
description:
name: source_helper
sha256: "86d247119aedce8e63f4751bd9626fc9613255935558447569ad42f9f5b48b3c"
sha256: a447acb083d3a5ef17f983dd36201aeea33fedadb3228fa831f2f0c92f0f3aca
url: "https://pub.dev"
source: hosted
version: "1.3.5"
version: "1.3.7"
source_span:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev"
source: hosted
version: "1.10.1"
version: "1.10.0"
sprintf:
dependency: transitive
description:
@@ -814,18 +814,18 @@ packages:
dependency: transitive
description:
name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377"
url: "https://pub.dev"
source: hosted
version: "1.12.1"
version: "1.12.0"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.1.2"
stream_transform:
dependency: transitive
description:
@@ -838,73 +838,73 @@ packages:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.3.0"
talker:
dependency: transitive
description:
name: talker
sha256: "028a753874d98df39f210cb74f0ee09a0a95e28f8bc2dc975c3c328e24fde23d"
sha256: "2d742b54e5cda58b7d386cd2d95088c3429ef273b2a0869dec552fe02601367a"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_bloc_logger:
dependency: "direct main"
description:
name: talker_bloc_logger
sha256: cf1e3b1d70f9a47e061288f0d230ba0e04a0f6394629d5df1c7b0933b236e397
sha256: "7752ca8a0b2eba487c8c189ca2390ebfcdaa4f7b10eda27587e5067e4427e7cd"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_cherrypick_logger:
dependency: "direct main"
description:
path: "../../talker_cherrypick_logger"
relative: true
source: path
version: "1.0.0"
version: "3.0.0"
talker_dio_logger:
dependency: "direct main"
description:
name: talker_dio_logger
sha256: dcf784f1841e248c270ef741f8a07ca9cf562c6424ee43fc6e598c4eb7f18238
sha256: "20cc3bc9820fa73040f23e27d5d86462e590ddf02c43d0a801c56bf5ecc68922"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_flutter:
dependency: "direct main"
description:
name: talker_flutter
sha256: "2cfee6661277d415a895b6258ecb0bf80d7b564e91ea7e769fc6d0f970a01c09"
sha256: d249fa16936a08fe5c4fb9e2b9b122fdcbaef6be9c4dcf61e448d0b76f3179f1
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_logger:
dependency: transitive
description:
name: talker_logger
sha256: "778ec673f1b71a6516e5576ae8d90ea23bbbcf9f405a97cc30e8ccdc33e26d27"
sha256: "4f06d46db664c11cf4d629378da661f2c75aee629e3ef898dbc3cf44a0c41cd7"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
url: "https://pub.dev"
source: hosted
version: "1.2.2"
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c"
url: "https://pub.dev"
source: hosted
version: "0.7.4"
version: "0.7.3"
timing:
dependency: transitive
description:
@@ -973,18 +973,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b
url: "https://pub.dev"
source: hosted
version: "14.3.1"
version: "14.3.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.3"
web:
dependency: transitive
description:
@@ -1013,10 +1013,10 @@ packages:
dependency: transitive
description:
name: win32
sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba"
sha256: daf97c9d80197ed7b619040e86c8ab9a9dad285e7671ee7390f9180cc828a51e
url: "https://pub.dev"
source: hosted
version: "5.13.0"
version: "5.10.1"
xdg_directories:
dependency: transitive
description:
@@ -1050,5 +1050,5 @@ packages:
source: hosted
version: "2.2.2"
sdks:
dart: ">=3.7.0 <4.0.0"
dart: ">=3.6.0 <4.0.0"
flutter: ">=3.27.0"

View File

@@ -5,7 +5,7 @@ publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.5.2
sdk: ">=3.6.0 <4.0.0"
dependencies:
@@ -22,32 +22,33 @@ dependencies:
freezed_annotation: ^2.4.4
dartz: ^0.10.1
flutter_bloc: ^9.1.1
auto_route: ^9.3.0+1
auto_route: ^10.1.0+1
cupertino_icons: ^1.0.8
talker_flutter: ^4.9.3
talker_flutter: ^5.0.0
talker_cherrypick_logger:
path: ../../talker_cherrypick_logger
talker_dio_logger: ^5.0.0
talker_bloc_logger: ^5.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
build_runner: 2.4.15
cherrypick_generator:
path: ../../cherrypick_generator
build_runner: 2.4.15
retrofit_generator: ^9.1.5
freezed: ^2.5.8
json_serializable: ^6.9.0
auto_route_generator: ^9.0.0
talker_dio_logger: ^4.9.3
talker_bloc_logger: ^4.9.3
retrofit_generator: ^9.1.5
auto_route_generator: ^10.0.1
freezed: ^2.5.8
melos: ^6.3.2
flutter:
uses-material-design: true
dev_dependencies:
melos: ^6.3.2

View File

@@ -13,6 +13,27 @@ packages:
- examples/postly
scripts:
clean_all:
run: |
melos clean
melos exec -- rm -rf lib/**.g.dart lib/generated/
description: |
Очищает build артефакты flutter и сгенерированный код во всех пакетах.
all:
steps:
- codegen
- analyze
- format
- test
description: Run all steps.
lint:all:
steps:
- analyze
- format
description: Run all static analysis checks.
analyze:
exec: dart analyze
@@ -20,11 +41,10 @@ scripts:
exec: dart format lib
test:
run: |
echo "Running Dart tests..."
melos exec --scope="cherrypick,cherrypick_annotations,cherrypick_generator" -- dart test --reporter=compact
echo "Running Flutter tests..."
melos exec --scope="cherrypick_flutter" -- flutter test --reporter=compact
steps:
- test:dart
- test:flutter
description: Run all tests.
test:dart:
description: "Run tests for Dart packages only"

View File

@@ -1,27 +1,6 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: "45cfa8471b89fb6643fe9bf51bd7931a76b8f5ec2d65de4fb176dba8d4f22c77"
url: "https://pub.dev"
source: hosted
version: "73.0.0"
_macros:
dependency: transitive
description: dart
source: sdk
version: "0.3.2"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "4959fec185fe70cce007c57e9ab6983101dbe593d2bf8bbfb4453aaec0cf470a"
url: "https://pub.dev"
source: hosted
version: "6.8.0"
ansi_styles:
dependency: transitive
description:
@@ -46,38 +25,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
build:
dependency: transitive
description:
name: build
sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
built_collection:
dependency: transitive
description:
name: built_collection
sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
built_value:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
url: "https://pub.dev"
source: hosted
version: "8.9.5"
charcode:
dependency: transitive
description:
@@ -94,22 +41,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.3"
cli_config:
dependency: transitive
description:
name: cli_config
sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
url: "https://pub.dev"
source: hosted
version: "0.2.0"
cli_launcher:
dependency: transitive
description:
name: cli_launcher
sha256: "5e7e0282b79e8642edd6510ee468ae2976d847a0a29b3916e85f5fa1bfe24005"
sha256: "67d89e0a1c07b103d1253f6b953a43d3f502ee36805c8cfc21196282c9ddf177"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
version: "0.3.2"
cli_util:
dependency: transitive
description:
@@ -126,14 +65,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_builder:
dependency: transitive
description:
name: code_builder
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
url: "https://pub.dev"
source: hosted
version: "4.10.1"
collection:
dependency: transitive
description:
@@ -146,42 +77,10 @@ packages:
dependency: transitive
description:
name: conventional_commit
sha256: dec15ad1118f029c618651a4359eb9135d8b88f761aa24e4016d061cd45948f2
sha256: fad254feb6fb8eace2be18855176b0a4b97e0d50e416ff0fe590d5ba83735d34
url: "https://pub.dev"
source: hosted
version: "0.6.0+1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.2"
coverage:
dependency: transitive
description:
name: coverage
sha256: "802bd084fb82e55df091ec8ad1553a7331b61c08251eef19a508b6f3f3a9858d"
url: "https://pub.dev"
source: hosted
version: "1.13.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
url: "https://pub.dev"
source: hosted
version: "3.0.6"
dart_style:
dependency: transitive
description:
name: dart_style
sha256: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab"
url: "https://pub.dev"
source: hosted
version: "2.3.7"
version: "0.6.1"
file:
dependency: transitive
description:
@@ -190,22 +89,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob:
dependency: transitive
description:
@@ -226,18 +109,10 @@ packages:
dependency: transitive
description:
name: http
sha256: fe7ab022b76f3034adc518fb6ea04a82387620e19977665ea18d30a1cf43442f
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.3.0"
http_multi_server:
dependency: transitive
description:
name: http_multi_server
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
url: "https://pub.dev"
source: hosted
version: "3.2.2"
version: "1.5.0"
http_parser:
dependency: transitive
description:
@@ -262,14 +137,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf
url: "https://pub.dev"
source: hosted
version: "0.7.1"
json_annotation:
dependency: transitive
description:
@@ -282,34 +149,10 @@ packages:
dependency: "direct dev"
description:
name: lints
sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "2.1.1"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
macros:
dependency: transitive
description:
name: macros
sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536"
url: "https://pub.dev"
source: hosted
version: "0.1.2-main.4"
matcher:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "5.1.1"
melos:
dependency: "direct dev"
description:
@@ -322,26 +165,10 @@ packages:
dependency: "direct main"
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
url: "https://pub.dev"
source: hosted
version: "1.16.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
mockito:
dependency: "direct dev"
description:
name: mockito
sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917"
url: "https://pub.dev"
source: hosted
version: "5.4.4"
version: "1.17.0"
mustache_template:
dependency: transitive
description:
@@ -350,22 +177,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
node_preamble:
dependency: transitive
description:
name: node_preamble
sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
package_config:
dependency: transitive
description:
name: package_config
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
url: "https://pub.dev"
source: hosted
version: "2.2.0"
path:
dependency: transitive
description:
@@ -394,10 +205,10 @@ packages:
dependency: transitive
description:
name: process
sha256: "107d8be718f120bbba9dcd1e95e3bd325b1b4a4f07db64154635ba03f2567a0d"
sha256: c6248e4526673988586e8c00bb22a49210c258dc91df5227d5da9748ecf79744
url: "https://pub.dev"
source: hosted
version: "5.0.3"
version: "5.0.5"
prompts:
dependency: transitive
description:
@@ -426,66 +237,10 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
shelf_packages_handler:
dependency: transitive
description:
name: shelf_packages_handler
sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
shelf_static:
dependency: transitive
description:
name: shelf_static
sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
url: "https://pub.dev"
source: hosted
version: "1.1.3"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
source_gen:
dependency: transitive
description:
name: source_gen
sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
source_map_stack_trace:
dependency: transitive
description:
name: source_map_stack_trace
sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
url: "https://pub.dev"
source: hosted
version: "2.1.2"
source_maps:
dependency: transitive
description:
name: source_maps
sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812"
url: "https://pub.dev"
source: hosted
version: "0.10.13"
source_span:
dependency: transitive
description:
@@ -502,14 +257,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.12.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
@@ -526,30 +273,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test:
dependency: "direct dev"
description:
name: test
sha256: "301b213cd241ca982e9ba50266bd3f5bd1ea33f1455554c5abb85d1be0e2d87e"
url: "https://pub.dev"
source: hosted
version: "1.25.15"
test_api:
dependency: transitive
description:
name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
url: "https://pub.dev"
source: hosted
version: "0.7.4"
test_core:
dependency: transitive
description:
name: test_core
sha256: "84d17c3486c8dfdbe5e12a50c8ae176d15e2a771b96909a9442b40173649ccaa"
url: "https://pub.dev"
source: hosted
version: "0.6.8"
typed_data:
dependency: transitive
description:
@@ -558,22 +281,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
url: "https://pub.dev"
source: hosted
version: "15.0.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web:
dependency: transitive
description:
@@ -582,30 +289,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web_socket:
dependency: transitive
description:
name: web_socket
sha256: bfe6f435f6ec49cb6c01da1e275ae4228719e59a6b067048c51e72d9d63bcc4b
url: "https://pub.dev"
source: hosted
version: "1.0.0"
web_socket_channel:
dependency: transitive
description:
name: web_socket_channel
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webkit_inspection_protocol:
dependency: transitive
description:
name: webkit_inspection_protocol
sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
yaml:
dependency: transitive
description:
@@ -623,4 +306,4 @@ packages:
source: hosted
version: "2.2.2"
sdks:
dart: ">=3.5.2 <4.0.0"
dart: ">=3.6.0 <4.0.0"

View File

@@ -7,16 +7,11 @@ repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: ">=3.2.0 <4.0.0"
dependencies:
meta: ^1.3.0
dev_dependencies:
#pedantic: ^1.11.0
test: ^1.17.2
mockito: ^5.0.6
lints: ^2.1.0
lints: ^5.1.1
melos: ^6.3.2

View File

@@ -1,3 +1,37 @@
## 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(talker_cherrypick_logger): sync version with cherrypick 3.0.0-dev.12
## 1.1.0-dev.7
- Update a dependency to the latest release.
## 1.1.0-dev.6
- Update a dependency to the latest release.
## 1.1.0-dev.5
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
## 1.1.0-dev.4
- **DOCS**(readme): update install instructions to use pub.dev as default method and remove obsolete git example.
## 1.1.0-dev.3
## 1.1.0-dev.2
- Bump "talker_cherrypick_logger" to `1.1.0-dev.2`.

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)
---
# talker_cherrypick_logger
An integration package that allows you to log [CherryPick](https://github.com/pese-dot-work/cherrypick) Dependency Injection (DI) container events using the [Talker](https://pub.dev/packages/talker) logging system.
@@ -21,15 +26,14 @@ All CherryPick lifecycle events, instance creations, cache operations, module ac
### 1. Add dependencies
Install the package **from [pub.dev](https://pub.dev/packages/talker_cherrypick_logger)**:
In your `pubspec.yaml`:
```yaml
dependencies:
cherrypick: ^latest
talker: ^latest
talker_cherrypick_logger:
git:
url: https://github.com/pese-dot-work/cherrypick.git
path: talker_cherrypick_logger
talker_cherrypick_logger: ^latest
```
### 2. Import the package

View File

@@ -69,26 +69,32 @@ class TalkerCherryPickObserver implements CherryPickObserver {
/// Called when a new instance is created.
@override
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {
talker.info('[create][CherryPick] $name$type => $instance (scope: $scopeName)');
void onInstanceCreated(String name, Type type, Object instance,
{String? scopeName}) {
talker.info(
'[create][CherryPick] $name$type => $instance (scope: $scopeName)');
}
/// Called when an instance is disposed.
@override
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {
talker.info('[dispose][CherryPick] $name$type => $instance (scope: $scopeName)');
void onInstanceDisposed(String name, Type type, Object instance,
{String? scopeName}) {
talker.info(
'[dispose][CherryPick] $name$type => $instance (scope: $scopeName)');
}
/// Called when modules are installed.
@override
void onModulesInstalled(List<String> modules, {String? scopeName}) {
talker.info('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
talker.info(
'[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
}
/// Called when modules are removed.
@override
void onModulesRemoved(List<String> modules, {String? scopeName}) {
talker.info('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
talker.info(
'[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
}
/// Called when a DI scope is opened.
@@ -106,7 +112,8 @@ class TalkerCherryPickObserver implements CherryPickObserver {
/// Called if the DI container detects a cycle in the dependency graph.
@override
void onCycleDetected(List<String> chain, {String? scopeName}) {
talker.warning('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
talker.warning(
'[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
}
/// Called when an instance is found in the cache.
@@ -136,6 +143,7 @@ class TalkerCherryPickObserver implements CherryPickObserver {
/// Called for error events with optional stack trace.
@override
void onError(String message, Object? error, StackTrace? stackTrace) {
talker.handle(error ?? '[CherryPick] $message', stackTrace, '[error][CherryPick] $message');
talker.handle(error ?? '[CherryPick] $message', stackTrace,
'[error][CherryPick] $message');
}
}
}

View File

@@ -1,8 +1,8 @@
name: talker_cherrypick_logger
description: A starting point for Dart libraries or applications.
version: 1.1.0-dev.2
homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki
description: A Talker logger integration for CherryPick DI to observe and log DI events and errors.
version: 3.0.1
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
@@ -13,14 +13,14 @@ topics:
- log
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: '>=3.2.0 <4.0.0'
# Add regular dependencies here.
dependencies:
talker: ^4.9.3
cherrypick: ^3.0.0-dev.9
talker: ^5.0.0
cherrypick: ^3.0.1
dev_dependencies:
lints: ^5.0.0
test: ^1.24.0
lints: ^4.0.0
test: ^1.25.6

View File

@@ -15,7 +15,8 @@ void main() {
test('onInstanceRequested logs info', () {
observer.onInstanceRequested('A', String, scopeName: 'test');
final log = talker.history.last;
expect(log.message, contains('[request][CherryPick] A — String (scope: test)'));
expect(log.message,
contains('[request][CherryPick] A — String (scope: test)'));
});
test('onCycleDetected logs warning', () {

20
website/.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

41
website/README.md Normal file
View File

@@ -0,0 +1,41 @@
# Website
This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
## Installation
```bash
yarn
```
## Local Development
```bash
yarn start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
## Build
```bash
yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## Deployment
Using SSH:
```bash
USE_SSH=true yarn deploy
```
Not using SSH:
```bash
GIT_USER=<Your GitHub username> yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

View File

@@ -0,0 +1,14 @@
---
sidebar_position: 9
---
# Additional Modules
CherryPick provides a set of official add-on modules for advanced use cases and specific platforms:
| Module name | Description |
|-------------|-------------|
| [**cherrypick_annotations**](https://pub.dev/packages/cherrypick_annotations) | Dart annotations for concise DI definitions and code generation. |
| [**cherrypick_generator**](https://pub.dev/packages/cherrypick_generator) | Code generator to produce DI bindings based on annotations. |
| [**cherrypick_flutter**](https://pub.dev/packages/cherrypick_flutter) | Flutter integration: DI provider widgets and helpers for Flutter. |
| [**talker_cherrypick_logger**](https://pub.dev/packages/talker_cherrypick_logger) | Advanced logger for CherryPick DI events and state. Provides seamless integration with [Talker](https://pub.dev/packages/talker) logger, enabling central and visual tracking of DI events, errors, and diagnostics in both UI and console. |

View File

@@ -0,0 +1,4 @@
{
"label": "Advanced Features",
"position": 6
}

View File

@@ -0,0 +1,71 @@
---
sidebar_position: 3
---
# Circular Dependency Detection
CherryPick can detect circular dependencies in your DI configuration, helping you avoid infinite loops and hard-to-debug errors.
## How to use:
### 1. Enable Cycle Detection for Development
**Local detection (within one scope):**
```dart
final scope = CherryPick.openSafeRootScope(); // Local detection enabled by default
// or, for an existing scope:
scope.enableCycleDetection();
```
**Global detection (across all scopes):**
```dart
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openGlobalSafeRootScope();
```
### 2. Error Example
If you declare mutually dependent services:
```dart
class A { A(B b); }
class B { B(A a); }
scope.installModules([
Module((bind) {
bind<A>().to((s) => A(s.resolve<B>()));
bind<B>().to((s) => B(s.resolve<A>()));
}),
]);
scope.resolve<A>(); // Throws CircularDependencyException
```
### 3. Typical Usage Pattern
- **Always enable detection** in debug and test environments for maximum safety.
- **Disable detection** in production for performance (after code is tested).
```dart
import 'package:flutter/foundation.dart';
void main() {
if (kDebugMode) {
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
}
runApp(MyApp());
}
```
### 4. Handling and Debugging Errors
On detection, `CircularDependencyException` is thrown with a readable dependency chain:
```dart
try {
scope.resolve<MyService>();
} on CircularDependencyException catch (e) {
print('Dependency chain: ${e.dependencyChain}');
}
```
<!-- **More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md) -->

View File

@@ -0,0 +1,45 @@
---
sidebar_position: 1
---
# Hierarchical Subscopes
CherryPick supports a hierarchical structure of scopes, allowing you to create complex and modular dependency graphs for advanced application architectures. Each subscope inherits from its parent, enabling context-specific overrides while still allowing access to global or shared services.
## Key Points
- **Subscopes** are child scopes that can be opened from any existing scope (including the root).
- Dependencies registered in a subscope override those from parent scopes when resolved.
- If a dependency is not found in the current subscope, the resolution process automatically searches parent scopes up the hierarchy.
- Subscopes can have their own modules, lifetime, and disposable objects.
- You can nest subscopes to any depth, modeling features, flows, or components independently.
## Example
```dart
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
// Open a hierarchical subscope for a feature or page
final userFeatureScope = rootScope.openSubScope('userFeature');
userFeatureScope.installModules([UserFeatureModule()]);
// Dependencies defined in UserFeatureModule will take precedence
final userService = userFeatureScope.resolve<UserService>();
// If not found in the subscope, lookup continues in the parent (rootScope)
final sharedService = userFeatureScope.resolve<SharedService>();
// You can nest subscopes
final dialogScope = userFeatureScope.openSubScope('dialog');
dialogScope.installModules([DialogModule()]);
final dialogManager = dialogScope.resolve<DialogManager>();
```
## Use Cases
- Isolate feature modules, flows, or screens with their own dependencies.
- Provide and override services for specific navigation stacks or platform-specific branches.
- Manage the lifetime and disposal of groups of dependencies independently (e.g., per-user, per-session, per-component).
**Tip:** Always close subscopes when they are no longer needed to release resources and trigger cleanup of Disposable dependencies.

View File

@@ -0,0 +1,63 @@
---
sidebar_position: 2
---
# Logging
CherryPick lets you log all dependency injection (DI) events and errors using a flexible observer mechanism.
## Custom Observers
You can pass any implementation of `CherryPickObserver` to your root scope or any sub-scope.
This allows centralized and extensible logging, which you can direct to print, files, visualization frameworks, external loggers, or systems like [Talker](https://pub.dev/packages/talker).
### Example: Printing All Events
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Use the built-in PrintCherryPickObserver for console logs
final observer = PrintCherryPickObserver();
final scope = CherryPick.openRootScope(observer: observer);
// All DI actions and errors will now be printed!
}
```
### Example: Advanced Logging with Talker
For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](https://pub.dev/packages/talker_cherrypick_logger):
<!-- For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](../talker_cherrypick_logger): -->
```dart
import 'package:cherrypick/cherrypick.dart';
import 'package:talker/talker.dart';
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
void main() {
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.openRootScope(observer: observer);
// All container events go to the Talker log system!
}
```
## Default Behavior
- By default, logging is silent (`SilentCherryPickObserver`) for production, with no output unless you supply an observer.
- You can configure observers **per scope** for isolated, test-specific, or feature-specific logging.
## Observer Capabilities
Events you can observe and log:
- Dependency registration
- Instance requests, creations, disposals
- Module installs/removals
- Scope opening/closing
- Cache hits/misses
- Cycle detection
- Diagnostics, warnings, errors
Just implement or extend `CherryPickObserver` and direct messages anywhere you want!
## When to Use
- Enable verbose logging and debugging in development or test builds.
- Route logs to your main log system or analytics.
- Hook into DI lifecycle for profiling or monitoring.

View File

@@ -0,0 +1,10 @@
---
sidebar_position: 4
---
# Performance Improvements
> **Performance Note:**
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()` and related methods are now O(1) operations, regardless of the number of modules or bindings in your scope. Previously, the library had to iterate over all modules and bindings to locate the requested dependency, which could impact performance as your project grew.
>
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.

View File

@@ -0,0 +1,7 @@
---
sidebar_position: 10
---
# Contributing
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -0,0 +1,4 @@
{
"label": "Core Concepts",
"position": 4
}

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