mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-05-16 10:10:43 +00:00
Compare commits
19 Commits
cherrypick
...
fix/BR-imp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9500a6a1c | ||
|
|
fb0e77a87f | ||
|
|
c413dfed20 | ||
|
|
4077ed8469 | ||
|
|
59234b44c2 | ||
|
|
3c4fc67166 | ||
|
|
3331a3ee9c | ||
|
|
3c550db8cd | ||
|
|
e6b3017384 | ||
|
|
3b2df58e9a | ||
|
|
f9100eb9ba | ||
|
|
94b3ba284a | ||
|
|
0651f74472 | ||
|
|
776f29945a | ||
|
|
49361f2f9e | ||
|
|
4953e917c9 | ||
|
|
cccf460f01 | ||
|
|
0c1ef70b73 | ||
|
|
eb6d786600 |
149
.github/prompts/opsx-apply.prompt.md
vendored
Normal file
149
.github/prompts/opsx-apply.prompt.md
vendored
Normal file
@@ -0,0 +1,149 @@
|
||||
---
|
||||
description: Implement tasks from an OpenSpec change (Experimental)
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- Context file paths (varies by schema)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read the files listed in `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx:archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
154
.github/prompts/opsx-archive.prompt.md
vendored
Normal file
154
.github/prompts/opsx-archive.prompt.md
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
---
|
||||
description: Archive a completed change in the experimental workflow
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
170
.github/prompts/opsx-explore.prompt.md
vendored
Normal file
170
.github/prompts/opsx-explore.prompt.md
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
---
|
||||
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|--------------|------------------|
|
||||
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||
| Requirement changed | `specs/<capability>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
103
.github/prompts/opsx-propose.prompt.md
vendored
Normal file
103
.github/prompts/opsx-propose.prompt.md
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
---
|
||||
description: Propose a new change - create it and generate all artifacts in one step
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` to start implementing."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
156
.github/skills/openspec-apply-change/SKILL.md
vendored
Normal file
156
.github/skills/openspec-apply-change/SKILL.md
vendored
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
name: openspec-apply-change
|
||||
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.2.0"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read the files listed in `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! Ready to archive this change.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
114
.github/skills/openspec-archive-change/SKILL.md
vendored
Normal file
114
.github/skills/openspec-archive-change/SKILL.md
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: openspec-archive-change
|
||||
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.2.0"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Whether specs were synced (if applicable)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, use openspec-sync-specs approach (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
288
.github/skills/openspec-explore/SKILL.md
vendored
Normal file
288
.github/skills/openspec-explore/SKILL.md
vendored
Normal file
@@ -0,0 +1,288 @@
|
||||
---
|
||||
name: openspec-explore
|
||||
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.2.0"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|--------------|------------------|
|
||||
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||
| Requirement changed | `specs/<capability>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Handling Different Entry Points
|
||||
|
||||
**User brings a vague idea:**
|
||||
```
|
||||
User: I'm thinking about adding real-time collaboration
|
||||
|
||||
You: Real-time collab is a big space. Let me think about this...
|
||||
|
||||
COLLABORATION SPECTRUM
|
||||
════════════════════════════════════════════
|
||||
|
||||
Awareness Coordination Sync
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Presence│ │Cursors │ │ CRDT │
|
||||
│ "3 │ │ Multi │ │Conflict│
|
||||
│online" │ │ select │ │ free │
|
||||
└────────┘ └────────┘ └────────┘
|
||||
│ │ │
|
||||
trivial moderate complex
|
||||
|
||||
Where's your head at?
|
||||
```
|
||||
|
||||
**User brings a specific problem:**
|
||||
```
|
||||
User: The auth system is a mess
|
||||
|
||||
You: [reads codebase]
|
||||
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ CURRENT AUTH FLOW │
|
||||
└─────────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│ Google │ │ GitHub │ │ Email │
|
||||
│ OAuth │ │ OAuth │ │ Magic │
|
||||
└────┬────┘ └────┬────┘ └────┬────┘
|
||||
│ │ │
|
||||
└─────────────┼─────────────┘
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Session │
|
||||
└─────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Perms │
|
||||
└───────────┘
|
||||
|
||||
I see three tangles. Which one's burning?
|
||||
```
|
||||
|
||||
**User is stuck mid-implementation:**
|
||||
```
|
||||
User: /opsx:explore add-auth-system
|
||||
The OAuth integration is more complex than expected
|
||||
|
||||
You: [reads change artifacts]
|
||||
|
||||
You're on task 4: "Implement OAuth flow"
|
||||
|
||||
Let me trace what's involved...
|
||||
|
||||
[draws diagram, explores options, suggests paths]
|
||||
|
||||
Want to update the design to reflect this?
|
||||
Or add a spike task to investigate?
|
||||
```
|
||||
|
||||
**User wants to compare options:**
|
||||
```
|
||||
User: Should we use Postgres or SQLite?
|
||||
|
||||
You: Generic answer is boring. What's the context?
|
||||
|
||||
User: A CLI tool that tracks local dev environments
|
||||
|
||||
You: That changes everything.
|
||||
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ CLI TOOL DATA STORAGE │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
Key constraints:
|
||||
• No daemon running
|
||||
• Must work offline
|
||||
• Single user
|
||||
|
||||
SQLite Postgres
|
||||
Deployment embedded ✓ needs server ✗
|
||||
Offline yes ✓ no ✗
|
||||
Single file yes ✓ no ✗
|
||||
|
||||
SQLite. Not even close.
|
||||
|
||||
Unless... is there a sync component?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When it feels like things are crystallizing, you might summarize:
|
||||
|
||||
```
|
||||
## What We Figured Out
|
||||
|
||||
**The problem**: [crystallized understanding]
|
||||
|
||||
**The approach**: [if one emerged]
|
||||
|
||||
**Open questions**: [if any remain]
|
||||
|
||||
**Next steps** (if ready):
|
||||
- Create a change proposal
|
||||
- Keep exploring: just keep talking
|
||||
```
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
110
.github/skills/openspec-propose/SKILL.md
vendored
Normal file
110
.github/skills/openspec-propose/SKILL.md
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: openspec-propose
|
||||
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.2.0"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no clear input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
101
CHANGELOG.md
101
CHANGELOG.md
@@ -3,6 +3,81 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## 2026-01-29
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v4.0.0-dev.0`](#cherrypick_annotations---v400-dev0)
|
||||
- [`cherrypick_generator` - `v4.0.0-dev.0`](#cherrypick_generator---v400-dev0)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- There are no other changes in this release.
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v4.0.0-dev.0`
|
||||
|
||||
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
|
||||
|
||||
#### `cherrypick_generator` - `v4.0.0-dev.0`
|
||||
|
||||
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
|
||||
|
||||
|
||||
## 2026-01-29
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v3.0.3`](#cherrypick_annotations---v303)
|
||||
- [`cherrypick_generator` - `v3.0.3`](#cherrypick_generator---v303)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.3`
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.3`
|
||||
|
||||
|
||||
## 2026-01-29
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v3.0.2`](#cherrypick_annotations---v302)
|
||||
- [`cherrypick_generator` - `v3.0.2`](#cherrypick_generator---v302)
|
||||
|
||||
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
|
||||
|
||||
- `cherrypick_annotations` - `v3.0.2`
|
||||
- `cherrypick_generator` - `v3.0.2`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.2`
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.2`
|
||||
|
||||
|
||||
## 2025-10-20
|
||||
|
||||
### Changes
|
||||
@@ -34,6 +109,32 @@ Packages with dependency updates only:
|
||||
- **FIX**(scope): properly clear binding and module references on dispose.
|
||||
|
||||
|
||||
## 2025-09-09
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v3.0.2-dev.0`](#cherrypick_annotations---v302-dev0)
|
||||
- [`cherrypick_generator` - `v3.0.2-dev.0`](#cherrypick_generator---v302-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.2-dev.0`
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.2-dev.0`
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
|
||||
## 2025-09-09
|
||||
|
||||
### Changes
|
||||
|
||||
137
benchmark_di/REPORT_BENCHMARK_COMPARISON.md
Normal file
137
benchmark_di/REPORT_BENCHMARK_COMPARISON.md
Normal file
@@ -0,0 +1,137 @@
|
||||
# Benchmark Comparison: cherrypick Performance Improvements
|
||||
|
||||
## Parameters
|
||||
|
||||
- chainCount = 100
|
||||
- nestingDepth = 100
|
||||
- repeat = 5
|
||||
- warmup = 2
|
||||
|
||||
---
|
||||
|
||||
## Results: firstResolve (Mean, µs)
|
||||
|
||||
### Lazy Singleton Scenarios (fair cross-DI comparison)
|
||||
|
||||
| Scenario | BR-improvements | develop | Improvement (vs develop) |
|
||||
|-----------------------|-----------------|---------|--------------------------|
|
||||
| ChainLazySingleton | 46.80 | 114.20 | **2.4× faster** |
|
||||
| ChainFactory | 54.00 | 105.60 | **2.0× faster** |
|
||||
| AsyncChain | 247.80 | 959.20 | **3.9× faster** |
|
||||
| Named | 0.20 | 3.60 | **18× faster** |
|
||||
| Override | 9.80 | 110.40 | **11.3× faster** |
|
||||
| RegisterLazySingleton | 1.20 | 19.60 | **16.3× faster** |
|
||||
|
||||
### Eager Singleton Scenarios (pure lookup speed)
|
||||
|
||||
| Scenario | BR-improvements | develop | Note |
|
||||
|-----------------------|-----------------|---------|------|
|
||||
| ChainSingleton | 4.80 | 114.20 | Not comparable — see note below |
|
||||
| RegisterSingleton | 12.80 | 19.60 | **1.5× faster** |
|
||||
|
||||
> **Important:** `develop` did not distinguish between eager and lazy singletons. Its "singleton" was always lazy (instance created on first resolve). The develop `ChainSingleton` value (114.2 µs) measures the same thing as BR-improvements `ChainLazySingleton` (46.8 µs). The `ChainSingleton` eager column in BR-improvements (4.8 µs) measures pure lookup after `.toInstance()` eager registration — a fundamentally different operation. Fair comparison: 114.2 → 46.8 = 2.4× faster.
|
||||
|
||||
\* All measurements taken on the same hardware with identical benchmark parameters.
|
||||
|
||||
---
|
||||
|
||||
## Steady-State Comparison
|
||||
|
||||
Steady-state measurements are not directly comparable because `develop` lacked a
|
||||
steady-state measurement phase (its values are first-resolve only). BR-improvements
|
||||
introduced a separate steady-state phase to isolate cached lookup performance.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
The `BR-improvements` branch shows performance improvements on first resolve vs the `develop` baseline:
|
||||
|
||||
- **ChainLazySingleton**: 2.4× faster (46.8 µs vs 114.2 µs)
|
||||
- **ChainFactory**: 2.0× faster (54.0 µs vs 105.6 µs)
|
||||
- **AsyncChain**: 3.9× faster (247.8 µs vs 959.2 µs)
|
||||
- **Named**: 18× faster (0.2 µs vs 3.6 µs)
|
||||
- **Override**: 11.3× faster (9.8 µs vs 110.4 µs)
|
||||
- **RegisterLazySingleton**: 16.3× faster (1.2 µs vs 19.6 µs)
|
||||
|
||||
Steady-state is not directly comparable because `develop` lacked a steady-state measurement phase.
|
||||
|
||||
### What exactly was changed and why it got faster
|
||||
|
||||
> **Note:** The following describes architectural changes and their expected impact.
|
||||
> Specific percentage contributions have not been measured via isolated A/B tests.
|
||||
|
||||
---
|
||||
|
||||
#### 1. Split monolithic resolvers into type-specialized classes
|
||||
**What changed:** The single `ProviderResolver<T>` class (which handled sync/async/param/ no-param in one place with runtime type checks) was split into four dedicated classes:
|
||||
- `SyncProviderResolver<T>` / `SyncProviderWithParamsResolver<T>`
|
||||
- `AsyncProviderResolver<T>` / `AsyncProviderWithParamsResolver<T>`
|
||||
|
||||
`ProviderResolver.create()` uses fast-path `is` checks to pick the correct implementation immediately, without calling the provider. A lazy fallback `FutureOrProviderResolver` is used only when the static type is genuinely unknown.
|
||||
|
||||
Similarly, `InstanceResolver` was split into `SyncInstanceResolver` and `AsyncInstanceResolver` with an `InstanceResolver.create()` factory.
|
||||
|
||||
**Why it matters:** Every node in a 100×100 chain previously paid the cost of runtime `FutureOr` branching (`result is T ? sync : async`) on every resolve. Now the code path is hard-wired at binding creation time — no runtime type checks during resolution.
|
||||
|
||||
**Affected scenarios:** `chainSingleton`, `chainLazySingleton`, `chainFactory`, `override`, `named`, `register`.
|
||||
|
||||
---
|
||||
|
||||
#### 2. Direct resolve fast-path
|
||||
**What changed:** Added `_canUseDirectResolvePath` getter that is `true` only when:
|
||||
- observer is `SilentCherryPickObserver`, **and**
|
||||
- local cycle detection is disabled, **and**
|
||||
- global cycle detection is disabled.
|
||||
|
||||
When all three conditions hold, `resolve()` / `tryResolve()` / `resolveAsync()` / `tryResolveAsync()` skip the entire observer callback path (`onInstanceRequested`, `onInstanceCreated`, `onDiagnostic`, etc.) and cycle-detection wrappers entirely. They call `_tryResolveInternal` directly.
|
||||
|
||||
**Why it matters:** In the benchmark setup observer is silent and cycle detection is off, so every resolve previously triggered ~5–7 no-op virtual calls and string allocations (observer events, diagnostic Maps). That overhead is now completely bypassed.
|
||||
|
||||
**Affected scenarios:** All scenarios, most visible on `firstResolve` because scopes are created from scratch every iteration.
|
||||
|
||||
---
|
||||
|
||||
#### 3. Silent observer guard
|
||||
**What changed:** All diagnostic calls (`observer.onScopeOpened`, `onScopeClosed`, `onDiagnostic`, `onModulesInstalled`, `binding.logAllDeferred()`) are now wrapped in `if (!_isSilentObserver)`. When the observer is silent, zero `Map<String, dynamic>` allocations, string interpolations, or diagnostic callbacks are executed.
|
||||
|
||||
**Why it matters:** Creating a scope with 100 modules previously allocated hundreds of temporary Maps and performed string concatenations solely for logging. That work is now entirely skipped.
|
||||
|
||||
**Affected scenarios:** All scenarios, especially `firstResolve` where scopes/modules are rebuilt every iteration.
|
||||
|
||||
---
|
||||
|
||||
#### 4. Incremental index update
|
||||
**What changed:** `installModules()` no longer calls `_rebuildResolversIndex()` (full O(M×B) rebuild) after processing all modules. Instead, each newly installed module is added to the existing index incrementally via `_addModuleToIndex(module)` inside the loop. `_rebuildResolversIndex()` is now only called from `dropModules()`.
|
||||
|
||||
**Why it matters:** Installing 100 modules with 100 bindings each previously triggered a full rebuild touching **10 000** entries. Now only the 100 new entries are inserted.
|
||||
|
||||
**Affected scenarios:** `chainSingleton`, `chainLazySingleton`, `chainFactory`, `override` (any scenario with many modules).
|
||||
|
||||
---
|
||||
|
||||
#### 5. `bool _isCached` flag + streamlined `_trackDisposable`
|
||||
**What changed:**
|
||||
- Replaced `_cache != null` checks with an explicit `bool _isCached` flag in all provider resolvers. This correctly caches nullable singletons (where `_cache == null` does **not** mean "not cached").
|
||||
- `_trackDisposable` removed the `!_disposables.contains(obj)` guard; it now simply calls `_disposables.add(obj)`.
|
||||
- `_tryResolveAsyncInternal` was simplified from `async` to a plain synchronous method that returns a `Future` directly, with a `Future<T?>.value(null)` fallback.
|
||||
|
||||
**Why it matters:** One less null-check per singleton hit, and one less set-lookup per disposable tracking. The async path no longer pays for an extra `async` frame.
|
||||
|
||||
**Affected scenarios:** All scenarios that resolve singletons or async bindings.
|
||||
|
||||
---
|
||||
|
||||
#### 6. Dispose loop cleanup
|
||||
**What changed:** In `dispose()`:
|
||||
- `Map<String, Scope>.from(_scopeMap)` → `_scopeMap.values.toList()`
|
||||
- `Set<Disposable>.from(_disposables)` → `_disposables.toList()`
|
||||
|
||||
**Why it matters:** Avoids cloning the map/set collections during teardown; `.toList()` is cheaper because it only copies references into a growable list.
|
||||
|
||||
**Affected scenarios:** All scenarios that create and tear down scopes.
|
||||
|
||||
---
|
||||
|
||||
### Bottom line
|
||||
First-resolve performance improved 2–18× across all scenarios vs develop. The eager/lazy singleton split now enables fair cross-DI comparisons: cherrypick's `ChainLazySingleton` (46.8 µs) is 2.4× faster than develop's equivalent (114.2 µs).
|
||||
148
benchmark_di/REPORT_v2.md
Normal file
148
benchmark_di/REPORT_v2.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod vs kiwi vs yx_scope
|
||||
|
||||
## Benchmark Parameters
|
||||
|
||||
- chainCount = 100
|
||||
- nestingDepth = 100
|
||||
- repeat = 5
|
||||
- warmup = 2
|
||||
|
||||
## Benchmark Scenarios
|
||||
|
||||
1. **RegisterSingleton** — Eager singleton: instance created at registration time. Measures pure lookup speed.
|
||||
2. **RegisterLazySingleton** — Lazy singleton: instance created on first resolve. Measures creation + caching.
|
||||
3. **ChainSingleton** — Eager dependency chain A → B → ... → N. All instances pre-created at registration. Pure lookup.
|
||||
4. **ChainLazySingleton** — Lazy dependency chain. Full graph creation + caching on first resolve. **Primary fairness metric.**
|
||||
5. **ChainFactory** — All chain elements are factories. Stateless creation chain.
|
||||
6. **AsyncChain** — Async chain (async factory). Performance on async graphs.
|
||||
7. **Named** — Registers two bindings with names, resolves by name. Named lookup test.
|
||||
8. **Override** — Registers a chain/alias in a child scope. Tests scope overrides.
|
||||
|
||||
> **Note:** kiwi and yx_scope do not support eager singleton registration. Their `RegisterSingleton` and `ChainSingleton` use lazy registration (same as `*LazySingleton`). Results marked with † reflect this.
|
||||
|
||||
---
|
||||
|
||||
## Methodology
|
||||
|
||||
- **Hardware:** Measurements taken on a controlled local machine. Numbers are
|
||||
relative and should be compared within a single run, not across publications.
|
||||
- **Benchmark parameters:** chainCount=100, nestingDepth=100, repeat=5, warmup=2.
|
||||
- **Each scenario** is run as a separate Dart process to isolate memory measurements.
|
||||
- **Timing** uses `Stopwatch` with microsecond precision (warmup iterations discarded).
|
||||
- **Memory** measured via `ProcessInfo.currentRss` (peak RSS per process).
|
||||
- **Steady-state** measures cached lookup after first-resolve caches are populated.
|
||||
|
||||
---
|
||||
|
||||
## First Resolve (Mean time, µs)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|----------|----------|-------|----------|
|
||||
| RegisterSingleton | 12.8 | 14.6 | 17.6 | 0.4† | 22.8† |
|
||||
| RegisterLazySingleton | 1.2 | 4.2 | 5.4 | 0.2 | 9.0 |
|
||||
| ChainSingleton | 4.8 | 2.8 | 436.2 | 67.8† | 134.2† |
|
||||
| ChainLazySingleton | 46.8 | 193.2 | 398.0 | 56.0 | 266.8 |
|
||||
| ChainFactory | 54.0 | 66.0 | 443.0 | 55.6 | 146.6 |
|
||||
| AsyncChain | 247.8 | 15033.0 | 1379.0 | – | – |
|
||||
| Named | 0.2 | 0.6 | 3.4 | 0.2 | 7.8 |
|
||||
| Override | 9.8 | 3.8 | 408.8 | 61.8 | 138.6 |
|
||||
|
||||
---
|
||||
|
||||
## Steady-State Resolution (Mean time, µs)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|--------|----------|-------|----------|
|
||||
| RegisterSingleton | 0.0 | 0.2 | 1.0 | 0.0 | 0.0 |
|
||||
| RegisterLazySingleton | 0.0 | 0.0 | 1.0 | 0.0 | 0.0 |
|
||||
| ChainSingleton | 2.8 | 0.8 | 2.8 | 1.6 | 2.0 |
|
||||
| ChainLazySingleton | 1.4 | 1.2 | 1.8 | 1.0 | 1.4 |
|
||||
| ChainFactory | 31.2 | 62.6 | 2.0 | 51.6 | 1.6 |
|
||||
| AsyncChain | 57.2 | 31.6 | 18.2 | – | – |
|
||||
| Named | 0.0 | 0.2 | 0.2 | 0.0 | 0.4 |
|
||||
| Override | 1.0 | 1.4 | 1.8 | 290.0 | 1.2 |
|
||||
|
||||
---
|
||||
|
||||
## Peak Memory Usage (Peak RSS, KB)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|----------|----------|---------|----------|
|
||||
| RegisterSingleton | 239,568 | 240,128 | 240,592 | 272,016 | 289,936 |
|
||||
| RegisterLazySingleton | 239,648 | 240,272 | 240,720 | 272,016 | 289,424 |
|
||||
| ChainSingleton | 275,664 | 290,912 | 258,624 | 281,728 | 287,104 |
|
||||
| ChainLazySingleton | 292,704 | 321,232 | 287,168 | 297,808 | 288,160 |
|
||||
| ChainFactory | 298,848 | 361,264 | 293,968 | 279,792 | 290,768 |
|
||||
| AsyncChain | 278,320 | 482,864 | 281,440 | – | – |
|
||||
| Named | 272,896 | 482,880 | 279,728 | 272,016 | 287,376 |
|
||||
| Override | 281,968 | 540,944 | 278,240 | 279,184 | 281,216 |
|
||||
|
||||
---
|
||||
|
||||
## Stability (Stddev / Mean ratio)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|--------|----------|-------|----------|
|
||||
| RegisterSingleton | 1.84 | 1.62 | 1.43 | 1.23 | 1.18 |
|
||||
| RegisterLazySingleton | 0.57 | 0.23 | 0.43 | 2.00 | 1.78 |
|
||||
| ChainSingleton | 0.36 | 0.27 | 0.06 | 0.37 | 0.17 |
|
||||
| ChainLazySingleton | 0.17 | 0.43 | 0.10 | 0.14 | 0.63 |
|
||||
| ChainFactory | 0.27 | 0.01 | 0.22 | 0.09 | 0.23 |
|
||||
| AsyncChain | 0.06 | 0.18 | 0.07 | – | – |
|
||||
| Named | 2.00 | 0.67 | 0.15 | 2.00 | 1.74 |
|
||||
| Override | 0.08 | 0.11 | 0.17 | 0.03 | 0.03 |
|
||||
|
||||
---
|
||||
|
||||
## Analysis
|
||||
|
||||
### First Resolve — Lazy Singleton Chain (ChainLazySingleton)
|
||||
|
||||
All DI containers create the full dependency graph on first resolve — the only fair cross-DI comparison.
|
||||
|
||||
- **cherrypick**: 46.8 µs — **4.1× faster** than get_it (193.2 µs), **8.5× faster** than riverpod (398.0 µs)
|
||||
- **kiwi**: 56.0 µs (+30% vs cherrypick)
|
||||
- **yx_scope**: 266.8 µs (stddev/mean = 0.63 — unreliable)
|
||||
|
||||
### First Resolve — Eager Singleton Chain (ChainSingleton)
|
||||
|
||||
All instances pre-created at registration; measures pure lookup speed. Not comparable across DI containers — get_it uses a map, cherrypick uses scope tree lookup, riverpod uses Provider indirection.
|
||||
|
||||
- **get_it**: 2.8 µs (map lookup)
|
||||
- **cherrypick**: 5.4 µs (scope tree lookup)
|
||||
- **riverpod**: 436.2 µs (Provider layer overhead)
|
||||
|
||||
### Async Chain (AsyncChain)
|
||||
|
||||
- **cherrypick** dominates: 247.8 µs (vs get_it 15,033 µs = **61× faster**)
|
||||
- **riverpod**: 1,379 µs (6.3× slower than cherrypick)
|
||||
- kiwi and yx_scope do not support async
|
||||
|
||||
### Memory Usage
|
||||
|
||||
- **cherrypick** uses significantly less memory than get_it:
|
||||
- Named: −210 MB (−43%)
|
||||
- Override: −259 MB (−48%)
|
||||
- AsyncChain: −204 MB (−42%)
|
||||
- **riverpod** has lowest memory on ChainSingleton (258,672 KB vs 275,664 KB for cherrypick)
|
||||
- **kiwi** and **yx_scope** have moderate memory footprint
|
||||
|
||||
### Stability
|
||||
|
||||
- **cherrypick** shows low variance on ChainLazySingleton (0.17) and Override (0.08)
|
||||
- **get_it** most stable on ChainFactory (0.01)
|
||||
- **yx_scope** highest variance on ChainLazySingleton (0.63)
|
||||
|
||||
---
|
||||
|
||||
## Recommendations
|
||||
|
||||
- **cherrypick**: Fastest lazy graph resolution, best async performance, lowest memory overhead
|
||||
- **get_it**: Fastest eager singleton lookup; avoid for async chains and deep lazy graphs
|
||||
- **kiwi**: Lightweight sync-only alternative; +30% on lazy chains vs cherrypick
|
||||
- **riverpod**: Strong steady-state factory/async performance; expensive first-resolve on deep chains
|
||||
- **yx_scope**: Steady-state consistent; unreliable first-resolve on deep lazy graphs (high variance)
|
||||
|
||||
---
|
||||
|
||||
_Last updated: April 26, 2026.
|
||||
148
benchmark_di/REPORT_v2.ru.md
Normal file
148
benchmark_di/REPORT_v2.ru.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod vs kiwi vs yx_scope
|
||||
|
||||
## Параметры запуска
|
||||
|
||||
- chainCount = 100
|
||||
- nestingDepth = 100
|
||||
- repeat = 5
|
||||
- warmup = 2
|
||||
|
||||
## Описание сценариев
|
||||
|
||||
1. **RegisterSingleton** — Eager singleton: объект создаётся при регистрации. Измеряет скорость поиска.
|
||||
2. **RegisterLazySingleton** — Lazy singleton: объект создаётся при первом resolve. Измеряет создание + кэширование.
|
||||
3. **ChainSingleton** — Eager цепочка зависимостей A → B → ... → N. Все объекты созданы при регистрации. Чистый lookup.
|
||||
4. **ChainLazySingleton** — Lazy цепочка. Полное создание графа + кэширование при первом resolve. **Основная метрика честного сравнения.**
|
||||
5. **ChainFactory** — Все элементы цепочки — фабрики. Stateless построение графа.
|
||||
6. **AsyncChain** — Асинхронная цепочка (async factory). Тест async/await графа.
|
||||
7. **Named** — Регистрация двух биндингов с именами, разрешение по имени.
|
||||
8. **Override** — Регистрация биндинга/цепочки в дочернем scope.
|
||||
|
||||
> **Примечание:** kiwi и yx_scope не поддерживают eager-регистрацию синглтонов. Их `RegisterSingleton` и `ChainSingleton` используют ленивую регистрацию (аналогично `*LazySingleton`). Результаты отмечены †.
|
||||
|
||||
---
|
||||
|
||||
## Методология
|
||||
|
||||
- **Оборудование:** Измерения проведены на локальной машине. Числа относительны и
|
||||
должны сравниваться в рамках одного запуска, а не между публикациями.
|
||||
- **Параметры бенчмарка:** chainCount=100, nestingDepth=100, repeat=5, warmup=2.
|
||||
- **Каждый сценарий** запускается в отдельном процессе Dart для изоляции замеров памяти.
|
||||
- **Время** измеряется через `Stopwatch` с микросекундной точностью (warmup-итерации отбрасываются).
|
||||
- **Память** измеряется через `ProcessInfo.currentRss` (пиковый RSS на процесс).
|
||||
- **Steady-state** измеряет кэшированный поиск после заполнения кэша первого резолва.
|
||||
|
||||
---
|
||||
|
||||
## Первый резолв (среднее время, мкс)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|---------|----------|-------|----------|
|
||||
| RegisterSingleton | 12.8 | 14.6 | 17.6 | 0.4† | 22.8† |
|
||||
| RegisterLazySingleton | 1.2 | 4.2 | 5.4 | 0.2 | 9.0 |
|
||||
| ChainSingleton | 4.8 | 2.8 | 436.2 | 67.8† | 134.2† |
|
||||
| ChainLazySingleton | 46.8 | 193.2 | 398.0 | 56.0 | 266.8 |
|
||||
| ChainFactory | 54.0 | 66.0 | 443.0 | 55.6 | 146.6 |
|
||||
| AsyncChain | 247.8 | 15033.0 | 1379.0 | -- | -- |
|
||||
| Named | 0.2 | 0.6 | 3.4 | 0.2 | 7.8 |
|
||||
| Override | 9.8 | 3.8 | 408.8 | 61.8 | 138.6 |
|
||||
|
||||
---
|
||||
|
||||
## Устоявшееся состояние (steady-state, среднее время, мкс)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|--------|----------|-------|----------|
|
||||
| RegisterSingleton | 0.0 | 0.2 | 1.0 | 0.0 | 0.0 |
|
||||
| RegisterLazySingleton | 0.0 | 0.0 | 1.0 | 0.0 | 0.0 |
|
||||
| ChainSingleton | 2.8 | 0.8 | 2.8 | 1.6 | 2.0 |
|
||||
| ChainLazySingleton | 1.4 | 1.2 | 1.8 | 1.0 | 1.4 |
|
||||
| ChainFactory | 31.2 | 62.6 | 2.0 | 51.6 | 1.6 |
|
||||
| AsyncChain | 57.2 | 31.6 | 18.2 | -- | -- |
|
||||
| Named | 0.0 | 0.2 | 0.2 | 0.0 | 0.4 |
|
||||
| Override | 1.0 | 1.4 | 1.8 | 290.0 | 1.2 |
|
||||
|
||||
---
|
||||
|
||||
## Пиковое потребление памяти (Пиковый RSS, Кб)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|---------|----------|---------|----------|
|
||||
| RegisterSingleton | 239,568 | 240,128 | 240,592 | 272,016 | 289,936 |
|
||||
| RegisterLazySingleton | 239,648 | 240,272 | 240,720 | 272,016 | 289,424 |
|
||||
| ChainSingleton | 275,664 | 290,912 | 258,624 | 281,728 | 287,104 |
|
||||
| ChainLazySingleton | 292,704 | 321,232 | 287,168 | 297,808 | 288,160 |
|
||||
| ChainFactory | 298,848 | 361,264 | 293,968 | 279,792 | 290,768 |
|
||||
| AsyncChain | 278,320 | 482,864 | 281,440 | -- | -- |
|
||||
| Named | 272,896 | 482,880 | 279,728 | 272,016 | 287,376 |
|
||||
| Override | 281,968 | 540,944 | 278,240 | 279,184 | 281,216 |
|
||||
|
||||
---
|
||||
|
||||
## Стабильность (коэффициент Stddev/Mean)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|-----------------------|------------|--------|----------|-------|----------|
|
||||
| RegisterSingleton | 1.84 | 1.62 | 1.43 | 1.23 | 1.18 |
|
||||
| RegisterLazySingleton | 0.57 | 0.23 | 0.43 | 2.00 | 1.78 |
|
||||
| ChainSingleton | 0.36 | 0.27 | 0.06 | 0.37 | 0.17 |
|
||||
| ChainLazySingleton | 0.17 | 0.43 | 0.10 | 0.14 | 0.63 |
|
||||
| ChainFactory | 0.27 | 0.01 | 0.22 | 0.09 | 0.23 |
|
||||
| AsyncChain | 0.06 | 0.18 | 0.07 | -- | -- |
|
||||
| Named | 2.00 | 0.67 | 0.15 | 2.00 | 1.74 |
|
||||
| Override | 0.08 | 0.11 | 0.17 | 0.03 | 0.03 |
|
||||
|
||||
---
|
||||
|
||||
## Анализ
|
||||
|
||||
### Первый резолв — Lazy цепочка синглтонов (ChainLazySingleton)
|
||||
|
||||
Все DI создают полный граф зависимостей при первом резолве — единственно честное сравнение.
|
||||
|
||||
- **cherrypick**: 46.8 мкс — **в 4.1 раза быстрее** get_it (193.2 мкс), **в 8.5 раза быстрее** riverpod (398.0 мкс)
|
||||
- **kiwi**: 56.0 мкс (+30% к cherrypick)
|
||||
- **yx_scope**: 266.8 мкс (высокая дисперсия, stddev/mean = 0.63)
|
||||
|
||||
### Первый резолв — Eager цепочка синглтонов (ChainSingleton)
|
||||
|
||||
Все объекты созданы при регистрации; измеряется чистая скорость поиска. Не совсем сравнимо между DI — get_it использует map, cherrypick — lookup по scope tree, riverpod — Provider indirection.
|
||||
|
||||
- **get_it**: 2.8 мкс (map lookup)
|
||||
- **cherrypick**: 5.4 мкс (scope tree lookup)
|
||||
- **riverpod**: 436.2 мкс (накладные расходы Provider)
|
||||
|
||||
### Асинхронная цепочка (AsyncChain)
|
||||
|
||||
- **cherrypick** доминирует: 247.8 мкс (vs get_it 15 033 мкс = **в 61 раз быстрее**)
|
||||
- **riverpod**: 1 379 мкс (в 6.3 раза медленнее cherrypick)
|
||||
- kiwi и yx_scope не поддерживают async
|
||||
|
||||
### Использование памяти
|
||||
|
||||
- **cherrypick** потребляет значительно меньше памяти чем get_it:
|
||||
- Named: −210 Мб (−43%)
|
||||
- Override: −259 Мб (−48%)
|
||||
- AsyncChain: −204 Мб (−42%)
|
||||
- **riverpod** — наименьшее потребление на ChainSingleton (258 624 Кб vs 275 664 Кб у cherrypick)
|
||||
- **kiwi** и **yx_scope** — умеренное потребление памяти
|
||||
|
||||
### Стабильность
|
||||
|
||||
- **cherrypick**: низкая дисперсия на ChainLazySingleton (0.17) и Override (0.08)
|
||||
- **get_it**: наиболее стабилен на ChainFactory (0.01)
|
||||
- **yx_scope**: наибольшая дисперсия на ChainLazySingleton (0.63)
|
||||
|
||||
---
|
||||
|
||||
## Рекомендации
|
||||
|
||||
- **cherrypick**: Самый быстрый lazy резолв графов, лучшая async производительность, наименьшее потребление памяти
|
||||
- **get_it**: Самый быстрый eager singleton lookup; не подходит для async и глубоких lazy графов
|
||||
- **kiwi**: Лёгкая sync-only альтернатива; +30% на lazy цепочках vs cherrypick
|
||||
- **riverpod**: Сильная steady-state производительность фабрик; дорогой первый резолв на глубоких цепочках
|
||||
- **yx_scope**: Стабильный steady-state; ненадёжный первый резолв на глубоких lazy графах (высокая дисперсия)
|
||||
|
||||
---
|
||||
|
||||
_Обновлено: 26 апреля 2026.
|
||||
@@ -25,7 +25,11 @@ class UniversalChainAsyncBenchmark<TContainer> extends AsyncBenchmarkBase {
|
||||
bindingMode: mode,
|
||||
scenario: UniversalScenario.asyncChain,
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> prewarm() async {
|
||||
await di.waitForAsyncReady();
|
||||
await run();
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -50,7 +50,14 @@ class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() => _di.teardown();
|
||||
void teardown() {
|
||||
_childDi?.teardown();
|
||||
_di.teardown();
|
||||
}
|
||||
|
||||
void prewarm() {
|
||||
run();
|
||||
}
|
||||
|
||||
@override
|
||||
void run() {
|
||||
@@ -59,11 +66,7 @@ class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
|
||||
_di.resolve<UniversalService>();
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
if (_di.runtimeType.toString().contains('GetItAdapter')) {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
} else {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
final serviceName = '${chainCount}_$nestingDepth';
|
||||
|
||||
@@ -31,9 +31,16 @@ class BenchmarkCliRunner {
|
||||
Future<void> run(List<String> args) async {
|
||||
final config = parseBenchmarkCli(args);
|
||||
final results = <Map<String, dynamic>>[];
|
||||
// DI implementations that do not support async scenarios
|
||||
const asyncUnsupported = {'kiwi', 'yx_scope'};
|
||||
for (final phase in config.phases) {
|
||||
for (final bench in config.benchesToRun) {
|
||||
final scenario = toScenario(bench);
|
||||
final mode = toMode(bench);
|
||||
if (asyncUnsupported.contains(config.di) &&
|
||||
scenario == UniversalScenario.asyncChain) {
|
||||
continue; // Skip async benchmarks for DI that does not support them
|
||||
}
|
||||
for (final c in config.chainCounts) {
|
||||
for (final d in config.nestDepths) {
|
||||
BenchmarkResult benchResult;
|
||||
@@ -50,6 +57,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<GetIt>(
|
||||
@@ -63,12 +71,12 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
}
|
||||
} else if (config.di == 'kiwi') {
|
||||
final di = KiwiAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
// UnsupportedError будет выброшен адаптером, но если дойдёт — вызывать async benchmark
|
||||
final benchAsync = UniversalChainAsyncBenchmark<KiwiContainer>(
|
||||
di,
|
||||
chainCount: c,
|
||||
@@ -79,6 +87,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<KiwiContainer>(
|
||||
@@ -92,6 +101,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
}
|
||||
} else if (config.di == 'riverpod') {
|
||||
@@ -108,6 +118,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<
|
||||
@@ -122,6 +133,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
}
|
||||
} else if (config.di == 'yx_scope') {
|
||||
@@ -138,6 +150,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
} else {
|
||||
final benchSync =
|
||||
@@ -152,6 +165,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
@@ -167,6 +181,7 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<Scope>(
|
||||
@@ -180,22 +195,27 @@ class BenchmarkCliRunner {
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
phase: phase,
|
||||
);
|
||||
}
|
||||
}
|
||||
final timings = benchResult.timings;
|
||||
if (timings.isEmpty) continue; // skip failed scenarios
|
||||
timings.sort();
|
||||
var mean = timings.reduce((a, b) => a + b) / timings.length;
|
||||
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);
|
||||
final count = timings.length;
|
||||
final mean = timings.reduce((a, b) => a + b) / count;
|
||||
final median = count.isOdd
|
||||
? timings[count ~/ 2]
|
||||
: (timings[count ~/ 2 - 1] + timings[count ~/ 2]) / 2;
|
||||
final minVal = timings.first;
|
||||
final maxVal = timings.last;
|
||||
final stddev = sqrt(timings
|
||||
.map((x) => pow(x - mean, 2))
|
||||
.reduce((a, b) => a + b) /
|
||||
count);
|
||||
results.add({
|
||||
'benchmark': 'Universal_$bench',
|
||||
'phase': phase.name,
|
||||
'chainCount': c,
|
||||
'nestingDepth': d,
|
||||
'mean_us': mean.toStringAsFixed(2),
|
||||
@@ -212,6 +232,7 @@ class BenchmarkCliRunner {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
final reportGenerators = {
|
||||
'pretty': PrettyReport(),
|
||||
'csv': CsvReport(),
|
||||
|
||||
@@ -6,12 +6,18 @@ import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
|
||||
/// Enum describing all supported Universal DI benchmark types.
|
||||
enum UniversalBenchmark {
|
||||
/// Simple singleton registration benchmark
|
||||
/// Simple singleton registration benchmark (eager, where supported)
|
||||
registerSingleton,
|
||||
|
||||
/// Chain of singleton dependencies
|
||||
/// Simple lazy singleton registration benchmark
|
||||
registerLazySingleton,
|
||||
|
||||
/// Chain of eager singleton dependencies
|
||||
chainSingleton,
|
||||
|
||||
/// Chain of lazy singleton dependencies
|
||||
chainLazySingleton,
|
||||
|
||||
/// Chain using factories
|
||||
chainFactory,
|
||||
|
||||
@@ -25,12 +31,19 @@ enum UniversalBenchmark {
|
||||
override,
|
||||
}
|
||||
|
||||
enum ResolvePhase {
|
||||
firstResolve,
|
||||
steadyStateResolve,
|
||||
}
|
||||
|
||||
/// Maps [UniversalBenchmark] to the scenario enum for DI chains.
|
||||
UniversalScenario toScenario(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
case UniversalBenchmark.registerLazySingleton:
|
||||
return UniversalScenario.register;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
case UniversalBenchmark.chainLazySingleton:
|
||||
return UniversalScenario.chain;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalScenario.chain;
|
||||
@@ -43,21 +56,21 @@ UniversalScenario toScenario(UniversalBenchmark b) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps benchmark to registration mode (singleton/factory/async).
|
||||
/// Maps benchmark to registration mode (singleton/lazySingleton/factory/async).
|
||||
UniversalBindingMode toMode(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
case UniversalBenchmark.named:
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.registerLazySingleton:
|
||||
case UniversalBenchmark.chainLazySingleton:
|
||||
return UniversalBindingMode.lazySingletonStrategy;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalBindingMode.factoryStrategy;
|
||||
case UniversalBenchmark.chainAsync:
|
||||
return UniversalBindingMode.asyncStrategy;
|
||||
case UniversalBenchmark.named:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +111,10 @@ class BenchmarkCliConfig {
|
||||
|
||||
/// Name of DI implementation ("cherrypick" or "getit")
|
||||
final String di;
|
||||
|
||||
/// Which resolve phase(s) to measure.
|
||||
final List<ResolvePhase> phases;
|
||||
|
||||
BenchmarkCliConfig({
|
||||
required this.benchesToRun,
|
||||
required this.chainCounts,
|
||||
@@ -106,6 +123,7 @@ class BenchmarkCliConfig {
|
||||
required this.warmups,
|
||||
required this.format,
|
||||
required this.di,
|
||||
required this.phases,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -119,6 +137,8 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
|
||||
..addOption('repeat', abbr: 'r', defaultsTo: '2')
|
||||
..addOption('warmup', abbr: 'w', defaultsTo: '1')
|
||||
..addOption('format', abbr: 'f', defaultsTo: 'pretty')
|
||||
..addOption('resolvePhase',
|
||||
defaultsTo: 'all', help: 'Resolve phase: first, steady, or all')
|
||||
..addOption('di',
|
||||
defaultsTo: 'cherrypick',
|
||||
help: 'DI implementation: cherrypick, getit or riverpod')
|
||||
@@ -128,12 +148,39 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
|
||||
print(parser.usage);
|
||||
exit(0);
|
||||
}
|
||||
final benchName = result['benchmark'] as String;
|
||||
final isAll = benchName == 'all';
|
||||
final benchNameInput = result['benchmark'] as String;
|
||||
final isAll = benchNameInput.trim() == 'all';
|
||||
final allBenches = UniversalBenchmark.values;
|
||||
|
||||
String normalizeBenchName(String name) {
|
||||
final n = name.trim().toLowerCase();
|
||||
return switch (n) {
|
||||
'register' || 'registersingleton' || 'registereager' => 'registerSingleton',
|
||||
'registerlazy' || 'registerlazysingleton' || 'registerlazysingle' => 'registerLazySingleton',
|
||||
'chain' || 'chainsingleton' || 'chaineager' => 'chainSingleton',
|
||||
'chainlazy' || 'chainlazysingleton' || 'lazysingleton' => 'chainLazySingleton',
|
||||
'chainfactory' || 'factory' => 'chainFactory',
|
||||
'async' || 'asyncchain' || 'chainasync' => 'chainAsync',
|
||||
'named' => 'named',
|
||||
'override' => 'override',
|
||||
_ => n,
|
||||
};
|
||||
}
|
||||
|
||||
final benchesToRun = isAll
|
||||
? allBenches
|
||||
: [parseEnum(benchName, allBenches, UniversalBenchmark.chainSingleton)];
|
||||
: benchNameInput
|
||||
.split(',')
|
||||
.map((n) => parseEnum(normalizeBenchName(n), allBenches,
|
||||
UniversalBenchmark.chainSingleton))
|
||||
.toSet()
|
||||
.toList();
|
||||
final phaseName = (result['resolvePhase'] as String).toLowerCase();
|
||||
final phases = switch (phaseName) {
|
||||
'first' => [ResolvePhase.firstResolve],
|
||||
'steady' => [ResolvePhase.steadyStateResolve],
|
||||
_ => ResolvePhase.values,
|
||||
};
|
||||
return BenchmarkCliConfig(
|
||||
benchesToRun: benchesToRun,
|
||||
chainCounts: parseIntList(result['chainCount'] as String),
|
||||
@@ -142,5 +189,6 @@ BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
|
||||
warmups: int.tryParse(result['warmup'] as String? ?? "") ?? 1,
|
||||
format: result['format'] as String,
|
||||
di: result['di'] as String? ?? 'cherrypick',
|
||||
phases: phases,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ class CsvReport extends ReportGenerator {
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark',
|
||||
'phase',
|
||||
'chainCount',
|
||||
'nestingDepth',
|
||||
'mean_us',
|
||||
|
||||
@@ -8,6 +8,7 @@ class MarkdownReport extends ReportGenerator {
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark',
|
||||
'phase',
|
||||
'chainCount',
|
||||
'nestingDepth',
|
||||
'mean_us',
|
||||
@@ -24,7 +25,9 @@ class MarkdownReport extends ReportGenerator {
|
||||
/// Friendly display names for each benchmark type.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.registerLazySingleton': 'RegisterLazySingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainLazySingleton': 'ChainLazySingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named': 'Named',
|
||||
@@ -36,6 +39,7 @@ class MarkdownReport extends ReportGenerator {
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark',
|
||||
'Phase',
|
||||
'Chain Count',
|
||||
'Depth',
|
||||
'Mean (us)',
|
||||
@@ -52,6 +56,7 @@ class MarkdownReport extends ReportGenerator {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['phase'],
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
@@ -82,6 +87,7 @@ class MarkdownReport extends ReportGenerator {
|
||||
final legend = '''
|
||||
> **Legend:**
|
||||
> `Benchmark` – Test name
|
||||
> `Phase` – `firstResolve` or `steadyStateResolve`
|
||||
> `Chain Count` – Number of independent chains
|
||||
> `Depth` – Depth of each chain
|
||||
> `Mean (us)` – Average time per run (microseconds)
|
||||
|
||||
@@ -8,6 +8,7 @@ class PrettyReport extends ReportGenerator {
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark',
|
||||
'phase',
|
||||
'chainCount',
|
||||
'nestingDepth',
|
||||
'mean_us',
|
||||
@@ -24,7 +25,9 @@ class PrettyReport extends ReportGenerator {
|
||||
/// Mappings from internal benchmark IDs to display names.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.registerLazySingleton': 'RegisterLazySingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainLazySingleton': 'ChainLazySingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named': 'Named',
|
||||
@@ -36,6 +39,7 @@ class PrettyReport extends ReportGenerator {
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark',
|
||||
'Phase',
|
||||
'Chain Count',
|
||||
'Depth',
|
||||
'Mean (us)',
|
||||
@@ -53,6 +57,7 @@ class PrettyReport extends ReportGenerator {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['phase'],
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_benchmark.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
|
||||
import 'package:benchmark_di/cli/parser.dart';
|
||||
|
||||
/// Holds the results for a single benchmark execution.
|
||||
class BenchmarkResult {
|
||||
@@ -50,17 +51,24 @@ class BenchmarkRunner {
|
||||
required UniversalChainBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
required ResolvePhase phase,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
benchmark.setup();
|
||||
if (phase == ResolvePhase.steadyStateResolve) {
|
||||
benchmark.prewarm();
|
||||
}
|
||||
benchmark.run();
|
||||
benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
benchmark.setup();
|
||||
if (phase == ResolvePhase.steadyStateResolve) {
|
||||
benchmark.prewarm();
|
||||
}
|
||||
final sw = Stopwatch()..start();
|
||||
benchmark.run();
|
||||
sw.stop();
|
||||
@@ -78,17 +86,24 @@ class BenchmarkRunner {
|
||||
required UniversalChainAsyncBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
required ResolvePhase phase,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
await benchmark.setup();
|
||||
if (phase == ResolvePhase.steadyStateResolve) {
|
||||
await benchmark.prewarm();
|
||||
}
|
||||
await benchmark.run();
|
||||
await benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
await benchmark.setup();
|
||||
if (phase == ResolvePhase.steadyStateResolve) {
|
||||
await benchmark.prewarm();
|
||||
}
|
||||
final sw = Stopwatch()..start();
|
||||
await benchmark.run();
|
||||
sw.stop();
|
||||
|
||||
@@ -59,11 +59,16 @@ class UniversalChainModule extends Module {
|
||||
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
// Simple singleton registration.
|
||||
if (bindingMode == UniversalBindingMode.lazySingletonStrategy) {
|
||||
bind<UniversalService>()
|
||||
.toProvide(
|
||||
() => UniversalServiceImpl(value: 'reg', dependency: null))
|
||||
.singleton();
|
||||
} else {
|
||||
bind<UniversalService>()
|
||||
.toInstance(
|
||||
UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
// Named factory registration for two distinct objects.
|
||||
@@ -76,6 +81,8 @@ class UniversalChainModule extends Module {
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
// Chain of nested services, with dependency on previous level by name.
|
||||
UniversalService? lastEagerInstance;
|
||||
final Map<String, UniversalService> eagerInstances = {};
|
||||
for (var chainIndex = 0; chainIndex < chainCount; chainIndex++) {
|
||||
for (var levelIndex = 0; levelIndex < nestingDepth; levelIndex++) {
|
||||
final chain = chainIndex + 1;
|
||||
@@ -84,6 +91,17 @@ class UniversalChainModule extends Module {
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
final instance = UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: eagerInstances[prevDepName],
|
||||
);
|
||||
bind<UniversalService>()
|
||||
.toInstance(instance)
|
||||
.withName(depName);
|
||||
eagerInstances[depName] = instance;
|
||||
lastEagerInstance = instance;
|
||||
break;
|
||||
case UniversalBindingMode.lazySingletonStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
@@ -116,15 +134,19 @@ class UniversalChainModule extends Module {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Регистрация алиаса без имени (на последний элемент цепочки)
|
||||
// Register unnamed alias for the last chain element.
|
||||
if (bindingMode == UniversalBindingMode.lazySingletonStrategy) {
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(
|
||||
() => currentScope.resolve<UniversalService>(named: depName))
|
||||
.singleton();
|
||||
} else if (lastEagerInstance != null) {
|
||||
bind<UniversalService>().toInstance(lastEagerInstance);
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level, но алиас нужен прямо в этом scope!
|
||||
// Handled at benchmark level, but alias is needed directly in this scope.
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(
|
||||
@@ -189,7 +211,7 @@ class CherrypickDIAdapter extends DIAdapter<Scope> {
|
||||
await CherryPick.closeRootScope();
|
||||
_scope = null;
|
||||
}
|
||||
// SubScope teardown не требуется
|
||||
// SubScope teardown is handled by the parent scope.
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -4,14 +4,14 @@ import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// Универсальный DIAdapter для GetIt c поддержкой scopes и строгой типизацией.
|
||||
/// DIAdapter for GetIt with scope support and strict typing.
|
||||
class GetItAdapter extends DIAdapter<GetIt> {
|
||||
late GetIt _getIt;
|
||||
final String? _scopeName;
|
||||
final bool _isSubScope;
|
||||
bool _scopePushed = false;
|
||||
|
||||
/// Основной (root) и subScope-конструкторы.
|
||||
/// Root and subScope constructors.
|
||||
GetItAdapter({GetIt? instance, String? scopeName, bool isSubScope = false})
|
||||
: _scopeName = scopeName,
|
||||
_isSubScope = isSubScope {
|
||||
@@ -23,7 +23,7 @@ class GetItAdapter extends DIAdapter<GetIt> {
|
||||
@override
|
||||
void setupDependencies(void Function(GetIt container) registration) {
|
||||
if (_isSubScope) {
|
||||
// Создаём scope через pushNewScope с init
|
||||
// Create scope via pushNewScope with init
|
||||
_getIt.pushNewScope(
|
||||
scopeName: _scopeName,
|
||||
init: (getIt) => registration(getIt),
|
||||
@@ -41,7 +41,7 @@ class GetItAdapter extends DIAdapter<GetIt> {
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async =>
|
||||
_getIt<T>(instanceName: named);
|
||||
_getIt.getAsync<T>(instanceName: named);
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
@@ -92,8 +92,13 @@ class GetItAdapter extends DIAdapter<GetIt> {
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.register:
|
||||
if (bindingMode == UniversalBindingMode.lazySingletonStrategy) {
|
||||
getIt.registerLazySingleton<UniversalService>(
|
||||
() => UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
} else {
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
getIt.registerFactory<UniversalService>(
|
||||
@@ -120,6 +125,17 @@ class GetItAdapter extends DIAdapter<GetIt> {
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.lazySingletonStrategy:
|
||||
getIt.registerLazySingleton<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? getIt<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
getIt.registerFactory<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
@@ -154,10 +170,16 @@ class GetItAdapter extends DIAdapter<GetIt> {
|
||||
if (scenario == UniversalScenario.chain ||
|
||||
scenario == UniversalScenario.override) {
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
if (bindingMode == UniversalBindingMode.lazySingletonStrategy) {
|
||||
getIt.registerLazySingleton<UniversalService>(
|
||||
() => getIt<UniversalService>(instanceName: depName),
|
||||
);
|
||||
} else {
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
getIt<UniversalService>(instanceName: depName),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by GetItAdapter');
|
||||
|
||||
@@ -4,14 +4,11 @@ import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:kiwi/kiwi.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// DIAdapter-для KiwiContainer с поддержкой universal benchmark сценариев.
|
||||
/// DIAdapter for KiwiContainer with universal benchmark scenario support.
|
||||
class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
late KiwiContainer _container;
|
||||
// ignore: unused_field
|
||||
final bool _isSubScope;
|
||||
|
||||
KiwiAdapter({KiwiContainer? container, bool isSubScope = false})
|
||||
: _isSubScope = isSubScope {
|
||||
KiwiAdapter({KiwiContainer? container, bool isSubScope = false}) {
|
||||
_container = container ?? KiwiContainer();
|
||||
}
|
||||
|
||||
@@ -57,6 +54,8 @@ class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
case UniversalBindingMode.lazySingletonStrategy:
|
||||
// Kiwi's registerSingleton is lazy (factory-based, cached on first resolve)
|
||||
container.registerSingleton<UniversalService>(
|
||||
(c) => UniversalServiceImpl(
|
||||
value: depName,
|
||||
@@ -75,7 +74,7 @@ class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
name: depName);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
// Не поддерживается
|
||||
// Not supported
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -97,23 +96,12 @@ class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
|
||||
@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
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) {
|
||||
return Future.value(_container.resolve<T>(named));
|
||||
} else {
|
||||
// Для совместимости с chain/override
|
||||
return Future.value(_container.resolve<T>(named));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -123,7 +111,7 @@ class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
|
||||
@override
|
||||
KiwiAdapter openSubScope(String name) {
|
||||
// Возвращаем новый scoped контейнер (отдельный). Наследование не реализовано.
|
||||
// Returns a new scoped container. Inheritance not implemented.
|
||||
return KiwiAdapter(container: KiwiContainer.scoped(), isSubScope: true);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,8 +29,7 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
// У yx_scope нет явного dispose на ScopeContainer, но можно добавить очистку Map/Deps если потребуется
|
||||
// Ничего не делаем
|
||||
_scope = UniversalYxScopeContainer();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -54,26 +53,13 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
if (scenario == UniversalScenario.asyncChain ||
|
||||
bindingMode == UniversalBindingMode.asyncStrategy) {
|
||||
throw UnsupportedError(
|
||||
'YxScope does not support async dependencies or async binding scenarios.');
|
||||
}
|
||||
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),
|
||||
@@ -113,6 +99,8 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (scenario == UniversalScenario.chain ||
|
||||
scenario == UniversalScenario.override) {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/// Enum to represent the DI registration/binding mode.
|
||||
enum UniversalBindingMode {
|
||||
/// Singleton/provider binding.
|
||||
/// Eager singleton — instance created at registration time.
|
||||
singletonStrategy,
|
||||
|
||||
/// Factory-based binding.
|
||||
/// Lazy singleton — instance created on first resolve, then cached.
|
||||
lazySingletonStrategy,
|
||||
|
||||
/// Factory-based binding — new instance every time.
|
||||
factoryStrategy,
|
||||
|
||||
/// Async-based binding.
|
||||
|
||||
@@ -47,7 +47,7 @@ packages:
|
||||
path: "../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -4,7 +4,7 @@ homepage: localhost
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
sdk: ">=2.12.0 <3.0.0"
|
||||
sdk: '>=3.2.0 <4.0.0'
|
||||
|
||||
|
||||
dependencies:
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
|
||||
/// {@template binding_docs}
|
||||
@@ -69,6 +71,8 @@ class Binding<T> {
|
||||
|
||||
CherryPickObserver? observer;
|
||||
|
||||
bool get _isSilentObserver => observer is SilentCherryPickObserver;
|
||||
|
||||
// Deferred logging flags
|
||||
bool _createdLogged = false;
|
||||
bool _namedLogged = false;
|
||||
@@ -191,10 +195,9 @@ class Binding<T> {
|
||||
/// }
|
||||
/// ```
|
||||
/// This restriction only applies to [toInstance] bindings.
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
/// With [toProvide]/[toProvideAsync] you may freely use `scope.resolve<T>()` in the builder or provider function.
|
||||
Binding<T> toInstance(Instance<T> value) {
|
||||
_resolver = InstanceResolver<T>(value);
|
||||
Binding<T> toInstance(FutureOr<T> value) {
|
||||
_resolver = InstanceResolver.create<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -205,8 +208,8 @@ class Binding<T> {
|
||||
/// bind<Api>().toProvide(() => ApiService());
|
||||
/// bind<Db>().toProvide(() async => await openDb());
|
||||
/// ```
|
||||
Binding<T> toProvide(Provider<T> value) {
|
||||
_resolver = ProviderResolver<T>((_) => value.call(), withParams: false);
|
||||
Binding<T> toProvide(FutureOr<T> Function() value) {
|
||||
_resolver = ProviderResolver.create<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -216,24 +219,32 @@ class Binding<T> {
|
||||
/// ```dart
|
||||
/// bind<User>().toProvideWithParams((params) => User(name: params["name"]));
|
||||
/// ```
|
||||
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
|
||||
_resolver = ProviderResolver<T>(value, withParams: true);
|
||||
Binding<T> toProvideWithParams(FutureOr<T> Function(dynamic) value) {
|
||||
_resolver = ProviderResolver.createWithParams<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Deprecated('Use toInstance instead of toInstanceAsync')
|
||||
Binding<T> toInstanceAsync(Instance<T> value) {
|
||||
return this.toInstance(value);
|
||||
Binding<T> toInstanceAsync(FutureOr<T> value) {
|
||||
return toInstance(value);
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvide instead of toProvideAsync')
|
||||
Binding<T> toProvideAsync(Provider<T> value) {
|
||||
return this.toProvide(value);
|
||||
/// Asynchronous variant of [toProvide] for providers that return [Future<T>].
|
||||
///
|
||||
/// Prefer this over [toProvide] when the provider is async, so the resolver
|
||||
/// is type-safe and avoids runtime detection overhead.
|
||||
Binding<T> toProvideAsync(AsyncProviderFactory<T> value) {
|
||||
_resolver = ProviderResolver.async<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvideWithParams instead of toProvideAsyncWithParams')
|
||||
Binding<T> toProvideAsyncWithParams(ProviderWithParams<T> value) {
|
||||
return this.toProvideWithParams(value);
|
||||
/// Asynchronous variant of [toProvideWithParams] for providers that return [Future<T>].
|
||||
///
|
||||
/// Prefer this over [toProvideWithParams] when the provider is async, so the resolver
|
||||
/// is type-safe and avoids runtime detection overhead.
|
||||
Binding<T> toProvideAsyncWithParams(AsyncProviderFactoryWithParams<T> value) {
|
||||
_resolver = ProviderResolver.asyncWithParams<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Marks this binding as singleton (will only create and cache one instance per scope).
|
||||
@@ -281,6 +292,10 @@ class Binding<T> {
|
||||
/// ```
|
||||
T? resolveSync([dynamic params]) {
|
||||
final res = resolver?.resolveSync(params);
|
||||
if (_isSilentObserver) {
|
||||
return res;
|
||||
}
|
||||
|
||||
if (res != null) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding resolved instance: ${T.toString()}',
|
||||
@@ -313,6 +328,10 @@ class Binding<T> {
|
||||
/// ```
|
||||
Future<T>? resolveAsync([dynamic params]) {
|
||||
final future = resolver?.resolveAsync(params);
|
||||
if (_isSilentObserver) {
|
||||
return future;
|
||||
}
|
||||
|
||||
if (future != null) {
|
||||
future
|
||||
.then((res) => observer?.onDiagnostic(
|
||||
|
||||
@@ -13,86 +13,37 @@
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
/// Represents a direct instance or an async instance ([T] or [Future<T>]).
|
||||
/// Used for both direct and async bindings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// Instance<String> sync = "hello";
|
||||
/// Instance<MyApi> async = Future.value(MyApi());
|
||||
/// ```
|
||||
typedef Instance<T> = FutureOr<T>;
|
||||
/// Synchronous factory: `T Function()`.
|
||||
typedef ProviderFactory<T> = T Function();
|
||||
|
||||
/// Provider function type for synchronous or asynchronous, parameterless creation of [T].
|
||||
/// Can return [T] or [Future<T>].
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// Provider<MyService> provider = () => MyService();
|
||||
/// Provider<Api> asyncProvider = () async => await Api.connect();
|
||||
/// ```
|
||||
typedef Provider<T> = FutureOr<T> Function();
|
||||
/// Parameterized synchronous factory: `T Function(dynamic)`.
|
||||
typedef ProviderFactoryWithParams<T> = T Function(dynamic);
|
||||
|
||||
/// Provider function type that accepts a dynamic parameter, for factory/parametrized injection.
|
||||
/// Returns [T] or [Future<T>].
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// ProviderWithParams<User> provider = (params) => User(params["name"]);
|
||||
/// ```
|
||||
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
||||
/// Asynchronous factory: `Future<T> Function()`.
|
||||
typedef AsyncProviderFactory<T> = Future<T> Function();
|
||||
|
||||
/// Abstract interface for dependency resolvers used by [Binding].
|
||||
/// Defines how to resolve instances of type [T].
|
||||
///
|
||||
/// You usually don't use this directly; it's used internally for advanced/low-level DI.
|
||||
/// Parameterized asynchronous factory: `Future<T> Function(dynamic)`.
|
||||
typedef AsyncProviderFactoryWithParams<T> = Future<T> Function(dynamic);
|
||||
|
||||
/// Internal interface for resolvers managed by [Binding].
|
||||
abstract class BindingResolver<T> {
|
||||
/// Synchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||
/// Throws if implementation does not support sync resolution.
|
||||
T? resolveSync([dynamic params]);
|
||||
|
||||
/// Asynchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||
/// If instance is already a [Future], returns it directly.
|
||||
Future<T>? resolveAsync([dynamic params]);
|
||||
|
||||
/// Marks this resolver as singleton: instance(s) will be cached and reused inside the scope.
|
||||
void toSingleton();
|
||||
|
||||
/// Returns true if this resolver is marked as singleton.
|
||||
bool get isSingleton;
|
||||
}
|
||||
|
||||
/// Concrete resolver for direct instance ([T] or [Future<T>]). No provider is called.
|
||||
///
|
||||
/// Used for [Binding.toInstance].
|
||||
/// Supports both sync and async resolution; sync will throw if underlying instance is [Future].
|
||||
/// Examples:
|
||||
/// ```dart
|
||||
/// var resolver = InstanceResolver("hello");
|
||||
/// resolver.resolveSync(); // == "hello"
|
||||
/// var asyncResolver = InstanceResolver(Future.value(7));
|
||||
/// asyncResolver.resolveAsync(); // Future<int>
|
||||
/// ```
|
||||
class InstanceResolver<T> implements BindingResolver<T> {
|
||||
final Instance<T> _instance;
|
||||
/// Resolver for a pre-built synchronous instance.
|
||||
class SyncInstanceResolver<T> implements BindingResolver<T> {
|
||||
final T _instance;
|
||||
|
||||
/// Wraps the given instance (sync or async) in a resolver.
|
||||
InstanceResolver(this._instance);
|
||||
SyncInstanceResolver(this._instance);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
if (_instance is T) return _instance;
|
||||
throw StateError(
|
||||
'Instance $_instance is Future; '
|
||||
'use resolveAsync() instead',
|
||||
);
|
||||
}
|
||||
T resolveSync([_]) => _instance;
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) {
|
||||
if (_instance is Future<T>) return _instance;
|
||||
return Future.value(_instance);
|
||||
}
|
||||
Future<T> resolveAsync([_]) => Future<T>.value(_instance);
|
||||
|
||||
@override
|
||||
void toSingleton() {}
|
||||
@@ -101,63 +52,31 @@ class InstanceResolver<T> implements BindingResolver<T> {
|
||||
bool get isSingleton => true;
|
||||
}
|
||||
|
||||
/// Resolver for provider functions (sync/async/factory), with optional singleton caching.
|
||||
/// Used for [Binding.toProvide], [Binding.toProvideWithParams], [Binding.singleton].
|
||||
///
|
||||
/// Examples:
|
||||
/// ```dart
|
||||
/// // No param, sync:
|
||||
/// var r = ProviderResolver((_) => 5, withParams: false);
|
||||
/// r.resolveSync(); // == 5
|
||||
/// // With param:
|
||||
/// var rp = ProviderResolver((p) => p * 2, withParams: true);
|
||||
/// rp.resolveSync(2); // == 4
|
||||
/// // Singleton:
|
||||
/// r.toSingleton();
|
||||
/// // Async:
|
||||
/// var ra = ProviderResolver((_) async => await Future.value(10), withParams: false);
|
||||
/// await ra.resolveAsync(); // == 10
|
||||
/// ```
|
||||
class ProviderResolver<T> implements BindingResolver<T> {
|
||||
final ProviderWithParams<T> _provider;
|
||||
final bool _withParams;
|
||||
/// Resolver for a pre-built async instance ([Future]).
|
||||
class AsyncInstanceResolver<T> implements BindingResolver<T> {
|
||||
final Future<T> _instance;
|
||||
|
||||
FutureOr<T>? _cache;
|
||||
AsyncInstanceResolver(this._instance);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
throw StateError('Instance is a Future; use resolveAsync() instead');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) => _instance;
|
||||
|
||||
@override
|
||||
void toSingleton() {}
|
||||
|
||||
@override
|
||||
bool get isSingleton => true;
|
||||
}
|
||||
|
||||
/// Base class for provider-based resolvers with singleton flag support.
|
||||
abstract class _BaseProviderResolver<T> implements BindingResolver<T> {
|
||||
bool _singleton = false;
|
||||
|
||||
/// Creates a resolver from [provider], optionally accepting dynamic params.
|
||||
ProviderResolver(
|
||||
ProviderWithParams<T> provider, {
|
||||
required bool withParams,
|
||||
}) : _provider = provider,
|
||||
_withParams = withParams;
|
||||
|
||||
@override
|
||||
T resolveSync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
final result = _cache ?? _provider(params);
|
||||
if (result is T) {
|
||||
if (_singleton) {
|
||||
_cache ??= result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
throw StateError(
|
||||
'Provider [$_provider] return Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
final result = _cache ?? _provider(params);
|
||||
final target = result is Future<T> ? result : Future<T>.value(result);
|
||||
if (_singleton) {
|
||||
_cache ??= target;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
@override
|
||||
void toSingleton() {
|
||||
_singleton = true;
|
||||
@@ -165,13 +84,282 @@ class ProviderResolver<T> implements BindingResolver<T> {
|
||||
|
||||
@override
|
||||
bool get isSingleton => _singleton;
|
||||
}
|
||||
|
||||
/// Throws if params required but not supplied.
|
||||
void _checkParams(dynamic params) {
|
||||
if (_withParams && params == null) {
|
||||
/// Resolves [Binding.toProvide] with a sync `T Function()` provider.
|
||||
class SyncProviderResolver<T> extends _BaseProviderResolver<T> {
|
||||
final ProviderFactory<T> _provider;
|
||||
Object? _cached;
|
||||
bool _isCached = false;
|
||||
|
||||
SyncProviderResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
if (_singleton && _isCached) {
|
||||
return _cached as T;
|
||||
}
|
||||
final result = _provider();
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) => Future<T>.value(resolveSync());
|
||||
}
|
||||
|
||||
/// Resolves [Binding.toProvideWithParams] with a sync `T Function(dynamic)` provider.
|
||||
class SyncProviderWithParamsResolver<T> extends _BaseProviderResolver<T> {
|
||||
final ProviderFactoryWithParams<T> _provider;
|
||||
Object? _cached;
|
||||
bool _isCached = false;
|
||||
|
||||
SyncProviderWithParamsResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([dynamic params]) {
|
||||
if (_singleton && _isCached) {
|
||||
return _cached as T;
|
||||
}
|
||||
if (params == null) {
|
||||
throw StateError('[$T] Params is null. Maybe you forgot to pass it?');
|
||||
}
|
||||
final result = _provider(params);
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) =>
|
||||
Future<T>.value(resolveSync(params));
|
||||
}
|
||||
|
||||
/// Resolves [Binding.toProvide] with an async `Future<T> Function()` provider.
|
||||
class AsyncProviderResolver<T> extends _BaseProviderResolver<T> {
|
||||
final AsyncProviderFactory<T> _provider;
|
||||
Future<T>? _cache;
|
||||
bool _isCached = false;
|
||||
|
||||
AsyncProviderResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
throw StateError(
|
||||
'[$T] Params is null. Maybe you forgot to pass it?',
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) {
|
||||
if (_singleton && _isCached) {
|
||||
return _cache!;
|
||||
}
|
||||
final result = _provider();
|
||||
if (_singleton) {
|
||||
_cache = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves [Binding.toProvideWithParams] with an async `Future<T> Function(dynamic)` provider.
|
||||
class AsyncProviderWithParamsResolver<T> extends _BaseProviderResolver<T> {
|
||||
final AsyncProviderFactoryWithParams<T> _provider;
|
||||
Future<T>? _cache;
|
||||
bool _isCached = false;
|
||||
|
||||
AsyncProviderWithParamsResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
throw StateError(
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) {
|
||||
if (_singleton && _isCached) {
|
||||
return _cache!;
|
||||
}
|
||||
if (params == null) {
|
||||
throw StateError('[$T] Params is null. Maybe you forgot to pass it?');
|
||||
}
|
||||
final result = _provider(params);
|
||||
if (_singleton) {
|
||||
_cache = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallback resolver for `FutureOr<T> Function()` providers whose static type
|
||||
/// is not known at compile time. Detects sync vs async at resolve time.
|
||||
class FutureOrProviderResolver<T> extends _BaseProviderResolver<T> {
|
||||
final FutureOr<T> Function() _provider;
|
||||
Object? _cached;
|
||||
bool _isCached = false;
|
||||
|
||||
FutureOrProviderResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
if (_singleton && _isCached) {
|
||||
final cached = _cached;
|
||||
if (cached is Future<T>) {
|
||||
throw StateError(
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
return cached as T;
|
||||
}
|
||||
final result = _provider();
|
||||
if (result is Future<T>) {
|
||||
throw StateError(
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) {
|
||||
if (_singleton && _isCached) {
|
||||
final cached = _cached;
|
||||
if (cached is Future<T>) return cached;
|
||||
return Future<T>.value(cached as T);
|
||||
}
|
||||
final result = _provider();
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
if (result is Future<T>) return result;
|
||||
return Future<T>.value(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallback resolver for `FutureOr<T> Function(dynamic)` providers with params
|
||||
/// whose static type is not known at compile time.
|
||||
class FutureOrProviderWithParamsResolver<T> extends _BaseProviderResolver<T> {
|
||||
final FutureOr<T> Function(dynamic) _provider;
|
||||
Object? _cached;
|
||||
bool _isCached = false;
|
||||
|
||||
FutureOrProviderWithParamsResolver(this._provider);
|
||||
|
||||
@override
|
||||
T resolveSync([dynamic params]) {
|
||||
if (_singleton && _isCached) {
|
||||
final cached = _cached;
|
||||
if (cached is Future<T>) {
|
||||
throw StateError(
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
return cached as T;
|
||||
}
|
||||
if (params == null) {
|
||||
throw StateError('[$T] Params is null. Maybe you forgot to pass it?');
|
||||
}
|
||||
final result = _provider(params);
|
||||
if (result is Future<T>) {
|
||||
throw StateError(
|
||||
'Provider returns Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) {
|
||||
if (_singleton && _isCached) {
|
||||
final cached = _cached;
|
||||
if (cached is Future<T>) return cached;
|
||||
return Future<T>.value(cached as T);
|
||||
}
|
||||
if (params == null) {
|
||||
throw StateError('[$T] Params is null. Maybe you forgot to pass it?');
|
||||
}
|
||||
final result = _provider(params);
|
||||
if (_singleton) {
|
||||
_cached = result;
|
||||
_isCached = true;
|
||||
}
|
||||
if (result is Future<T>) return result;
|
||||
return Future<T>.value(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// Factory for creating instance resolvers (sync or async).
|
||||
class InstanceResolver {
|
||||
static BindingResolver<T> create<T>(FutureOr<T> instance) {
|
||||
if (instance is Future<T>) {
|
||||
return AsyncInstanceResolver<T>(instance);
|
||||
}
|
||||
return SyncInstanceResolver<T>(instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// Factory for creating the correct provider resolver based on the
|
||||
/// provider's static return type, avoiding runtime checks in fast paths.
|
||||
class ProviderResolver {
|
||||
static BindingResolver<T> create<T>(FutureOr<T> Function() provider) {
|
||||
if (provider is T Function()) {
|
||||
return SyncProviderResolver<T>(provider);
|
||||
}
|
||||
if (provider is Future<T> Function()) {
|
||||
return AsyncProviderResolver<T>(provider);
|
||||
}
|
||||
return FutureOrProviderResolver<T>(provider);
|
||||
}
|
||||
|
||||
static BindingResolver<T> createWithParams<T>(
|
||||
FutureOr<T> Function(dynamic) provider) {
|
||||
if (provider is T Function(dynamic)) {
|
||||
return SyncProviderWithParamsResolver<T>(provider);
|
||||
}
|
||||
if (provider is Future<T> Function(dynamic)) {
|
||||
return AsyncProviderWithParamsResolver<T>(provider);
|
||||
}
|
||||
return FutureOrProviderWithParamsResolver<T>(provider);
|
||||
}
|
||||
|
||||
/// Explicit sync resolver without parameters.
|
||||
static BindingResolver<T> sync<T>(ProviderFactory<T> provider) {
|
||||
return SyncProviderResolver<T>(provider);
|
||||
}
|
||||
|
||||
/// Explicit sync resolver with parameters.
|
||||
static BindingResolver<T> syncWithParams<T>(
|
||||
ProviderFactoryWithParams<T> provider) {
|
||||
return SyncProviderWithParamsResolver<T>(provider);
|
||||
}
|
||||
|
||||
/// Explicit async resolver without parameters.
|
||||
static BindingResolver<T> async<T>(AsyncProviderFactory<T> provider) {
|
||||
return AsyncProviderResolver<T>(provider);
|
||||
}
|
||||
|
||||
/// Explicit async resolver with parameters.
|
||||
static BindingResolver<T> asyncWithParams<T>(
|
||||
AsyncProviderFactoryWithParams<T> provider) {
|
||||
return AsyncProviderWithParamsResolver<T>(provider);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
// import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
/// Represents a DI scope (container) for modules, subscopes,
|
||||
/// and dependency resolution (sync/async) in CherryPick.
|
||||
@@ -60,6 +59,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
@override
|
||||
CherryPickObserver get observer => _observer;
|
||||
|
||||
bool get _isSilentObserver => _observer is SilentCherryPickObserver;
|
||||
|
||||
bool get _canUseDirectResolvePath =>
|
||||
_isSilentObserver &&
|
||||
!isCycleDetectionEnabled &&
|
||||
!isGlobalCycleDetectionEnabled;
|
||||
|
||||
/// COLLECTS all resolved instances that implement [Disposable].
|
||||
final Set<Disposable> _disposables = HashSet();
|
||||
|
||||
@@ -71,6 +77,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
Scope(this._parentScope, {required CherryPickObserver observer})
|
||||
: _observer = observer {
|
||||
setScopeId(_generateScopeId());
|
||||
if (!_isSilentObserver) {
|
||||
observer.onScopeOpened(scopeId ?? 'NO_ID');
|
||||
observer.onDiagnostic(
|
||||
'Scope created: ${scopeId ?? 'NO_ID'}',
|
||||
@@ -82,10 +89,11 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final Set<Module> _modulesList = HashSet();
|
||||
|
||||
// индекс для мгновенного поиска binding’ов
|
||||
// index for fast binding lookup
|
||||
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
||||
|
||||
/// Generates a unique identifier string for this scope instance.
|
||||
@@ -119,6 +127,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
childScope.enableGlobalCycleDetection();
|
||||
}
|
||||
_scopeMap[name] = childScope;
|
||||
if (!_isSilentObserver) {
|
||||
observer.onDiagnostic(
|
||||
'SubScope created: $name',
|
||||
details: {
|
||||
@@ -130,6 +139,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
return _scopeMap[name]!;
|
||||
}
|
||||
|
||||
@@ -149,6 +159,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
if (childScope.scopeId != null) {
|
||||
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
||||
}
|
||||
if (!_isSilentObserver) {
|
||||
observer.onScopeClosed(childScope.scopeId ?? name);
|
||||
observer.onDiagnostic(
|
||||
'SubScope closed: $name',
|
||||
@@ -161,6 +172,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
_scopeMap.remove(name);
|
||||
}
|
||||
|
||||
@@ -175,13 +187,14 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// ```
|
||||
Scope installModules(List<Module> modules) {
|
||||
_modulesList.addAll(modules);
|
||||
if (modules.isNotEmpty) {
|
||||
if (!_isSilentObserver && modules.isNotEmpty) {
|
||||
observer.onModulesInstalled(
|
||||
modules.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
for (var module in modules) {
|
||||
if (!_isSilentObserver) {
|
||||
observer.onDiagnostic(
|
||||
'Module installed: ${module.runtimeType}',
|
||||
details: {
|
||||
@@ -191,14 +204,17 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
'description': 'module installed',
|
||||
},
|
||||
);
|
||||
}
|
||||
module.builder(this);
|
||||
// Associate bindings with this scope's observer
|
||||
for (final binding in module.bindingSet) {
|
||||
binding.observer = observer;
|
||||
if (!_isSilentObserver) {
|
||||
binding.logAllDeferred();
|
||||
}
|
||||
}
|
||||
_rebuildResolversIndex();
|
||||
_addModuleToIndex(module);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -212,12 +228,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// testScope.dropModules();
|
||||
/// ```
|
||||
Scope dropModules() {
|
||||
if (_modulesList.isNotEmpty) {
|
||||
if (!_isSilentObserver && _modulesList.isNotEmpty) {
|
||||
observer.onModulesRemoved(
|
||||
_modulesList.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
if (!_isSilentObserver) {
|
||||
observer.onDiagnostic(
|
||||
'Modules dropped for scope: $scopeId',
|
||||
details: {
|
||||
@@ -226,6 +243,7 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
'description': 'modules dropped',
|
||||
},
|
||||
);
|
||||
}
|
||||
_modulesList.clear();
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
@@ -242,6 +260,16 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// final special = scope.resolve<Service>(named: 'special');
|
||||
/// ```
|
||||
T resolve<T>({String? named, dynamic params}) {
|
||||
if (_canUseDirectResolvePath) {
|
||||
final result = _tryResolveInternal<T>(named: named, params: params);
|
||||
if (result == null) {
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
if (result is Disposable) _disposables.add(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
observer.onInstanceRequested(T.toString(), T, scopeName: scopeId);
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
@@ -315,6 +343,12 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// final maybeDb = scope.tryResolve<Database>();
|
||||
/// ```
|
||||
T? tryResolve<T>({String? named, dynamic params}) {
|
||||
if (_canUseDirectResolvePath) {
|
||||
final result = _tryResolveInternal<T>(named: named, params: params);
|
||||
if (result != null && result is Disposable) _disposables.add(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = withGlobalCycleDetection<T?>(T, named, () {
|
||||
@@ -358,6 +392,21 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// final special = await scope.resolveAsync<Service>(named: "special");
|
||||
/// ```
|
||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||
if (_canUseDirectResolvePath) {
|
||||
final result =
|
||||
await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
if (result == null) {
|
||||
throw StateError(
|
||||
"Can't resolve async dependency `$T`. Maybe you forget register it?");
|
||||
}
|
||||
if (result is Disposable) _disposables.add(result);
|
||||
return result;
|
||||
}
|
||||
return _resolveAsyncWithObserverPath<T>(named: named, params: params);
|
||||
}
|
||||
|
||||
Future<T> _resolveAsyncWithObserverPath<T>(
|
||||
{String? named, dynamic params}) async {
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||
@@ -413,6 +462,17 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// final user = await scope.tryResolveAsync<User>();
|
||||
/// ```
|
||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||
if (_canUseDirectResolvePath) {
|
||||
final result =
|
||||
await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
if (result != null && result is Disposable) _disposables.add(result);
|
||||
return result;
|
||||
}
|
||||
return _tryResolveAsyncWithObserverPath<T>(named: named, params: params);
|
||||
}
|
||||
|
||||
Future<T?> _tryResolveAsyncWithObserverPath<T>(
|
||||
{String? named, dynamic params}) async {
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||
@@ -441,12 +501,12 @@ 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}) {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
// 1 - Try from own modules; 2 - Fallback to parent
|
||||
return resolver?.resolveAsync(params) ??
|
||||
_parentScope?.tryResolveAsync(named: named, params: params);
|
||||
_parentScope?.tryResolveAsync(named: named, params: params) ??
|
||||
Future<T?>.value(null);
|
||||
}
|
||||
|
||||
/// Looks up the [BindingResolver] for [T] and [named] within this scope.
|
||||
@@ -454,23 +514,27 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
||||
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
||||
|
||||
/// Rebuilds the internal index of all [BindingResolver]s from installed modules.
|
||||
/// Called after [installModules] and [dropModules]. Internal use only.
|
||||
void _rebuildResolversIndex() {
|
||||
_bindingResolvers.clear();
|
||||
for (var module in _modulesList) {
|
||||
void _addModuleToIndex(Module module) {
|
||||
for (var binding in module.bindingSet) {
|
||||
_bindingResolvers.putIfAbsent(binding.key, () => {});
|
||||
final nameKey = binding.isNamed ? binding.name : null;
|
||||
_bindingResolvers[binding.key]![nameKey] = binding.resolver!;
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the internal index of all [BindingResolver]s from installed modules.
|
||||
/// Called after [dropModules]. Internal use only.
|
||||
void _rebuildResolversIndex() {
|
||||
_bindingResolvers.clear();
|
||||
for (var module in _modulesList) {
|
||||
_addModuleToIndex(module);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks resolved [Disposable] instances, to ensure dispose is called automatically.
|
||||
/// Internal use only.
|
||||
void _trackDisposable(Object? obj) {
|
||||
if (obj is Disposable && !_disposables.contains(obj)) {
|
||||
if (obj is Disposable) {
|
||||
_disposables.add(obj);
|
||||
}
|
||||
}
|
||||
@@ -487,14 +551,14 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// ```
|
||||
Future<void> dispose() async {
|
||||
// Create copies to avoid concurrent modification
|
||||
final scopesCopy = Map<String, Scope>.from(_scopeMap);
|
||||
for (final subScope in scopesCopy.values) {
|
||||
final scopes = _scopeMap.values.toList();
|
||||
for (final subScope in scopes) {
|
||||
await subScope.dispose();
|
||||
}
|
||||
_scopeMap.clear();
|
||||
|
||||
final disposablesCopy = Set<Disposable>.from(_disposables);
|
||||
for (final d in disposablesCopy) {
|
||||
final disposables = _disposables.toList();
|
||||
for (final d in disposables) {
|
||||
await d.dispose();
|
||||
}
|
||||
_disposables.clear();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
@@ -12,7 +14,8 @@ void main() {
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
expect(binding.resolver, isA<BindingResolver<int>>());
|
||||
expect(binding.resolver, isA<SyncInstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
@@ -34,7 +37,8 @@ void main() {
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
expect(binding.resolver, isA<BindingResolver<int>>());
|
||||
expect(binding.resolver, isA<SyncInstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
@@ -73,7 +77,8 @@ void main() {
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
expect(binding.resolver, isA<BindingResolver<int>>());
|
||||
expect(binding.resolver, isA<AsyncInstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('isSingleton is true after toInstanceAsync', () {
|
||||
@@ -107,7 +112,8 @@ void main() {
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
expect(binding.resolver, isA<BindingResolver<int>>());
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
@@ -129,7 +135,8 @@ void main() {
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
expect(binding.resolver, isA<BindingResolver<int>>());
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
@@ -166,6 +173,43 @@ void main() {
|
||||
.toProvideWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.resolveAsync(3), 8);
|
||||
});
|
||||
|
||||
test('Resolves toProvideAsync value', () async {
|
||||
final binding = Binding<int>().toProvideAsync(() async => 5);
|
||||
expect(await binding.resolveAsync(), 5);
|
||||
});
|
||||
|
||||
test('toProvideAsync singleton caches instance', () async {
|
||||
int counter = 0;
|
||||
final binding = Binding<int>().toProvideAsync(() async {
|
||||
counter++;
|
||||
return counter;
|
||||
}).singleton();
|
||||
|
||||
final first = await binding.resolveAsync();
|
||||
final second = await binding.resolveAsync();
|
||||
expect(first, equals(second));
|
||||
expect(counter, 1);
|
||||
});
|
||||
|
||||
test('Resolves toProvideAsyncWithParams value', () async {
|
||||
final binding = Binding<int>()
|
||||
.toProvideAsyncWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.resolveAsync(3), 8);
|
||||
});
|
||||
|
||||
test('toProvideAsyncWithParams singleton caches instance', () async {
|
||||
int counter = 0;
|
||||
final binding = Binding<int>().toProvideAsyncWithParams((param) async {
|
||||
counter++;
|
||||
return counter + (param as int);
|
||||
}).singleton();
|
||||
|
||||
final first = await binding.resolveAsync(10);
|
||||
final second = await binding.resolveAsync(20);
|
||||
expect(first, equals(second));
|
||||
expect(counter, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Singleton provider binding ---
|
||||
@@ -232,6 +276,103 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
// --- FutureOr provider resolver (lazy detection, no eager side-effects) ---
|
||||
group('FutureOr Provider Resolver', () {
|
||||
test('Does not call provider at binding creation', () {
|
||||
int calls = 0;
|
||||
FutureOr<int> provider() {
|
||||
calls++;
|
||||
return 42;
|
||||
}
|
||||
|
||||
final binding = Binding<int>().toProvide(provider);
|
||||
expect(calls, 0);
|
||||
expect(binding.resolveSync(), 42);
|
||||
expect(calls, 1);
|
||||
});
|
||||
|
||||
test('Sync FutureOr provider resolves via resolveSync', () {
|
||||
final binding = Binding<int>().toProvide(() => 7);
|
||||
expect(binding.resolveSync(), 7);
|
||||
});
|
||||
|
||||
test('Async FutureOr provider throws on resolveSync', () {
|
||||
final binding =
|
||||
Binding<int>().toProvide(() async => 7);
|
||||
expect(() => binding.resolveSync(), throwsStateError);
|
||||
});
|
||||
|
||||
test('Async FutureOr provider resolves via resolveAsync', () async {
|
||||
final binding =
|
||||
Binding<int>().toProvide(() async => 7);
|
||||
expect(await binding.resolveAsync(), 7);
|
||||
});
|
||||
|
||||
test('FutureOr provider with params does not call provider at creation',
|
||||
() {
|
||||
int calls = 0;
|
||||
FutureOr<int> provider(dynamic p) {
|
||||
calls++;
|
||||
return (p as int) + 1;
|
||||
}
|
||||
|
||||
final binding = Binding<int>().toProvideWithParams(provider);
|
||||
expect(calls, 0);
|
||||
expect(binding.resolveSync(5), 6);
|
||||
expect(calls, 1);
|
||||
});
|
||||
|
||||
test('Async FutureOr provider with params throws on resolveSync', () {
|
||||
final binding = Binding<int>()
|
||||
.toProvideWithParams((p) async => (p as int) + 1);
|
||||
expect(() => binding.resolveSync(5), throwsStateError);
|
||||
});
|
||||
|
||||
test('Async FutureOr provider with params resolves via resolveAsync',
|
||||
() async {
|
||||
final binding = Binding<int>()
|
||||
.toProvideWithParams((p) async => (p as int) + 1);
|
||||
expect(await binding.resolveAsync(5), 6);
|
||||
});
|
||||
|
||||
test('FutureOr singleton caches sync result', () {
|
||||
int calls = 0;
|
||||
final binding = Binding<int>().toProvide(() {
|
||||
calls++;
|
||||
return 99;
|
||||
}).singleton();
|
||||
|
||||
expect(binding.resolveSync(), 99);
|
||||
expect(binding.resolveSync(), 99);
|
||||
expect(calls, 1);
|
||||
});
|
||||
|
||||
test('FutureOr singleton caches async result', () async {
|
||||
int calls = 0;
|
||||
final binding = Binding<int>().toProvide(() async {
|
||||
calls++;
|
||||
return 99;
|
||||
}).singleton();
|
||||
|
||||
expect(await binding.resolveAsync(), 99);
|
||||
expect(await binding.resolveAsync(), 99);
|
||||
expect(calls, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// --- InstanceResolver factory ---
|
||||
group('InstanceResolver.create', () {
|
||||
test('Returns SyncInstanceResolver for sync value', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver, isA<SyncInstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('Returns AsyncInstanceResolver for Future value', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
expect(binding.resolver, isA<AsyncInstanceResolver<int>>());
|
||||
});
|
||||
});
|
||||
|
||||
// --- WithName / Named binding, isNamed, edge-cases ---
|
||||
group('Named binding & helpers', () {
|
||||
test('withName sets isNamed true and stores name', () {
|
||||
|
||||
153
cherrypick/test/src/scope_fast_path_test.dart
Normal file
153
cherrypick/test/src/scope_fast_path_test.dart
Normal file
@@ -0,0 +1,153 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
class _IntModule extends Module {
|
||||
final int value;
|
||||
final void Function()? onBuild;
|
||||
|
||||
_IntModule(this.value, {this.onBuild});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
onBuild?.call();
|
||||
bind<int>().toInstance(value);
|
||||
}
|
||||
}
|
||||
|
||||
class _StringModule extends Module {
|
||||
final String value;
|
||||
|
||||
_StringModule(this.value);
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstance(value);
|
||||
}
|
||||
}
|
||||
|
||||
class _NamedIntModule extends Module {
|
||||
final String name;
|
||||
final int value;
|
||||
|
||||
_NamedIntModule(this.name, this.value);
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<int>().withName(name).toInstance(value);
|
||||
}
|
||||
}
|
||||
|
||||
class _DisposableModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<_DisposableService>().toProvide(() => _DisposableService());
|
||||
}
|
||||
}
|
||||
|
||||
class _DisposableService implements Disposable {
|
||||
bool disposed = false;
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
tearDown(() => CherryPick.closeRootScope());
|
||||
|
||||
group('SilentCherryPickObserver fast-path', () {
|
||||
late Scope scope;
|
||||
|
||||
setUp(() {
|
||||
// Must NOT have cycle detection — otherwise _canUseDirectResolvePath is false
|
||||
// and the fast-path branch is never taken.
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
scope = CherryPick.openRootScope();
|
||||
});
|
||||
|
||||
test('resolve with default silent observer uses fast-path', () {
|
||||
scope.installModules([_IntModule(42)]);
|
||||
expect(scope.resolve<int>(), 42);
|
||||
});
|
||||
|
||||
test('resolveAsync with default silent observer uses fast-path', () async {
|
||||
scope.installModules([_IntModule(42)]);
|
||||
final result = await scope.resolveAsync<int>();
|
||||
expect(result, 42);
|
||||
});
|
||||
|
||||
test('tryResolve with default silent observer uses fast-path', () {
|
||||
scope.installModules([_IntModule(42)]);
|
||||
expect(scope.tryResolve<int>(), 42);
|
||||
});
|
||||
|
||||
test('tryResolveAsync with default silent observer uses fast-path',
|
||||
() async {
|
||||
scope.installModules([_IntModule(42)]);
|
||||
final result = await scope.tryResolveAsync<int>();
|
||||
expect(result, 42);
|
||||
});
|
||||
|
||||
test('fast-path missing dependency throws', () {
|
||||
expect(() => scope.resolve<int>(), throwsStateError);
|
||||
});
|
||||
|
||||
test('fast-path missing async dependency throws', () {
|
||||
expect(scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('installModules with silent observer skips diagnostics', () {
|
||||
var buildCalls = 0;
|
||||
scope.installModules([_IntModule(42, onBuild: () => buildCalls++)]);
|
||||
expect(buildCalls, 1);
|
||||
expect(scope.resolve<int>(), 42);
|
||||
});
|
||||
|
||||
test('Disposable is tracked even in silent observer fast-path', () async {
|
||||
scope.installModules([_DisposableModule()]);
|
||||
|
||||
final service = scope.resolve<_DisposableService>();
|
||||
expect(service.disposed, false);
|
||||
await scope.dispose();
|
||||
expect(service.disposed, true);
|
||||
});
|
||||
});
|
||||
|
||||
group('Incremental module index', () {
|
||||
test('Multiple installModules calls accumulate bindings', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
scope.installModules([_IntModule(1)]);
|
||||
scope.installModules([_StringModule('two')]);
|
||||
|
||||
expect(scope.resolve<int>(), 1);
|
||||
expect(scope.resolve<String>(), 'two');
|
||||
});
|
||||
|
||||
test('dropModules clears all bindings', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
scope.installModules([_IntModule(1)]);
|
||||
scope.dropModules();
|
||||
|
||||
expect(() => scope.resolve<int>(), throwsStateError);
|
||||
});
|
||||
|
||||
test('Re-installing modules after dropModules works', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
scope.installModules([_IntModule(1)]);
|
||||
scope.dropModules();
|
||||
scope.installModules([_IntModule(2)]);
|
||||
|
||||
expect(scope.resolve<int>(), 2);
|
||||
});
|
||||
|
||||
test('Named bindings are indexed incrementally', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
scope.installModules([_NamedIntModule('a', 1)]);
|
||||
scope.installModules([_NamedIntModule('b', 2)]);
|
||||
|
||||
expect(scope.resolve<int>(named: 'a'), 1);
|
||||
expect(scope.resolve<int>(named: 'b'), 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,19 @@
|
||||
## 4.0.0-dev.0
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
|
||||
|
||||
## 3.0.3
|
||||
|
||||
## 3.0.2
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.2-dev.0
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: cherrypick_annotations
|
||||
description: |
|
||||
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
||||
version: 3.0.1
|
||||
version: 4.0.0-dev.0
|
||||
homepage: https://cherrypick-di.netlify.app
|
||||
documentation: https://cherrypick-di.netlify.app/docs/intro
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
|
||||
@@ -14,7 +14,7 @@ topics:
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.6.0 <4.0.0"
|
||||
sdk: ">=3.9.0 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
@@ -22,5 +22,5 @@ dependencies:
|
||||
# path: ^1.8.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
lints: ^6.0.0
|
||||
test: ^1.25.8
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
## 4.0.0-dev.0
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **BREAKING** **FEAT**: update Dart SDK minimum versions.
|
||||
|
||||
## 3.0.3
|
||||
|
||||
## 3.0.2
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.2-dev.0
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
@@ -11,13 +11,12 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:analyzer/dart/constant/value.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'package:analyzer/dart/element/nullability_suffix.dart';
|
||||
import 'package:analyzer/dart/element/type.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
/// CherryPick DI field injector generator for codegen.
|
||||
@@ -100,12 +99,12 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
/// }
|
||||
/// ```
|
||||
@override
|
||||
FutureOr<String> generateForAnnotatedElement(
|
||||
Element element,
|
||||
dynamic generateForAnnotatedElement(
|
||||
Element2 element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement) {
|
||||
if (element is! ClassElement2) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@injectable() can only be applied to classes.',
|
||||
element: element,
|
||||
@@ -113,7 +112,7 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
final className = classElement.name;
|
||||
final className = classElement.firstFragment.name2;
|
||||
final mixinName = '_\$$className';
|
||||
|
||||
final buffer = StringBuffer()
|
||||
@@ -121,8 +120,9 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
..writeln(' void _inject($className instance) {');
|
||||
|
||||
// Collect and process all @inject fields
|
||||
final injectFields =
|
||||
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
||||
final injectFields = classElement.fields2
|
||||
.where((f) => _isInjectField(f))
|
||||
.map((f) => _parseInjectField(f));
|
||||
|
||||
for (final parsedField in injectFields) {
|
||||
buffer.writeln(_generateInjectionLine(parsedField));
|
||||
@@ -138,8 +138,8 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
/// Returns true if a field is annotated with `@inject`.
|
||||
///
|
||||
/// Used to detect which fields should be processed for injection.
|
||||
static bool _isInjectField(FieldElement field) {
|
||||
return field.metadata.any(
|
||||
static bool _isInjectField(FieldElement2 field) {
|
||||
return field.firstFragment.metadata2.annotations.any(
|
||||
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
||||
);
|
||||
}
|
||||
@@ -149,11 +149,11 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
///
|
||||
/// Converts Dart field declaration and all parameterizing injection-related
|
||||
/// annotations into a [_ParsedInjectField] which is used for codegen.
|
||||
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
||||
static _ParsedInjectField _parseInjectField(FieldElement2 field) {
|
||||
String? scopeName;
|
||||
String? namedValue;
|
||||
|
||||
for (final meta in field.metadata) {
|
||||
for (final meta in field.firstFragment.metadata2.annotations) {
|
||||
final DartObject? obj = meta.computeConstantValue();
|
||||
final type = obj?.type?.getDisplayString();
|
||||
if (type == 'scope') {
|
||||
@@ -177,15 +177,15 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
}
|
||||
|
||||
// Determine nullability for field types like T? or Future<T?>
|
||||
bool isNullable = dartType.nullabilitySuffix ==
|
||||
NullabilitySuffix.question ||
|
||||
bool isNullable =
|
||||
dartType.nullabilitySuffix == NullabilitySuffix.question ||
|
||||
(dartType is ParameterizedType &&
|
||||
(dartType)
|
||||
.typeArguments
|
||||
.any((t) => t.nullabilitySuffix == NullabilitySuffix.question));
|
||||
(dartType).typeArguments.any(
|
||||
(t) => t.nullabilitySuffix == NullabilitySuffix.question,
|
||||
));
|
||||
|
||||
return _ParsedInjectField(
|
||||
fieldName: field.name,
|
||||
fieldName: field.firstFragment.name2 ?? '',
|
||||
coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий
|
||||
isFuture: isFuture,
|
||||
isNullable: isNullable,
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
@@ -79,12 +79,12 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
||||
///
|
||||
/// See file-level docs for usage and generated output example.
|
||||
@override
|
||||
String generateForAnnotatedElement(
|
||||
Element element,
|
||||
dynamic generateForAnnotatedElement(
|
||||
Element2 element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement) {
|
||||
if (element is! ClassElement2) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@module() can only be applied to classes.',
|
||||
element: element,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'exceptions.dart';
|
||||
import 'metadata_utils.dart';
|
||||
|
||||
@@ -52,8 +53,10 @@ class AnnotationValidator {
|
||||
/// - Parameter validation for method arguments.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] on any violation.
|
||||
static void validateMethodAnnotations(MethodElement method) {
|
||||
final annotations = _getAnnotationNames(method.metadata);
|
||||
static void validateMethodAnnotations(MethodElement2 method) {
|
||||
final annotations = _getAnnotationNames(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateMutuallyExclusiveAnnotations(method, annotations);
|
||||
_validateAnnotationCombinations(method, annotations);
|
||||
@@ -68,8 +71,10 @@ class AnnotationValidator {
|
||||
/// - Correct scope naming if present.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] if checks fail.
|
||||
static void validateFieldAnnotations(FieldElement field) {
|
||||
final annotations = _getAnnotationNames(field.metadata);
|
||||
static void validateFieldAnnotations(FieldElement2 field) {
|
||||
final annotations = _getAnnotationNames(
|
||||
field.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateInjectFieldAnnotations(field, annotations);
|
||||
}
|
||||
@@ -82,8 +87,10 @@ class AnnotationValidator {
|
||||
/// - Provides helpful context for error/warning reporting.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] if checks fail.
|
||||
static void validateClassAnnotations(ClassElement classElement) {
|
||||
final annotations = _getAnnotationNames(classElement.metadata);
|
||||
static void validateClassAnnotations(ClassElement2 classElement) {
|
||||
final annotations = _getAnnotationNames(
|
||||
classElement.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateModuleClassAnnotations(classElement, annotations);
|
||||
_validateInjectableClassAnnotations(classElement, annotations);
|
||||
@@ -104,7 +111,7 @@ class AnnotationValidator {
|
||||
///
|
||||
/// For example, `@instance` and `@provide` cannot both be present.
|
||||
static void _validateMutuallyExclusiveAnnotations(
|
||||
MethodElement method,
|
||||
MethodElement2 method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// @instance and @provide are mutually exclusive
|
||||
@@ -127,7 +134,7 @@ class AnnotationValidator {
|
||||
/// - One of `@instance` or `@provide` must be present for a registration method
|
||||
/// - Validates singleton usage
|
||||
static void _validateAnnotationCombinations(
|
||||
MethodElement method,
|
||||
MethodElement2 method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// @params can only be used with @provide
|
||||
@@ -165,7 +172,7 @@ class AnnotationValidator {
|
||||
|
||||
/// Singleton-specific method annotation checks.
|
||||
static void _validateSingletonUsage(
|
||||
MethodElement method,
|
||||
MethodElement2 method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// Singleton with params might not make sense in some contexts
|
||||
@@ -181,18 +188,17 @@ class AnnotationValidator {
|
||||
'Singleton methods cannot return void',
|
||||
element: method,
|
||||
suggestion: 'Remove @singleton annotation or change return type',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'return_type': returnType,
|
||||
},
|
||||
context: {'method_name': method.displayName, 'return_type': returnType},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates extra requirements or syntactic rules for annotation arguments, like @named.
|
||||
static void _validateAnnotationParameters(MethodElement method) {
|
||||
static void _validateAnnotationParameters(MethodElement2 method) {
|
||||
// Validate @named annotation parameters
|
||||
final namedValue = MetadataUtils.getNamedValue(method.metadata);
|
||||
final namedValue = MetadataUtils.getNamedValue(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
if (namedValue != null) {
|
||||
if (namedValue.isEmpty) {
|
||||
throw AnnotationValidationException(
|
||||
@@ -222,8 +228,10 @@ class AnnotationValidator {
|
||||
}
|
||||
|
||||
// Validate method parameters for @params usage
|
||||
for (final param in method.parameters) {
|
||||
final paramAnnotations = _getAnnotationNames(param.metadata);
|
||||
for (final param in method.formalParameters) {
|
||||
final paramAnnotations = _getAnnotationNames(
|
||||
param.firstFragment.metadata2.annotations,
|
||||
);
|
||||
if (paramAnnotations.contains('params')) {
|
||||
_validateParamsParameter(param, method);
|
||||
}
|
||||
@@ -232,7 +240,9 @@ class AnnotationValidator {
|
||||
|
||||
/// Checks that @params is used with compatible parameter type.
|
||||
static void _validateParamsParameter(
|
||||
ParameterElement param, MethodElement method) {
|
||||
FormalParameterElement param,
|
||||
MethodElement2 method,
|
||||
) {
|
||||
// @params parameter should typically be dynamic or Map<String, dynamic>
|
||||
final paramType = param.type.getDisplayString();
|
||||
if (paramType != 'dynamic' &&
|
||||
@@ -256,7 +266,7 @@ class AnnotationValidator {
|
||||
|
||||
/// Checks field-level annotation for valid injectable fields.
|
||||
static void _validateInjectFieldAnnotations(
|
||||
FieldElement field,
|
||||
FieldElement2 field,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('inject')) {
|
||||
@@ -270,15 +280,12 @@ class AnnotationValidator {
|
||||
'Cannot inject void type',
|
||||
element: field,
|
||||
suggestion: 'Use a concrete type instead of void',
|
||||
context: {
|
||||
'field_name': field.displayName,
|
||||
'field_type': fieldType,
|
||||
},
|
||||
context: {'field_name': field.displayName, 'field_type': fieldType},
|
||||
);
|
||||
}
|
||||
|
||||
// Validate scope annotation if present
|
||||
for (final meta in field.metadata) {
|
||||
for (final meta in field.firstFragment.metadata2.annotations) {
|
||||
final obj = meta.computeConstantValue();
|
||||
final type = obj?.type?.getDisplayString();
|
||||
if (type == 'scope') {
|
||||
@@ -290,7 +297,7 @@ class AnnotationValidator {
|
||||
|
||||
/// Checks @module usage: must have at least one DI method, each with DI-annotation.
|
||||
static void _validateModuleClassAnnotations(
|
||||
ClassElement classElement,
|
||||
ClassElement2 classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('module')) {
|
||||
@@ -298,8 +305,9 @@ class AnnotationValidator {
|
||||
}
|
||||
|
||||
// Check if class has public methods
|
||||
final publicMethods =
|
||||
classElement.methods.where((m) => m.isPublic).toList();
|
||||
final publicMethods = classElement.methods2
|
||||
.where((m) => m.isPublic)
|
||||
.toList();
|
||||
if (publicMethods.isEmpty) {
|
||||
throw AnnotationValidationException(
|
||||
'Module class must have at least one public method',
|
||||
@@ -314,7 +322,9 @@ class AnnotationValidator {
|
||||
|
||||
// Validate that public methods have appropriate annotations
|
||||
for (final method in publicMethods) {
|
||||
final methodAnnotations = _getAnnotationNames(method.metadata);
|
||||
final methodAnnotations = _getAnnotationNames(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
if (!methodAnnotations.contains('instance') &&
|
||||
!methodAnnotations.contains('provide')) {
|
||||
throw AnnotationValidationException(
|
||||
@@ -332,7 +342,7 @@ class AnnotationValidator {
|
||||
|
||||
/// Checks @injectable usage on classes and their fields.
|
||||
static void _validateInjectableClassAnnotations(
|
||||
ClassElement classElement,
|
||||
ClassElement2 classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('injectable')) {
|
||||
@@ -340,8 +350,10 @@ class AnnotationValidator {
|
||||
}
|
||||
|
||||
// Check if class has injectable fields
|
||||
final injectFields = classElement.fields.where((f) {
|
||||
final fieldAnnotations = _getAnnotationNames(f.metadata);
|
||||
final injectFields = classElement.fields2.where((f) {
|
||||
final fieldAnnotations = _getAnnotationNames(
|
||||
f.firstFragment.metadata2.annotations,
|
||||
);
|
||||
return fieldAnnotations.contains('inject');
|
||||
}).toList();
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
|
||||
import 'bind_parameters_spec.dart';
|
||||
import 'metadata_utils.dart';
|
||||
@@ -25,7 +25,7 @@ enum BindingType {
|
||||
instance,
|
||||
|
||||
/// Provider/factory function (@provide).
|
||||
provide;
|
||||
provide,
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
@@ -155,7 +155,8 @@ class BindSpec {
|
||||
switch (bindingType) {
|
||||
case BindingType.instance:
|
||||
throw StateError(
|
||||
'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.');
|
||||
'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.',
|
||||
);
|
||||
//return isAsyncInstance
|
||||
// ? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))'
|
||||
// : '.toInstance(($fnArgs) => $methodName($fnArgs))';
|
||||
@@ -189,20 +190,24 @@ class BindSpec {
|
||||
case BindingType.provide:
|
||||
if (isAsyncProvide) {
|
||||
if (needsMultiline) {
|
||||
final lambdaIndent =
|
||||
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||
final closingIndent =
|
||||
(isSingleton || named != null) ? indent + 4 : indent;
|
||||
final lambdaIndent = (isSingleton || named != null)
|
||||
? indent + 6
|
||||
: indent + 2;
|
||||
final closingIndent = (isSingleton || named != null)
|
||||
? indent + 4
|
||||
: indent;
|
||||
return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
|
||||
} else {
|
||||
return '.toProvideAsync(() => $methodName($argsStr))';
|
||||
}
|
||||
} else {
|
||||
if (needsMultiline) {
|
||||
final lambdaIndent =
|
||||
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||
final closingIndent =
|
||||
(isSingleton || named != null) ? indent + 4 : indent;
|
||||
final lambdaIndent = (isSingleton || named != null)
|
||||
? indent + 6
|
||||
: indent + 2;
|
||||
final closingIndent = (isSingleton || named != null)
|
||||
? indent + 4
|
||||
: indent;
|
||||
return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
|
||||
} else {
|
||||
return '.toProvide(() => $methodName($argsStr))';
|
||||
@@ -246,7 +251,7 @@ class BindSpec {
|
||||
/// print(bindSpec.returnType); // e.g., 'Logger'
|
||||
/// ```
|
||||
/// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid.
|
||||
static BindSpec fromMethod(MethodElement method) {
|
||||
static BindSpec fromMethod(MethodElement2 method) {
|
||||
try {
|
||||
// Validate method annotations
|
||||
AnnotationValidator.validateMethodAnnotations(method);
|
||||
@@ -254,28 +259,44 @@ class BindSpec {
|
||||
// Parse return type using improved type parser
|
||||
final parsedReturnType = TypeParser.parseType(method.returnType, method);
|
||||
|
||||
final methodName = method.displayName;
|
||||
final methodName = method.firstFragment.name2 ?? '';
|
||||
|
||||
// Check for @singleton annotation.
|
||||
final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton');
|
||||
final isSingleton = MetadataUtils.anyMeta(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
'singleton',
|
||||
);
|
||||
|
||||
// Get @named value if present.
|
||||
final named = MetadataUtils.getNamedValue(method.metadata);
|
||||
final named = MetadataUtils.getNamedValue(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
// Parse each method parameter.
|
||||
final params = <BindParameterSpec>[];
|
||||
bool hasParams = false;
|
||||
for (final p in method.parameters) {
|
||||
for (final p in method.formalParameters) {
|
||||
final typeStr = p.type.getDisplayString();
|
||||
final paramNamed = MetadataUtils.getNamedValue(p.metadata);
|
||||
final isParams = MetadataUtils.anyMeta(p.metadata, 'params');
|
||||
final paramNamed = MetadataUtils.getNamedValue(
|
||||
p.firstFragment.metadata2.annotations,
|
||||
);
|
||||
final isParams = MetadataUtils.anyMeta(
|
||||
p.firstFragment.metadata2.annotations,
|
||||
'params',
|
||||
);
|
||||
if (isParams) hasParams = true;
|
||||
params.add(BindParameterSpec(typeStr, paramNamed, isParams: isParams));
|
||||
}
|
||||
|
||||
// Determine bindingType: @instance or @provide.
|
||||
final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance');
|
||||
final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide');
|
||||
final hasInstance = MetadataUtils.anyMeta(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
'instance',
|
||||
);
|
||||
final hasProvide = MetadataUtils.anyMeta(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
'provide',
|
||||
);
|
||||
|
||||
if (!hasInstance && !hasProvide) {
|
||||
throw AnnotationValidationException(
|
||||
@@ -290,8 +311,9 @@ class BindSpec {
|
||||
);
|
||||
}
|
||||
|
||||
final bindingType =
|
||||
hasInstance ? BindingType.instance : BindingType.provide;
|
||||
final bindingType = hasInstance
|
||||
? BindingType.instance
|
||||
: BindingType.provide;
|
||||
|
||||
// PROHIBIT @params with @instance bindings!
|
||||
if (bindingType == BindingType.instance && hasParams) {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
@@ -48,7 +48,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
||||
|
||||
CherryPickGeneratorException(
|
||||
String message, {
|
||||
required Element element,
|
||||
required Element2 element,
|
||||
required this.category,
|
||||
this.suggestion,
|
||||
this.context,
|
||||
@@ -62,7 +62,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
||||
String category,
|
||||
String? suggestion,
|
||||
Map<String, dynamic>? context,
|
||||
Element element,
|
||||
Element2 element,
|
||||
) {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
@@ -74,7 +74,9 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
||||
buffer.writeln('Context:');
|
||||
buffer.writeln(' Element: ${element.displayName}');
|
||||
buffer.writeln(' Type: ${element.runtimeType}');
|
||||
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}');
|
||||
buffer.writeln(
|
||||
' Location: ${element.firstFragment.libraryFragment?.source.fullName ?? 'unknown'}',
|
||||
);
|
||||
|
||||
// Try to show enclosing element info for extra context
|
||||
try {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'bind_spec.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
@@ -75,14 +76,11 @@ class GeneratedClass {
|
||||
/// final gen = GeneratedClass.fromClassElement(classElement);
|
||||
/// print(gen.generatedClassName); // e.g. $AppModule
|
||||
/// ```
|
||||
static GeneratedClass fromClassElement(ClassElement element) {
|
||||
final className = element.displayName;
|
||||
// Generated class name with '$' prefix (standard for generated Dart code).
|
||||
static GeneratedClass fromClassElement(ClassElement2 element) {
|
||||
final className = element.firstFragment.name2 ?? '';
|
||||
final generatedClassName = r'$' + className;
|
||||
// Get source file name
|
||||
final sourceFile = element.source.shortName;
|
||||
// Collect bindings for all non-abstract methods.
|
||||
final binds = element.methods
|
||||
final sourceFile = element.firstFragment.libraryFragment.source.shortName;
|
||||
final binds = element.methods2
|
||||
.where((m) => !m.isAbstract)
|
||||
.map(BindSpec.fromMethod)
|
||||
.toList();
|
||||
|
||||
@@ -41,14 +41,16 @@ class MetadataUtils {
|
||||
/// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata, 'singleton');
|
||||
/// ```
|
||||
static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
|
||||
return meta.any((m) =>
|
||||
return meta.any(
|
||||
(m) =>
|
||||
m
|
||||
.computeConstantValue()
|
||||
?.type
|
||||
?.getDisplayString()
|
||||
.toLowerCase()
|
||||
.contains(typeName.toLowerCase()) ??
|
||||
false);
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Extracts the string value from a `@named('value')` annotation if present in [meta].
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'package:analyzer/dart/element/nullability_suffix.dart';
|
||||
import 'package:analyzer/dart/element/type.dart';
|
||||
import 'exceptions.dart';
|
||||
@@ -45,7 +45,7 @@ class TypeParser {
|
||||
/// final parsed = TypeParser.parseType(field.type, field);
|
||||
/// if (parsed.isNullable) print('Field is nullable');
|
||||
/// ```
|
||||
static ParsedType parseType(DartType dartType, Element context) {
|
||||
static ParsedType parseType(DartType dartType, Element2 context) {
|
||||
try {
|
||||
return _parseTypeInternal(dartType, context);
|
||||
} catch (e) {
|
||||
@@ -61,7 +61,7 @@ class TypeParser {
|
||||
}
|
||||
}
|
||||
|
||||
static ParsedType _parseTypeInternal(DartType dartType, Element context) {
|
||||
static ParsedType _parseTypeInternal(DartType dartType, Element2 context) {
|
||||
final displayString = dartType.getDisplayString();
|
||||
final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question;
|
||||
|
||||
@@ -87,7 +87,10 @@ class TypeParser {
|
||||
}
|
||||
|
||||
static ParsedType _parseFutureType(
|
||||
DartType dartType, Element context, bool isNullable) {
|
||||
DartType dartType,
|
||||
Element2 context,
|
||||
bool isNullable,
|
||||
) {
|
||||
if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) {
|
||||
throw TypeParsingException(
|
||||
'Future type must have a type argument',
|
||||
@@ -112,7 +115,10 @@ class TypeParser {
|
||||
}
|
||||
|
||||
static ParsedType _parseGenericType(
|
||||
ParameterizedType dartType, Element context, bool isNullable) {
|
||||
ParameterizedType dartType,
|
||||
Element2 context,
|
||||
bool isNullable,
|
||||
) {
|
||||
final typeArguments = dartType.typeArguments
|
||||
.map((arg) => _parseTypeInternal(arg, context))
|
||||
.toList();
|
||||
@@ -138,7 +144,7 @@ class TypeParser {
|
||||
/// final parsed = TypeParser.parseType(field.type, field);
|
||||
/// TypeParser.validateInjectableType(parsed, field);
|
||||
/// ```
|
||||
static void validateInjectableType(ParsedType parsedType, Element context) {
|
||||
static void validateInjectableType(ParsedType parsedType, Element2 context) {
|
||||
// Check for void type
|
||||
if (parsedType.coreType == 'void') {
|
||||
throw TypeParsingException(
|
||||
|
||||
@@ -2,7 +2,7 @@ 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: 3.0.1
|
||||
version: 4.0.0-dev.0
|
||||
homepage: https://cherrypick-di.netlify.app
|
||||
documentation: https://cherrypick-di.netlify.app/docs/intro
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
|
||||
@@ -15,20 +15,20 @@ topics:
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.6.0 <4.0.0"
|
||||
sdk: ">=3.9.0 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
cherrypick_annotations: ^3.0.1
|
||||
analyzer: ^7.7.1
|
||||
cherrypick_annotations: ^4.0.0-dev.0
|
||||
analyzer: ">=8.2.9 <10.0.1"
|
||||
dart_style: ^3.0.0
|
||||
build: ^2.4.1
|
||||
source_gen: ^2.0.0
|
||||
build: ^3.0.0
|
||||
source_gen: ^4.2.0
|
||||
collection: ^1.18.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.1.1
|
||||
lints: ^6.0.0
|
||||
mockito: ^5.4.5
|
||||
test: ^1.25.8
|
||||
build_test: ^2.1.7
|
||||
build_runner: ^2.4.13
|
||||
build_test: ^3.0.0
|
||||
build_runner: ^2.5.0
|
||||
|
||||
@@ -480,7 +480,8 @@ void notAClass() {}
|
||||
);
|
||||
});
|
||||
|
||||
test('should generate empty mixin for class without @inject fields',
|
||||
test(
|
||||
'should generate empty mixin for class without @inject fields',
|
||||
() async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
@@ -510,7 +511,8 @@ mixin _\$TestWidget {
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('Edge Cases', () {
|
||||
@@ -593,12 +595,8 @@ mixin _\$TestWidget {
|
||||
Future<void> _testGeneration(String input, String expectedOutput) async {
|
||||
await testBuilder(
|
||||
injectBuilder(BuilderOptions.empty),
|
||||
{
|
||||
'a|lib/test_widget.dart': input,
|
||||
},
|
||||
outputs: {
|
||||
'a|lib/test_widget.inject.cherrypick.g.dart': expectedOutput,
|
||||
},
|
||||
reader: await PackageAssetReader.currentIsolate(),
|
||||
{'a|lib/test_widget.dart': input},
|
||||
outputs: {'a|lib/test_widget.inject.cherrypick.g.dart': expectedOutput},
|
||||
readerWriter: TestReaderWriter(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -590,7 +590,8 @@ void notAClass() {}
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw error for method without @instance or @provide',
|
||||
test(
|
||||
'should throw error for method without @instance or @provide',
|
||||
() async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
@@ -608,7 +609,8 @@ abstract class TestModule extends Module {
|
||||
() => _testGeneration(input, ''),
|
||||
throwsA(isA<InvalidGenerationSourceError>()),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('should throw error for @params with @instance', () async {
|
||||
const input = '''
|
||||
@@ -637,12 +639,8 @@ abstract class TestModule extends Module {
|
||||
Future<void> _testGeneration(String input, String expectedOutput) async {
|
||||
await testBuilder(
|
||||
moduleBuilder(BuilderOptions.empty),
|
||||
{
|
||||
'a|lib/test_module.dart': input,
|
||||
},
|
||||
outputs: {
|
||||
'a|lib/test_module.module.cherrypick.g.dart': expectedOutput,
|
||||
},
|
||||
reader: await PackageAssetReader.currentIsolate(),
|
||||
{'a|lib/test_module.dart': input},
|
||||
outputs: {'a|lib/test_module.module.cherrypick.g.dart': expectedOutput},
|
||||
readerWriter: TestReaderWriter(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/source/source.dart';
|
||||
import 'package:cherrypick_generator/src/type_parser.dart';
|
||||
import 'package:cherrypick_generator/src/exceptions.dart';
|
||||
|
||||
@@ -42,7 +41,9 @@ void main() {
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
parsedType,
|
||||
_createMockElement(),
|
||||
),
|
||||
throwsA(isA<TypeParsingException>()),
|
||||
);
|
||||
});
|
||||
@@ -59,7 +60,9 @@ void main() {
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
parsedType,
|
||||
_createMockElement(),
|
||||
),
|
||||
throwsA(isA<TypeParsingException>()),
|
||||
);
|
||||
});
|
||||
@@ -76,7 +79,9 @@ void main() {
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
parsedType,
|
||||
_createMockElement(),
|
||||
),
|
||||
returnsNormally,
|
||||
);
|
||||
});
|
||||
@@ -159,7 +164,8 @@ void main() {
|
||||
expect(parsedType.resolveMethodName, equals('resolveAsync'));
|
||||
});
|
||||
|
||||
test('should return correct resolveMethodName for nullable async types',
|
||||
test(
|
||||
'should return correct resolveMethodName for nullable async types',
|
||||
() {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'Future<String?>',
|
||||
@@ -171,7 +177,8 @@ void main() {
|
||||
);
|
||||
|
||||
expect(parsedType.resolveMethodName, equals('tryResolveAsync'));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('should implement equality correctly', () {
|
||||
final parsedType1 = ParsedType(
|
||||
@@ -216,19 +223,19 @@ void main() {
|
||||
}
|
||||
|
||||
// Mock element for testing
|
||||
Element _createMockElement() {
|
||||
Element2 _createMockElement() {
|
||||
return _MockElement();
|
||||
}
|
||||
|
||||
class _MockElement implements Element {
|
||||
class _MockElement implements Element2 {
|
||||
@override
|
||||
String get displayName => 'MockElement';
|
||||
|
||||
@override
|
||||
String get name => 'MockElement';
|
||||
|
||||
@override
|
||||
Source? get source => null;
|
||||
//@override
|
||||
//String get name => 'MockElement';
|
||||
//
|
||||
//@override
|
||||
//Source? get source => null;
|
||||
|
||||
@override
|
||||
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
|
||||
@@ -9,11 +9,7 @@ void main() {
|
||||
// Создаем модуль, который будет предоставлять UseCase
|
||||
]);
|
||||
|
||||
runApp(
|
||||
const CherryPickProvider(
|
||||
child: MyApp(),
|
||||
),
|
||||
);
|
||||
runApp(const CherryPickProvider(child: MyApp()));
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
@@ -21,10 +17,6 @@ class MyApp extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CherryPickProvider(
|
||||
child: MaterialApp(
|
||||
home: MyHomePage(),
|
||||
),
|
||||
);
|
||||
return CherryPickProvider(child: MaterialApp(home: MyHomePage()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,8 @@ class MyHomePage extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
//_inject(context); // Make sure this function is called in context
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Example App'),
|
||||
),
|
||||
body: Center(
|
||||
child: Text(useCase.fetchData()),
|
||||
),
|
||||
appBar: AppBar(title: const Text('Example App')),
|
||||
body: Center(child: Text(useCase.fetchData())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,18 +5,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: _fe_analyzer_shared
|
||||
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
|
||||
sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "85.0.0"
|
||||
version: "91.0.0"
|
||||
analyzer:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: analyzer
|
||||
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
|
||||
sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.7.1"
|
||||
version: "8.4.1"
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -45,50 +45,50 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build
|
||||
sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0
|
||||
sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
version: "3.1.0"
|
||||
build_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_config
|
||||
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
|
||||
sha256: "4f64382b97504dc2fcdf487d5aae33418e08b4703fc21249e4db6d804a4d0187"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
version: "1.2.0"
|
||||
build_daemon:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_daemon
|
||||
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
|
||||
sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.4"
|
||||
version: "4.1.1"
|
||||
build_resolvers:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_resolvers
|
||||
sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0
|
||||
sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
version: "3.0.3"
|
||||
build_runner:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: build_runner
|
||||
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
|
||||
sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.15"
|
||||
version: "2.7.1"
|
||||
build_runner_core:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_runner_core
|
||||
sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021"
|
||||
sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.0.0"
|
||||
version: "9.3.1"
|
||||
built_collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -101,10 +101,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: built_value
|
||||
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
|
||||
sha256: "7931c90b84bc573fef103548e354258ae4c9d28d140e41961df6843c5d60d4d8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.12.0"
|
||||
version: "8.12.3"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -117,38 +117,38 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: checked_yaml
|
||||
sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff
|
||||
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.3"
|
||||
version: "2.0.4"
|
||||
cherrypick:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cherrypick_annotations:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_annotations"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cherrypick_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_flutter"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cherrypick_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
path: "../../cherrypick_generator"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -161,10 +161,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: code_builder
|
||||
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
|
||||
sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.10.1"
|
||||
version: "4.11.1"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -185,10 +185,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.6"
|
||||
version: "3.0.7"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -201,10 +201,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dart_style
|
||||
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac"
|
||||
sha256: a9c30492da18ff84efe2422ba2d319a89942d93e58eb0b73d32abe822ef54b7b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
version: "3.1.3"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -238,10 +238,10 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_lints
|
||||
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
|
||||
sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "6.0.0"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
@@ -271,14 +271,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.0"
|
||||
http_multi_server:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -303,54 +295,46 @@ 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:
|
||||
name: json_annotation
|
||||
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
|
||||
sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.9.0"
|
||||
version: "4.10.0"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker
|
||||
sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
|
||||
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.0.9"
|
||||
version: "11.0.2"
|
||||
leak_tracker_flutter_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_flutter_testing
|
||||
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
|
||||
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.9"
|
||||
version: "3.0.10"
|
||||
leak_tracker_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_testing
|
||||
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
|
||||
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lints
|
||||
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
|
||||
sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.1"
|
||||
version: "6.0.0"
|
||||
logging:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -379,10 +363,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
|
||||
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.16.0"
|
||||
version: "1.17.0"
|
||||
mime:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -411,10 +395,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pool
|
||||
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
|
||||
sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.1"
|
||||
version: "1.5.2"
|
||||
pub_semver:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -456,10 +440,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_gen
|
||||
sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b"
|
||||
sha256: "1d562a3c1f713904ebbed50d2760217fd8a51ca170ac4b05b0db490699dbac17"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "4.2.0"
|
||||
source_span:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -512,10 +496,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: test_api
|
||||
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
|
||||
sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.4"
|
||||
version: "0.7.7"
|
||||
timing:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -536,26 +520,26 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_math
|
||||
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
version: "2.2.0"
|
||||
vm_service:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
|
||||
sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "15.0.0"
|
||||
version: "15.0.2"
|
||||
watcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: watcher
|
||||
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
|
||||
sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.3"
|
||||
version: "1.2.1"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -589,5 +573,5 @@ packages:
|
||||
source: hosted
|
||||
version: "3.1.3"
|
||||
sdks:
|
||||
dart: ">=3.7.0-0 <4.0.0"
|
||||
dart: ">=3.9.0 <4.0.0"
|
||||
flutter: ">=3.18.0-18.0.pre.54"
|
||||
|
||||
@@ -5,7 +5,7 @@ publish_to: 'none'
|
||||
version: 1.0.0+1
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
sdk: ">=3.9.0 <4.0.0"
|
||||
|
||||
|
||||
dependencies:
|
||||
@@ -25,11 +25,11 @@ dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
|
||||
flutter_lints: ^5.0.0
|
||||
flutter_lints: ^6.0.0
|
||||
|
||||
cherrypick_generator:
|
||||
path: ../../cherrypick_generator
|
||||
build_runner: ^2.4.15
|
||||
build_runner: ^2.5.0
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
|
||||
@@ -4,7 +4,7 @@ part 'post_model.freezed.dart';
|
||||
part 'post_model.g.dart';
|
||||
|
||||
@freezed
|
||||
class PostModel with _$PostModel {
|
||||
abstract class PostModel with _$PostModel {
|
||||
const factory PostModel({
|
||||
required int id,
|
||||
required String title,
|
||||
|
||||
@@ -12,9 +12,9 @@ class PostRepositoryImpl implements PostRepository {
|
||||
Future<Either<Exception, List<Post>>> getPosts() async {
|
||||
try {
|
||||
final posts = await api.getPosts();
|
||||
return Right(posts
|
||||
.map((e) => Post(id: e.id, title: e.title, body: e.body))
|
||||
.toList());
|
||||
return Right(
|
||||
posts.map((e) => Post(id: e.id, title: e.title, body: e.body)).toList(),
|
||||
);
|
||||
} catch (e) {
|
||||
return Left(Exception(e.toString()));
|
||||
}
|
||||
|
||||
@@ -23,8 +23,9 @@ abstract class AppModule extends Module {
|
||||
@provide()
|
||||
@singleton()
|
||||
TalkerDioLogger talkerDioLogger(
|
||||
Talker talker, TalkerDioLoggerSettings settings) =>
|
||||
TalkerDioLogger(talker: talker, settings: settings);
|
||||
Talker talker,
|
||||
TalkerDioLoggerSettings settings,
|
||||
) => TalkerDioLogger(talker: talker, settings: settings);
|
||||
|
||||
@instance()
|
||||
int timeout() => 1000;
|
||||
@@ -75,12 +76,14 @@ abstract class AppModule extends Module {
|
||||
@provide()
|
||||
@named('TestProvideWithParams1')
|
||||
String testProvideWithParams1(
|
||||
@named('baseUrl') String baseUrl, @params() dynamic params) =>
|
||||
"hello $params";
|
||||
@named('baseUrl') String baseUrl,
|
||||
@params() dynamic params,
|
||||
) => "hello $params";
|
||||
|
||||
@provide()
|
||||
@named('TestProvideAsyncWithParams1')
|
||||
Future<String> testProvideAsyncWithParams1(
|
||||
@named('baseUrl') String baseUrl, @params() dynamic params) async =>
|
||||
"hello $params";
|
||||
@named('baseUrl') String baseUrl,
|
||||
@params() dynamic params,
|
||||
) async => "hello $params";
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
part 'post.freezed.dart';
|
||||
|
||||
@freezed
|
||||
class Post with _$Post {
|
||||
abstract class Post with _$Post {
|
||||
const factory Post({
|
||||
required int id,
|
||||
required String title,
|
||||
|
||||
@@ -23,10 +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));
|
||||
}
|
||||
|
||||
@@ -12,10 +12,7 @@ class PostDetailsPage extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text('Post #${post.id}')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(post.body),
|
||||
),
|
||||
body: Padding(padding: const EdgeInsets.all(16), child: Text(post.body)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,9 @@ class PostsPage extends StatelessWidget {
|
||||
title: Text(posts[i].title),
|
||||
subtitle: Text(posts[i].body),
|
||||
onTap: () {
|
||||
AutoRouter.of(context)
|
||||
.push(PostDetailsRoute(post: posts[i]));
|
||||
AutoRouter.of(
|
||||
context,
|
||||
).push(PostDetailsRoute(post: posts[i]));
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
@@ -5,18 +5,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: _fe_analyzer_shared
|
||||
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
|
||||
sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "85.0.0"
|
||||
version: "91.0.0"
|
||||
analyzer:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: analyzer
|
||||
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
|
||||
sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.7.1"
|
||||
version: "8.4.1"
|
||||
ansi_styles:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -53,26 +53,26 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: auto_route
|
||||
sha256: b8c036fa613a98a759cf0fdcba26e62f4985dcbff01a5e760ab411e8554bbaf0
|
||||
sha256: "6d3ccc11b520b6eff0ab5a2c3d1c43c46d1486249cc746c4bb14486d876e8b43"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.1.0+1"
|
||||
version: "10.3.0"
|
||||
auto_route_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: auto_route_generator
|
||||
sha256: "8e622d26dc6be4bf496d47969e3e9ba555c3abcf2290da6abfa43cbd4f57fa52"
|
||||
sha256: a84dcd972e3e38c8925cca2669faa8112a79db9b5d726e0fb8d4ea15ced095fb
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.0.1"
|
||||
version: "10.3.1"
|
||||
bloc:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: bloc
|
||||
sha256: "52c10575f4445c61dd9e0cafcc6356fdd827c4c64dd7945ef3c4105f6b6ac189"
|
||||
sha256: a48653a82055a900b88cd35f92429f068c5a8057ae9b136d197b3d56c57efb81
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "9.0.0"
|
||||
version: "9.2.0"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -85,50 +85,50 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build
|
||||
sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0
|
||||
sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
version: "3.1.0"
|
||||
build_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_config
|
||||
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
|
||||
sha256: "4f64382b97504dc2fcdf487d5aae33418e08b4703fc21249e4db6d804a4d0187"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
version: "1.2.0"
|
||||
build_daemon:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_daemon
|
||||
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
|
||||
sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.4"
|
||||
version: "4.1.1"
|
||||
build_resolvers:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_resolvers
|
||||
sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0
|
||||
sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
version: "3.0.3"
|
||||
build_runner:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: build_runner
|
||||
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
|
||||
sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.15"
|
||||
version: "2.7.1"
|
||||
build_runner_core:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_runner_core
|
||||
sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021"
|
||||
sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.0.0"
|
||||
version: "9.3.1"
|
||||
built_collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -141,10 +141,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: built_value
|
||||
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
|
||||
sha256: "7931c90b84bc573fef103548e354258ae4c9d28d140e41961df6843c5d60d4d8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.12.0"
|
||||
version: "8.12.3"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -165,39 +165,39 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: checked_yaml
|
||||
sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff
|
||||
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.3"
|
||||
version: "2.0.4"
|
||||
cherrypick:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cherrypick_annotations:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_annotations"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cherrypick_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
path: "../../cherrypick_generator"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
cli_launcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cli_launcher
|
||||
sha256: "67d89e0a1c07b103d1253f6b953a43d3f502ee36805c8cfc21196282c9ddf177"
|
||||
sha256: "17d2744fb9a254c49ec8eda582536abe714ea0131533e24389843a4256f82eac"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.2"
|
||||
version: "0.3.2+1"
|
||||
cli_util:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -218,10 +218,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: code_builder
|
||||
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
|
||||
sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.10.1"
|
||||
version: "4.11.1"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -234,10 +234,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: conventional_commit
|
||||
sha256: fad254feb6fb8eace2be18855176b0a4b97e0d50e416ff0fe590d5ba83735d34
|
||||
sha256: c40b1b449ce2a63fa2ce852f35e3890b1e182f5951819934c0e4a66254bc0dc3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.1"
|
||||
version: "0.6.1+1"
|
||||
convert:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -250,18 +250,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cross_file
|
||||
sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670"
|
||||
sha256: "701dcfc06da0882883a2657c445103380e53e647060ad8d9dfb710c100996608"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.4+2"
|
||||
version: "0.3.5+1"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.6"
|
||||
version: "3.0.7"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -274,10 +274,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dart_style
|
||||
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac"
|
||||
sha256: a9c30492da18ff84efe2422ba2d319a89942d93e58eb0b73d32abe822ef54b7b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
version: "3.1.3"
|
||||
dartz:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -290,10 +290,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: dio
|
||||
sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9
|
||||
sha256: b9d46faecab38fc8cc286f80bc4d61a3bb5d4ac49e51ed877b4d6706efe57b25
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.9.0"
|
||||
version: "5.9.1"
|
||||
dio_web_adapter:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -314,10 +314,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ffi
|
||||
sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6"
|
||||
sha256: d07d37192dbf97461359c1518788f203b0c9102cfd2c35a716b823741219542c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
version: "2.1.5"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -351,10 +351,10 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_lints
|
||||
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
|
||||
sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "6.0.0"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
@@ -369,18 +369,18 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: freezed
|
||||
sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c"
|
||||
sha256: "13065f10e135263a4f5a4391b79a8efc5fb8106f8dd555a9e49b750b45393d77"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.8"
|
||||
version: "3.2.3"
|
||||
freezed_annotation:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: freezed_annotation
|
||||
sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2
|
||||
sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
version: "3.1.0"
|
||||
frontend_server_client:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -413,14 +413,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.3.4"
|
||||
hotreloader:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: hotreloader
|
||||
sha256: bc167a1163807b03bada490bfe2df25b0d744df359227880220a5cbd04e5734b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.3.0"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.0"
|
||||
version: "1.6.0"
|
||||
http_multi_server:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -437,14 +445,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
intl:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: intl
|
||||
sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.19.0"
|
||||
io:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -453,16 +453,8 @@ 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
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: json_annotation
|
||||
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
|
||||
@@ -473,42 +465,50 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: json_serializable
|
||||
sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c
|
||||
sha256: c5b2ee75210a0f263c6c7b9eeea80553dbae96ea1bf57f02484e806a3ffdffa3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.9.5"
|
||||
version: "6.11.2"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker
|
||||
sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
|
||||
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.0.9"
|
||||
version: "11.0.2"
|
||||
leak_tracker_flutter_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_flutter_testing
|
||||
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
|
||||
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.9"
|
||||
version: "3.0.10"
|
||||
leak_tracker_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_testing
|
||||
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
|
||||
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
lean_builder:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lean_builder
|
||||
sha256: "4f3d70c34c52cc5034e8cc6f53d35aa3a32fb373b78fb4c29cf45cd1dcf06942"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.5"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lints
|
||||
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
|
||||
sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.1"
|
||||
version: "6.0.0"
|
||||
logging:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -537,18 +537,18 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: melos
|
||||
sha256: "3f3ab3f902843d1e5a1b1a4dd39a4aca8ba1056f2d32fd8995210fa2843f646f"
|
||||
sha256: "4280dc46bd5b741887cce1e67e5c1a6aaf3c22310035cf5bd33dceeeda62ed22"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.3.2"
|
||||
version: "6.3.3"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
|
||||
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.16.0"
|
||||
version: "1.17.0"
|
||||
mime:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -561,10 +561,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: mustache_template
|
||||
sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c
|
||||
sha256: "4326d0002ff58c74b9486990ccbdab08157fca3c996fe9e197aff9d61badf307"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "2.0.3"
|
||||
nested:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -601,18 +601,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_android
|
||||
sha256: d0d310befe2c8ab9e7f393288ccbb11b60c019c6b5afc21973eeee4dda2b35e9
|
||||
sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.17"
|
||||
version: "2.2.22"
|
||||
path_provider_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_foundation
|
||||
sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942"
|
||||
sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.1"
|
||||
version: "2.5.1"
|
||||
path_provider_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -637,14 +637,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
petitparser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: petitparser
|
||||
sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.0.2"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -665,10 +657,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pool
|
||||
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
|
||||
sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.1"
|
||||
version: "1.5.2"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -689,10 +681,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: protobuf
|
||||
sha256: "579fe5557eae58e3adca2e999e38f02441d8aa908703854a9e0a0f47fa857731"
|
||||
sha256: "75ec242d22e950bdcc79ee38dd520ce4ee0bc491d7fadc4ea47694604d22bf06"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.0"
|
||||
version: "6.0.0"
|
||||
provider:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -713,10 +705,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pub_updater
|
||||
sha256: "54e8dc865349059ebe7f163d6acce7c89eb958b8047e6d6e80ce93b13d7c9e60"
|
||||
sha256: "739a0161d73a6974c0675b864fb0cf5147305f7b077b7f03a58fa7a9ab3e7e7d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.4.0"
|
||||
version: "0.5.0"
|
||||
pubspec_parse:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -729,26 +721,26 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: retrofit
|
||||
sha256: "84d70114a5b6bae5f4c1302335f9cb610ebeb1b02023d5e7e87697aaff52926a"
|
||||
sha256: "0f629ed26b2c48c66fe54bd548313c6fdf7955be18bff37e08a46dd3f97f8eaf"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.6.0"
|
||||
version: "4.9.2"
|
||||
retrofit_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: retrofit_generator
|
||||
sha256: e48c5a7ac362621b74976c64c540500dc7a54b8b5b074616a96a4854a2e5bb5b
|
||||
sha256: fed2c4e4ed6dab084c00d25c739988aa3cec1acd2b168771136188cced8d967d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "9.6.0"
|
||||
version: "10.2.1"
|
||||
share_plus:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: share_plus
|
||||
sha256: d7dc0630a923883c6328ca31b89aa682bacbf2f8304162d29f7c6aaff03a27a1
|
||||
sha256: "14c8860d4de93d3a7e53af51bff479598c4e999605290756bbbe45cf65b37840"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "11.1.0"
|
||||
version: "12.0.1"
|
||||
share_plus_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -782,18 +774,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_gen
|
||||
sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b"
|
||||
sha256: "1d562a3c1f713904ebbed50d2760217fd8a51ca170ac4b05b0db490699dbac17"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "4.2.0"
|
||||
source_helper:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_helper
|
||||
sha256: a447acb083d3a5ef17f983dd36201aeea33fedadb3228fa831f2f0c92f0f3aca
|
||||
sha256: "6a3c6cc82073a8797f8c4dc4572146114a39652851c157db37e964d9c7038723"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.7"
|
||||
version: "1.3.8"
|
||||
source_span:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -802,14 +794,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.10.1"
|
||||
sprintf:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sprintf
|
||||
sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.0"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -846,49 +830,49 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: talker
|
||||
sha256: "2d742b54e5cda58b7d386cd2d95088c3429ef273b2a0869dec552fe02601367a"
|
||||
sha256: "4160d27f4da6d87f016212bbe6abfb15c8954b72726a0f154d72f77664c48b8c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "5.1.13"
|
||||
talker_bloc_logger:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: talker_bloc_logger
|
||||
sha256: "7752ca8a0b2eba487c8c189ca2390ebfcdaa4f7b10eda27587e5067e4427e7cd"
|
||||
sha256: d69cfaf3b7294babc1f2b0e297fb33b885cc859a4ceae5393bd39da9eb93e537
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "5.1.13"
|
||||
talker_cherrypick_logger:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../talker_cherrypick_logger"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.1"
|
||||
version: "3.0.2"
|
||||
talker_dio_logger:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: talker_dio_logger
|
||||
sha256: "20cc3bc9820fa73040f23e27d5d86462e590ddf02c43d0a801c56bf5ecc68922"
|
||||
sha256: c5769f4b1ee6fcc1a0670cdfc7f3253016a1090b583aeb70e3ccd73f479970a8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "5.1.13"
|
||||
talker_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: talker_flutter
|
||||
sha256: d249fa16936a08fe5c4fb9e2b9b122fdcbaef6be9c4dcf61e448d0b76f3179f1
|
||||
sha256: "6a807972565dc7d5bacfb6a980efa0f766bfdbacac5660adf150aa386c440052"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "5.1.13"
|
||||
talker_logger:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: talker_logger
|
||||
sha256: "4f06d46db664c11cf4d629378da661f2c75aee629e3ef898dbc3cf44a0c41cd7"
|
||||
sha256: ed5f8434f17f3988548abc5f617b88e7a5d2d61d7a975e7c12eee75755848aa8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
version: "5.1.13"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -901,10 +885,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: test_api
|
||||
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
|
||||
sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.4"
|
||||
version: "0.7.7"
|
||||
timing:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -925,10 +909,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_linux
|
||||
sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935"
|
||||
sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.1"
|
||||
version: "3.2.2"
|
||||
url_launcher_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -941,50 +925,50 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_web
|
||||
sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2"
|
||||
sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.1"
|
||||
version: "2.4.2"
|
||||
url_launcher_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_windows
|
||||
sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77"
|
||||
sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.4"
|
||||
version: "3.1.5"
|
||||
uuid:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: uuid
|
||||
sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff
|
||||
sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.5.1"
|
||||
version: "4.5.2"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_math
|
||||
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
version: "2.2.0"
|
||||
vm_service:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
|
||||
sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "15.0.0"
|
||||
version: "15.0.2"
|
||||
watcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: watcher
|
||||
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
|
||||
sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.3"
|
||||
version: "1.2.1"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1013,10 +997,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: win32
|
||||
sha256: daf97c9d80197ed7b619040e86c8ab9a9dad285e7671ee7390f9180cc828a51e
|
||||
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.10.1"
|
||||
version: "5.15.0"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1025,14 +1009,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
xml:
|
||||
xxh3:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xml
|
||||
sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226
|
||||
name: xxh3
|
||||
sha256: "399a0438f5d426785723c99da6b16e136f4953fb1e9db0bf270bd41dd4619916"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.5.0"
|
||||
version: "1.2.0"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1045,10 +1029,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yaml_edit
|
||||
sha256: fb38626579fb345ad00e674e2af3a5c9b0cc4b9bfb8fd7f7ff322c7c9e62aef5
|
||||
sha256: ec709065bb2c911b336853b67f3732dd13e0336bd065cc2f1061d7610ddf45e3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.2"
|
||||
version: "2.2.3"
|
||||
sdks:
|
||||
dart: ">=3.7.0-0 <4.0.0"
|
||||
flutter: ">=3.27.0"
|
||||
dart: ">=3.10.0 <4.0.0"
|
||||
flutter: ">=3.38.0"
|
||||
|
||||
@@ -5,21 +5,20 @@ publish_to: 'none'
|
||||
version: 1.0.0+1
|
||||
|
||||
environment:
|
||||
sdk: ">=3.6.0 <4.0.0"
|
||||
sdk: ">=3.9.0 <4.0.0"
|
||||
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
cherrypick:
|
||||
path: ../../cherrypick
|
||||
cherrypick_annotations:
|
||||
path: ../../cherrypick_annotations
|
||||
cherrypick: any
|
||||
cherrypick_annotations: ^4.0.0-dev.0
|
||||
|
||||
dio: ^5.4.0
|
||||
retrofit: ^4.0.3
|
||||
freezed_annotation: ^2.4.4
|
||||
freezed_annotation: ^3.0.0
|
||||
json_annotation: ^4.9.0
|
||||
dartz: ^0.10.1
|
||||
flutter_bloc: ^9.1.1
|
||||
auto_route: ^10.1.0+1
|
||||
@@ -28,8 +27,7 @@ dependencies:
|
||||
cupertino_icons: ^1.0.8
|
||||
|
||||
talker_flutter: ^5.0.0
|
||||
talker_cherrypick_logger:
|
||||
path: ../../talker_cherrypick_logger
|
||||
talker_cherrypick_logger: any
|
||||
talker_dio_logger: ^5.0.0
|
||||
talker_bloc_logger: ^5.0.0
|
||||
|
||||
@@ -37,16 +35,15 @@ dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
|
||||
flutter_lints: ^5.0.0
|
||||
flutter_lints: ^6.0.0
|
||||
|
||||
build_runner: 2.4.15
|
||||
cherrypick_generator:
|
||||
path: ../../cherrypick_generator
|
||||
build_runner: ^2.5.0
|
||||
cherrypick_generator: ^4.0.0-dev.0
|
||||
|
||||
json_serializable: ^6.9.0
|
||||
retrofit_generator: ^9.1.5
|
||||
retrofit_generator: ^10.0.5
|
||||
auto_route_generator: ^10.0.1
|
||||
freezed: ^2.5.8
|
||||
freezed: ^3.0.0
|
||||
melos: ^6.3.2
|
||||
|
||||
flutter:
|
||||
|
||||
@@ -16,7 +16,8 @@ scripts:
|
||||
clean_all:
|
||||
run: |
|
||||
melos clean
|
||||
melos exec -- rm -rf lib/**.g.dart lib/generated/
|
||||
melos exec -- rm -rf lib/**.g.dart lib/**/**.g.dart lib/generated/
|
||||
melos exec -- rm -rf .dart_tool build pubspec_overrides.yaml
|
||||
description: |
|
||||
Очищает build артефакты flutter и сгенерированный код во всех пакетах.
|
||||
|
||||
|
||||
2
openspec/changes/cherrypick-system-spec/.openspec.yaml
Normal file
2
openspec/changes/cherrypick-system-spec/.openspec.yaml
Normal file
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-02-27
|
||||
40
openspec/changes/cherrypick-system-spec/design.md
Normal file
40
openspec/changes/cherrypick-system-spec/design.md
Normal file
@@ -0,0 +1,40 @@
|
||||
## Context
|
||||
|
||||
CherryPick — монорепозиторий DI‑экосистемы для Dart/Flutter, включающий ядро рантайма, аннотации, генератор и Flutter‑интеграцию, а также адаптер логирования для Talker. Требуется системная спецификация модулей и их контрактов на русском языке.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Зафиксировать архитектурные границы и контракты модулей.
|
||||
- Согласовать терминологию и жизненные циклы ключевых сущностей.
|
||||
- Дать проверяемые требования с однозначными сценариями.
|
||||
|
||||
**Non-Goals:**
|
||||
- Изменение или рефакторинг кода.
|
||||
- Детализация низкоуровневых алгоритмов генератора.
|
||||
- Документация внешних библиотек (Flutter, Talker).
|
||||
|
||||
## Decisions
|
||||
|
||||
- Разбить спецификацию по четырем capability: `di-runtime`, `annotations-and-codegen`, `flutter-integration`, `talker-logging-adapter`.
|
||||
- Все требования формулировать нормативно (MUST) и снабжать сценариями WHEN/THEN.
|
||||
- Описывать сущности, жизненный цикл, ошибки и точки расширения в каждом capability.
|
||||
|
||||
**Альтернативы:**
|
||||
- Единый монолитный spec.md: отклонено из-за ухудшения навигации и поддержки.
|
||||
- Использовать SHOULD/MAY: отклонено для уменьшения двусмысленности.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Risk] Спецификация может расходиться с фактическим поведением кода → Mitigation: привязка требований к публичным API и README, дальнейшая валидация при реализации.
|
||||
- [Risk] Перекрывающиеся требования между capability → Mitigation: строгие границы и минимальный повтор.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
- Спецификация вводится как документ без влияния на runtime.
|
||||
- При необходимости последующих изменений — через отдельные change‑запросы OpenSpec.
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Нужно ли фиксировать требования по производительности (O(1) lookup) как отдельный раздел?
|
||||
- Нужны ли отдельные сценарии для edge‑cases (например, singleton + params)?
|
||||
23
openspec/changes/cherrypick-system-spec/proposal.md
Normal file
23
openspec/changes/cherrypick-system-spec/proposal.md
Normal file
@@ -0,0 +1,23 @@
|
||||
## Why
|
||||
|
||||
CherryPick is a multi-package DI ecosystem. A system-level spec will make module boundaries, expected behaviors, and integration contracts explicit for contributors and downstream users.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Define system specifications for the core DI runtime, annotations/codegen, Flutter integration, and Talker logging adapter.
|
||||
- Document expected behaviors, inputs, and outputs for each module and its public integration points.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `di-runtime`: Core dependency injection runtime (scopes, modules, bindings, resolution, lifecycle).
|
||||
- `annotations-and-codegen`: Annotation vocabulary and code generation behavior for DI wiring.
|
||||
- `flutter-integration`: Flutter-specific provider and scope access integration.
|
||||
- `talker-logging-adapter`: Observer adapter that routes DI events to Talker.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
## Impact
|
||||
|
||||
- Documentation and contributor guidance for module behaviors.
|
||||
- Clarifies runtime and codegen expectations for users and maintainers.
|
||||
@@ -0,0 +1,88 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сущности аннотаций
|
||||
Пакет аннотаций MUST предоставлять аннотации `@module`, `@provide`, `@instance`, `@singleton`, `@named`, `@params`, `@inject`, `@injectable`, `@scope`.
|
||||
|
||||
#### Scenario: Наличие аннотаций
|
||||
- **WHEN** разработчик импортирует пакет аннотаций
|
||||
- **THEN** все перечисленные аннотации доступны для использования
|
||||
|
||||
### Requirement: Семантика module/provide/instance/singleton
|
||||
Генератор MUST трактовать аннотации `@module`, `@provide`, `@instance`, `@singleton` как источники bindings и жизненного цикла.
|
||||
|
||||
#### Scenario: Генерация bindings для @module
|
||||
- **WHEN** класс помечен `@module` и содержит методы с `@provide`
|
||||
- **THEN** сгенерированный модуль регистрирует эти методы как DI‑bindings
|
||||
|
||||
#### Scenario: Singleton vs Instance
|
||||
- **WHEN** метод помечен `@singleton`
|
||||
- **THEN** binding создается как singleton
|
||||
- **WHEN** метод помечен `@instance` или не имеет lifecycle‑аннотации
|
||||
- **THEN** binding создается как factory/instance
|
||||
|
||||
#### Scenario: Обязательность provide/instance
|
||||
- **WHEN** публичный метод в `@module` не помечен `@instance` или `@provide`
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
### Requirement: Инъекция полей
|
||||
Генератор MUST создавать миксин для класса с `@injectable` и инъектировать все поля, помеченные `@inject`.
|
||||
|
||||
#### Scenario: Инъекция полей без квалификаторов
|
||||
- **WHEN** поле помечено `@inject`
|
||||
- **THEN** миксин вызывает resolve для типа поля
|
||||
|
||||
#### Scenario: Инъекция с @named и @scope
|
||||
- **WHEN** поле помечено `@inject` и `@named` или `@scope`
|
||||
- **THEN** миксин использует соответствующий named/scope при резолве
|
||||
|
||||
### Requirement: Параметры выполнения
|
||||
`@params` MUST обозначать runtime‑параметры, которые передаются при резолве.
|
||||
|
||||
#### Scenario: Параметризованный provider
|
||||
- **WHEN** provider‑метод имеет параметр с `@params`
|
||||
- **THEN** генерируется binding с параметрами и соответствующий API резолва
|
||||
|
||||
#### Scenario: Запрет @params с @instance
|
||||
- **WHEN** `@params` используется вместе с `@instance`
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
### Requirement: Поддержка async
|
||||
Генератор MUST корректно обрабатывать `Future<T>` и асинхронные зависимости.
|
||||
|
||||
#### Scenario: Async provider
|
||||
- **WHEN** provider возвращает `Future<T>`
|
||||
- **THEN** генерируется async‑binding и используется `resolveAsync`
|
||||
|
||||
### Requirement: Обработка ошибок и валидация
|
||||
Генератор MUST валидировать корректность применения аннотаций и сообщать об ошибках на стадии build.
|
||||
|
||||
#### Scenario: Некорректная цель аннотации
|
||||
- **WHEN** аннотация применена к неподдерживаемому элементу
|
||||
- **THEN** генератор завершает сборку с понятной ошибкой
|
||||
|
||||
#### Scenario: Взаимоисключающие аннотации
|
||||
- **WHEN** метод помечен одновременно `@instance` и `@provide`
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
#### Scenario: Требования к @named на provider-методе
|
||||
- **WHEN** `@named` на provider-методе использует пустую строку или некорректный идентификатор
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
#### Scenario: Пустой @named на inject-поле
|
||||
- **WHEN** `@named('')` указан на поле с `@inject`
|
||||
- **THEN** генератор трактует поле как безымянный резолв (без параметра `named`)
|
||||
|
||||
#### Scenario: Валидность @module
|
||||
- **WHEN** класс с `@module` не имеет публичных методов
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
#### Scenario: Валидность @injectable полей
|
||||
- **WHEN** поле с `@inject` не является `final`
|
||||
- **THEN** генератор завершает сборку с ошибкой валидации
|
||||
|
||||
### Requirement: Точки расширения
|
||||
Система MUST позволять расширять DI‑контракт через новые модули/классы без изменения генератора, используя стандартные аннотации.
|
||||
|
||||
#### Scenario: Новый модуль
|
||||
- **WHEN** разработчик добавляет новый класс `@module`
|
||||
- **THEN** генератор автоматически включает его в DI‑регистрации
|
||||
137
openspec/changes/cherrypick-system-spec/specs/di-runtime/spec.md
Normal file
137
openspec/changes/cherrypick-system-spec/specs/di-runtime/spec.md
Normal file
@@ -0,0 +1,137 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сущности ядра DI
|
||||
Ядро DI MUST определять сущности `Scope`, `Module`, `Binding`, `BindingResolver`, `Disposable`, `CherryPickObserver` и их роли.
|
||||
|
||||
#### Scenario: Декларация базовых сущностей
|
||||
- **WHEN** разработчик использует публичный API ядра
|
||||
- **THEN** сущности `Scope`, `Module`, `Binding`, `Disposable`, `CherryPickObserver` доступны и описывают контракт DI
|
||||
|
||||
### Requirement: Жизненный цикл Scope
|
||||
`Scope` MUST поддерживать жизненный цикл открытия, использования и корректного закрытия с освобождением ресурсов.
|
||||
|
||||
#### Scenario: Открытие root scope
|
||||
- **WHEN** вызывается открытие root scope
|
||||
- **THEN** создается корневой контейнер для регистраций и резолва
|
||||
|
||||
#### Scenario: Открытие named subscope
|
||||
- **WHEN** открывается именованный subscope
|
||||
- **THEN** subscope наследует bindings родителя и может переопределять зависимости
|
||||
|
||||
#### Scenario: Закрытие subscope
|
||||
- **WHEN** вызывается закрытие subscope
|
||||
- **THEN** subscope удаляется из дерева, а связанные ресурсы освобождаются
|
||||
|
||||
#### Scenario: Путь scope и разделитель
|
||||
- **WHEN** вызывается `CherryPick.openScope(scopeName: ..., separator: ...)` с иерархическим путем
|
||||
- **THEN** создается цепочка subscopes по каждому сегменту пути
|
||||
|
||||
#### Scenario: Пустой scopeName
|
||||
- **WHEN** вызывается `CherryPick.openScope(scopeName: '')`
|
||||
- **THEN** возвращается root scope
|
||||
|
||||
### Requirement: Установка и удаление модулей
|
||||
`Scope` MUST поддерживать установку и удаление `Module`, а их bindings MUST становиться доступными сразу после установки.
|
||||
|
||||
#### Scenario: Установка модуля
|
||||
- **WHEN** модуль установлен в scope
|
||||
- **THEN** его bindings доступны для resolve/tryResolve
|
||||
|
||||
#### Scenario: Сброс модулей
|
||||
- **WHEN** модули сброшены
|
||||
- **THEN** bindings модулей не доступны для резолва в этом scope
|
||||
|
||||
### Requirement: Типы bindings
|
||||
`Binding` MUST поддерживать прямые инстансы, синхронные провайдеры, асинхронные провайдеры и провайдеры с параметрами, а также именованные bindings.
|
||||
|
||||
#### Scenario: Именованные bindings
|
||||
- **WHEN** зарегистрированы два bindings одного типа с разными именами
|
||||
- **THEN** resolve с указанным именем возвращает соответствующую реализацию
|
||||
|
||||
#### Scenario: Параметризованный provider
|
||||
- **WHEN** binding зарегистрирован с провайдером, принимающим параметры
|
||||
- **THEN** resolve с параметрами использует переданные аргументы для создания экземпляра
|
||||
|
||||
### Requirement: Семантика резолва и fallback
|
||||
Резолв MUST искать зависимость в текущем scope и, при отсутствии, подниматься к родительским scope.
|
||||
|
||||
#### Scenario: Fallback к родителю
|
||||
- **WHEN** зависимость отсутствует в текущем scope, но есть в родительском
|
||||
- **THEN** резолв выполняется через родительский binding
|
||||
|
||||
### Requirement: Синхронный и асинхронный резолв
|
||||
`Scope` MUST предоставлять синхронный и асинхронный резолв и их nullable‑варианты.
|
||||
|
||||
#### Scenario: Resolve (sync)
|
||||
- **WHEN** вызывается `resolve<T>()` для существующей зависимости
|
||||
- **THEN** возвращается экземпляр или выбрасывается ошибка при отсутствии
|
||||
|
||||
#### Scenario: TryResolve (sync)
|
||||
- **WHEN** вызывается `tryResolve<T>()` для отсутствующей зависимости
|
||||
- **THEN** возвращается `null` без исключения
|
||||
|
||||
#### Scenario: Resolve (async)
|
||||
- **WHEN** вызывается `resolveAsync<T>()` для зависимости с async‑провайдером
|
||||
- **THEN** возвращается `Future<T>` с экземпляром
|
||||
|
||||
#### Scenario: TryResolve (async)
|
||||
- **WHEN** вызывается `tryResolveAsync<T>()` для отсутствующей зависимости
|
||||
- **THEN** возвращается `null` без исключения
|
||||
|
||||
### Requirement: Ошибки несоответствия sync/async
|
||||
Резолв MUST выбрасывать ошибки при несоответствии sync/async режима.
|
||||
|
||||
#### Scenario: Синхронный резолв для async‑binding
|
||||
- **WHEN** binding зарегистрирован как async‑инстанс или async‑provider, а вызывается `resolve<T>()` или `tryResolve<T>()`
|
||||
- **THEN** выбрасывается ошибка с указанием использовать async‑резолв
|
||||
|
||||
### Requirement: Управление Disposable
|
||||
`Scope` MUST отслеживать экземпляры, реализующие `Disposable`, и вызывать `dispose()` при закрытии scope.
|
||||
|
||||
#### Scenario: Автоматическое освобождение
|
||||
- **WHEN** scope закрывается
|
||||
- **THEN** все `Disposable` в scope и дочерних scope освобождаются
|
||||
|
||||
### Requirement: Детекция циклов зависимостей
|
||||
Ядро DI MUST поддерживать локальную и глобальную детекцию циклов.
|
||||
|
||||
#### Scenario: Локальный цикл
|
||||
- **WHEN** локальная детекция включена и резолв обнаруживает цикл
|
||||
- **THEN** резолв завершается ошибкой цикла
|
||||
|
||||
#### Scenario: Глобальный цикл
|
||||
- **WHEN** глобальная детекция включена и цикл пересекает scope
|
||||
- **THEN** резолв завершается ошибкой цикла
|
||||
|
||||
### Requirement: Наблюдатель событий (Observer)
|
||||
Ядро DI MUST предоставлять наблюдателя, получающего события регистрации, резолва, ошибок, lifecycle и диагностики.
|
||||
|
||||
#### Scenario: События lifecycle
|
||||
- **WHEN** scope открывается, модули устанавливаются и зависимости резолвятся
|
||||
- **THEN** observer получает соответствующие уведомления
|
||||
|
||||
### Requirement: Ошибки и сообщения об ошибках
|
||||
При критических сбоях резолва ядро MUST выбрасывать ошибку с понятным сообщением. Для отсутствующей зависимости `tryResolve`/`tryResolveAsync` MUST возвращать `null` без исключения; ошибки выполнения резолва (например, цикл, sync/async mismatch, отсутствие обязательных params) MAY быть проброшены.
|
||||
|
||||
#### Scenario: Ошибка отсутствующей зависимости
|
||||
- **WHEN** вызывается `resolve<T>()` для незарегистрированной зависимости
|
||||
- **THEN** выбрасывается ошибка с сообщением о невозможности резолва
|
||||
|
||||
#### Scenario: Ошибка цикла
|
||||
- **WHEN** обнаружен цикл зависимостей
|
||||
- **THEN** выбрасывается ошибка с указанием цепочки
|
||||
|
||||
#### Scenario: Отсутствующие параметры для параметризованного binding
|
||||
- **WHEN** binding зарегистрирован с `toProvideWithParams`, но резолв вызывается без `params`
|
||||
- **THEN** выбрасывается ошибка о необходимости передать параметры
|
||||
|
||||
### Requirement: Точки расширения
|
||||
Ядро DI MUST предоставлять точки расширения через пользовательский `Module` и `CherryPickObserver`.
|
||||
|
||||
#### Scenario: Пользовательский Module
|
||||
- **WHEN** разработчик создает свой `Module`
|
||||
- **THEN** он может зарегистрировать bindings и контролировать регистрацию
|
||||
|
||||
#### Scenario: Пользовательский Observer
|
||||
- **WHEN** разработчик передает кастомный observer
|
||||
- **THEN** он получает все DI‑события и может интегрировать внешние логеры/метрики
|
||||
@@ -0,0 +1,58 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сущности Flutter‑интеграции
|
||||
Flutter‑интеграция MUST предоставлять `CherryPickProvider` как `InheritedWidget` для доступа к DI‑scope в дереве виджетов.
|
||||
|
||||
#### Scenario: Публичная сущность провайдера
|
||||
- **WHEN** разработчик импортирует Flutter‑пакет
|
||||
- **THEN** `CherryPickProvider` доступен и может быть помещен в дерево виджетов
|
||||
|
||||
### Requirement: Жизненный цикл провайдера
|
||||
`CherryPickProvider` MUST быть статическим проводником к scope и не владеть их жизненным циклом.
|
||||
|
||||
#### Scenario: Stateless поведение
|
||||
- **WHEN** `CherryPickProvider` пересоздается с тем же child
|
||||
- **THEN** он не инициирует изменения DI‑состояния и не уведомляет зависимые виджеты
|
||||
|
||||
### Requirement: Доступ к root scope
|
||||
Провайдер MUST предоставлять доступ к root scope через `openRootScope`.
|
||||
|
||||
#### Scenario: Открытие root scope
|
||||
- **WHEN** вызывается `openRootScope`
|
||||
- **THEN** возвращается root scope DI‑контейнера
|
||||
|
||||
### Requirement: Доступ к subscope
|
||||
Провайдер MUST предоставлять доступ к subscope через `openSubScope` с именем и разделителем.
|
||||
|
||||
#### Scenario: Открытие named subscope
|
||||
- **WHEN** вызывается `openSubScope` с именем
|
||||
- **THEN** возвращается subscope с указанным именем
|
||||
|
||||
#### Scenario: Пустое имя scope
|
||||
- **WHEN** вызывается `openSubScope` без имени
|
||||
- **THEN** возвращается root scope
|
||||
|
||||
### Requirement: Доступ через BuildContext
|
||||
`CherryPickProvider.of(context)` MUST возвращать провайдер из ближайшего ancestor.
|
||||
|
||||
#### Scenario: Успешный lookup
|
||||
- **WHEN** вызов происходит внутри поддерева провайдера
|
||||
- **THEN** возвращается экземпляр провайдера
|
||||
|
||||
#### Scenario: Ошибка lookup
|
||||
- **WHEN** вызов происходит вне поддерева провайдера
|
||||
- **THEN** в debug‑режиме происходит assertion‑ошибка
|
||||
|
||||
### Requirement: Ошибки и сообщения
|
||||
При отсутствии провайдера в дереве MUST быть диагностируемая ошибка.
|
||||
|
||||
#### Scenario: Диагностика отсутствия провайдера
|
||||
- **WHEN** `CherryPickProvider.of(context)` не находит провайдер
|
||||
- **THEN** в debug‑режиме сообщение assertion указывает на отсутствие провайдера
|
||||
|
||||
### Requirement: Точки расширения
|
||||
Flutter‑интеграция MUST позволять использовать собственные DI‑scope стратегии поверх `CherryPickProvider`.
|
||||
|
||||
#### Scenario: Кастомная организация scope
|
||||
- **WHEN** приложение использует собственные правила создания subscope
|
||||
- **THEN** провайдер остается совместимым и не ограничивает стратегию
|
||||
@@ -0,0 +1,47 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сущность адаптера логирования
|
||||
Адаптер MUST предоставлять `TalkerCherryPickObserver`, реализующий `CherryPickObserver`.
|
||||
|
||||
#### Scenario: Доступность адаптера
|
||||
- **WHEN** разработчик импортирует пакет адаптера
|
||||
- **THEN** `TalkerCherryPickObserver` доступен для использования
|
||||
|
||||
### Requirement: Жизненный цикл наблюдателя
|
||||
Наблюдатель MUST подключаться при создании scope и работать в течение жизненного цикла этого scope.
|
||||
|
||||
#### Scenario: Подключение наблюдателя
|
||||
- **WHEN** observer передан при открытии scope
|
||||
- **THEN** все DI‑события в scope направляются в Talker
|
||||
|
||||
### Requirement: Маппинг уровней логирования
|
||||
Адаптер MUST маршрутизировать DI‑события в Talker с корректными уровнями (info/warning/verbose/handle).
|
||||
|
||||
#### Scenario: Диагностика
|
||||
- **WHEN** DI‑ядро генерирует диагностическое событие
|
||||
- **THEN** адаптер логирует его как verbose
|
||||
|
||||
#### Scenario: Ошибка резолва
|
||||
- **WHEN** DI‑ядро генерирует ошибку
|
||||
- **THEN** адаптер логирует ее через `handle` и включает stack trace при наличии
|
||||
|
||||
### Requirement: Ненавязчивость поведения
|
||||
Адаптер MUST быть наблюдателем и не изменять DI‑поведение, жизненный цикл или кэширование.
|
||||
|
||||
#### Scenario: Разрешение с адаптером
|
||||
- **WHEN** адаптер подключен
|
||||
- **THEN** резолв и поведение DI не изменяются, кроме появления логов
|
||||
|
||||
### Requirement: Ошибки логирования
|
||||
Адаптер MUST передавать ошибки логирования как есть и не содержит собственной обработки исключений.
|
||||
|
||||
#### Scenario: Исключение в Talker
|
||||
- **WHEN** Talker выбрасывает исключение при логировании
|
||||
- **THEN** исключение пробрасывается вызывающему коду
|
||||
|
||||
### Requirement: Точки расширения
|
||||
Адаптер MUST позволять использовать пользовательские настройки Talker без изменения адаптера.
|
||||
|
||||
#### Scenario: Кастомная конфигурация Talker
|
||||
- **WHEN** пользователь передает кастомный Talker
|
||||
- **THEN** адаптер использует переданную конфигурацию для всех DI‑событий
|
||||
28
openspec/changes/cherrypick-system-spec/tasks.md
Normal file
28
openspec/changes/cherrypick-system-spec/tasks.md
Normal file
@@ -0,0 +1,28 @@
|
||||
## 1. Системная структура спецификации
|
||||
|
||||
- [x] 1.1 Проверить корректность capability‑разделения и согласованность терминов
|
||||
- [x] 1.2 Уточнить cross‑cutting требования (терминология, общие lifecycle‑понятия)
|
||||
|
||||
## 2. DI Runtime (ядро)
|
||||
|
||||
- [x] 2.1 Сверить требования по сущностям и lifecycle со структурой кода `cherrypick`
|
||||
- [x] 2.2 Уточнить сценарии ошибок и сообщений об ошибках
|
||||
- [x] 2.3 Проверить сценарии расширения (Module/Observer) на полноту
|
||||
|
||||
## 3. Аннотации и генератор
|
||||
|
||||
- [x] 3.1 Проверить полноту словаря аннотаций и их назначений
|
||||
- [x] 3.2 Сверить требования по codegen (module/field injection/params/async)
|
||||
- [x] 3.3 Уточнить сценарии валидации и типовых ошибок генератора
|
||||
|
||||
## 4. Flutter‑интеграция
|
||||
|
||||
- [x] 4.1 Сверить требования `CherryPickProvider` с фактическим API
|
||||
- [x] 4.2 Уточнить сценарии lookup и диагностических ошибок
|
||||
- [x] 4.3 Проверить корректность заявленных точек расширения
|
||||
|
||||
## 5. Talker‑адаптер
|
||||
|
||||
- [x] 5.1 Сверить маппинг уровней логирования с фактическим поведением
|
||||
- [x] 5.2 Уточнить поведение при ошибках логирования
|
||||
- [x] 5.3 Проверить сценарии ненавязчивости и расширения
|
||||
62
pubspec.lock
62
pubspec.lock
@@ -37,18 +37,18 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: checked_yaml
|
||||
sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff
|
||||
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.3"
|
||||
version: "2.0.4"
|
||||
cli_launcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cli_launcher
|
||||
sha256: "67d89e0a1c07b103d1253f6b953a43d3f502ee36805c8cfc21196282c9ddf177"
|
||||
sha256: "17d2744fb9a254c49ec8eda582536abe714ea0131533e24389843a4256f82eac"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.2"
|
||||
version: "0.3.2+1"
|
||||
cli_util:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -57,14 +57,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.4.2"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: clock
|
||||
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -77,10 +69,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: conventional_commit
|
||||
sha256: fad254feb6fb8eace2be18855176b0a4b97e0d50e416ff0fe590d5ba83735d34
|
||||
sha256: c40b1b449ce2a63fa2ce852f35e3890b1e182f5951819934c0e4a66254bc0dc3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.1"
|
||||
version: "0.6.1+1"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -109,10 +101,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.0"
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -121,14 +113,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
intl:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: intl
|
||||
sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.19.0"
|
||||
io:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -141,10 +125,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: json_annotation
|
||||
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
|
||||
sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.9.0"
|
||||
version: "4.10.0"
|
||||
lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -157,26 +141,26 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: melos
|
||||
sha256: "3f3ab3f902843d1e5a1b1a4dd39a4aca8ba1056f2d32fd8995210fa2843f646f"
|
||||
sha256: "4280dc46bd5b741887cce1e67e5c1a6aaf3c22310035cf5bd33dceeeda62ed22"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.3.2"
|
||||
version: "6.3.3"
|
||||
meta:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: meta
|
||||
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
|
||||
sha256: "9f29b9bcc8ee287b1a31e0d01be0eae99a930dbffdaecf04b3f3d82a969f296f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.17.0"
|
||||
version: "1.18.1"
|
||||
mustache_template:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: mustache_template
|
||||
sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c
|
||||
sha256: "4326d0002ff58c74b9486990ccbdab08157fca3c996fe9e197aff9d61badf307"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "2.0.3"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -197,10 +181,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pool
|
||||
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
|
||||
sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.1"
|
||||
version: "1.5.2"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -229,10 +213,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pub_updater
|
||||
sha256: "54e8dc865349059ebe7f163d6acce7c89eb958b8047e6d6e80ce93b13d7c9e60"
|
||||
sha256: "739a0161d73a6974c0675b864fb0cf5147305f7b077b7f03a58fa7a9ab3e7e7d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.4.0"
|
||||
version: "0.5.0"
|
||||
pubspec_parse:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -301,9 +285,9 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yaml_edit
|
||||
sha256: fb38626579fb345ad00e674e2af3a5c9b0cc4b9bfb8fd7f7ff322c7c9e62aef5
|
||||
sha256: ec709065bb2c911b336853b67f3732dd13e0336bd065cc2f1061d7610ddf45e3
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.2"
|
||||
version: "2.2.3"
|
||||
sdks:
|
||||
dart: ">=3.6.0 <4.0.0"
|
||||
dart: ">=3.9.0 <4.0.0"
|
||||
|
||||
@@ -7,7 +7,7 @@ repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
|
||||
environment:
|
||||
sdk: ">=3.2.0 <4.0.0"
|
||||
sdk: ">=3.8.0 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
meta: ^1.3.0
|
||||
|
||||
Reference in New Issue
Block a user