Skip to content

try sync returns#33

Merged
w01fgang merged 15 commits intomainfrom
try-sync-returns
Feb 1, 2026
Merged

try sync returns#33
w01fgang merged 15 commits intomainfrom
try-sync-returns

Conversation

@w01fgang
Copy link
Copy Markdown
Contributor

@w01fgang w01fgang commented Feb 1, 2026

  • Add design for sync Try returns
  • Ignore .worktrees directory
  • feat: return sync values for sync Try functions
  • chore: remove any in sync return path
  • fix(quick-002-tests-are-failing-01): align Try return typing
  • docs(quick-002-tests-are-failing-01): complete tests-are-failing plan
  • docs(quick-002): tests are failing
  • docs: add sync/async Try changeset and plan

Summary by CodeRabbit

  • New Features

    • Try now transparently supports both synchronous and asynchronous execution: methods return direct values for sync paths or Promises for async paths.
  • Documentation

    • Public API docs and examples updated to clarify sync vs async return behavior and when awaits are required.
  • Tests

    • Expanded coverage exercising both sync and async flows, error propagation, finally behavior, tagging, and breadcrumbs.
  • Chores

    • Version bumped to 1.1.0, changelog updated, and ignore list extended.

✏️ Tip: You can customize this high-level summary in your review settings.

w01fgang and others added 7 commits February 1, 2026 10:01
- infer async return types
- stabilize promise narrowing
Tasks completed: 3/3
- Capture current typecheck failures
- Fix breadcrumb and Try typings to satisfy tests
- Confirm typecheck passes

SUMMARY: .planning/quick/002-tests-are-failing/002-SUMMARY.md
Quick task completed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 1, 2026

Walkthrough

Adds first-class synchronous execution to Try: core API now returns direct values for sync functions or Promises for async ones. Changes touch core implementation, tests, README, changelog, package version, planning state, and .gitignore.

Changes

Cohort / File(s) Summary
Core implementation
src/core/Try.ts
Refactored public generic TTReturn; introduced promise-like helpers (PromiseLikeValue, isPromiseLike, IfPromise); execute can return sync TryResult or a Promise<TryResult>; added runFinallyCallback; many public methods' signatures updated to model sync vs async returns; caching for sync/async results added.
Tests (behavior & types)
src/__tests__/Try.test.ts, src/__tests__/type-safety.test.ts
Reworked tests to exercise both sync and async paths; moved/added async helpers and greet/greetSync; updated assertions and type expectations to reflect direct returns for sync invocations and Promise returns for async ones; expanded coverage (defaults, errors, tags, breadcrumbs, Sentry).
Docs & examples
README.md
Updated public API signatures and examples to reflect mixed sync/async return types (e.g., unwrap, value, error); clarified sync vs async behavior and removed unnecessary awaits in examples.
Release & metadata
package.json, CHANGELOG.md, .planning/STATE.md
Bumped package to 1.1.0; added changelog entry for sync+async support; updated planning state (dates, tasks, performance metrics, recent decisions, pending todo, quick tasks).
Repo config
.gitignore
Added .worktrees to ignored paths.

Sequence Diagram

sequenceDiagram
    participant Client as Client
    participant Try as Try
    participant Fn as Fn
    participant Cache as Cache
    participant Finally as Finally

    Note over Client,Try: Sync function flow
    Client->>Try: construct Try(syncFn, ...)
    Client->>Try: call value()/unwrap()
    Try->>Fn: invoke syncFn(...)
    Fn-->>Try: return value
    Try->>Cache: store result
    Try->>Finally: runFinallyCallback()
    Finally-->>Try: done
    Try-->>Client: return direct value

    Note over Client,Try: Async function flow
    Client->>Try: construct Try(asyncFn, ...)
    Client->>Try: call value()/unwrap()
    Try->>Fn: invoke asyncFn(...)
    Fn-->>Try: return Promise
    Try->>Cache: cache Promise
    Try-->>Client: return Promise
    par resolve
      Try->>Fn: await Promise
      Fn-->>Try: resolved value
      Try->>Cache: store resolved result
      Try->>Finally: await runFinallyCallback()
      Finally-->>Try: done
    end
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through code both quick and slow,

Sync delights delivered in a row,
Promises wait while carrots gleam,
Try now handles both in one dream,
I thump at edge cases — nibble, then beam.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'try sync returns' is concise and directly reflects the main change: implementing synchronous return values for the Try class when functions execute synchronously, which aligns with the core objectives of allowing both sync and async execution paths.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch try-sync-returns

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2bc6389cea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/core/Try.ts
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@README.md`:
- Line 120: Update the README sentence that currently reads "Sync functions
return values immediately; async functions requires `await`." to correct the
grammar: change "requires" to "require" so it reads "Sync functions return
values immediately; async functions require `await`." Locate the exact sentence
in README.md (the line with "Sync functions return values immediately; async
functions requires `await`.") and replace the verb to ensure subject-verb
agreement.

In `@src/core/Try.ts`:
- Around line 52-56: IfPromise currently uses a non‑distributive conditional
which misclassifies union types like Promise<T> | T; change its implementation
to keep the existing never guard but use a distributive check (i.e. preserve the
[T] extends [never] ? False : ... pattern, then use T extends
PromiseLike<unknown> ? True : False) so value()/unwrap() types are sound for
mixed sync/async unions; update/type-add a unit type-safety test that defines a
function returning Promise<number> | number and asserts the resolved typing path
(referencing IfPromise and the value()/unwrap() callers) to validate the fix.

Comment thread README.md Outdated
Comment thread src/core/Try.ts Outdated
Releases:
  @power-rent/try-catch@1.1.0

[skip ci]
Signed-off-by: w01fgang <sumin@unix-center.ru>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@src/__tests__/Try.test.ts`:
- Around line 1064-1079: The test calls new Try(throwingFunction,
params).debug(false).breadcrumbs(['parameterKey']) but never executes the Try
instance, so no breadcrumb is recorded; update the test to invoke the executor
on the Try instance (e.g., append .run() or the appropriate execution method on
Try after breadcrumbs) and await it if it returns a Promise (e.g., new
Try(...).debug(false).breadcrumbs([...]).run()), then assert
Sentry.addBreadcrumb was called.
- Around line 250-259: The test calls the async TestClass.greet via new
Try(...).unwrap() but doesn't await the Promise; update the test to await the
result of Try.unwrap() (e.g., const result = await new
Try(newTest.greet.bind(newTest), { greeting }).unwrap()) so the assertions
compare the resolved string, referencing Try, TestClass, greet, and unwrap().
- Around line 1090-1099: The test is calling the async method TestClass.greet in
a synchronous assertion, causing a Promise to be compared; update the test to
use the synchronous method TestClass.greetSync instead of greet (or
alternatively make the test async and await new Try(newTest.greet,
{...}).unwrap()), so replace the bound function newTest.greet.bind(newTest) with
newTest.greetSync.bind(newTest) when constructing the Try in this sync test to
ensure unwrap() returns the actual string.
- Around line 1449-1485: The tests for async finally are not awaiting
asynchronous work: update both "should async finally callbacks" and "should
async finally callbacks on error" to be async test functions, make the
asyncFinally callback an async function that awaits the created Promise (e.g.,
await new Promise(resolve => setTimeout(resolve, 10))), and await the result of
new Try(...).finally(asyncFinally).unwrap(); for the error case capture the
returned promise into a variable and use await
expect(exec).rejects.toThrow('boom'); then assert asyncCallbackResolved and
finallySpy as before so the tests actually verify async behavior of
Try.prototype.finally.
- Around line 957-965: The test uses the sync ThrowingFunction with new
Try(...).unwrap() which throws synchronously, so replace the async-style
assertion using .rejects with a synchronous assertion: call unwrap() inside a
function wrapper and assert expect(() => new Try(throwingFunction,
params).debug(false).unwrap()).toThrow('boom'); and keep the Sentry assertions
the same; apply the same change to the other sync test cases (those around lines
1043–1062) that call Try.unwrap() with non-Promise throwers.

Comment thread src/__tests__/Try.test.ts
Comment thread src/__tests__/Try.test.ts
Comment thread src/__tests__/Try.test.ts
Comment thread src/__tests__/Try.test.ts
Comment thread src/__tests__/Try.test.ts
Signed-off-by: w01fgang <sumin@unix-center.ru>
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Feb 1, 2026

Quality Gate Failed Quality Gate failed

Failed conditions
14.0% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/core/Try.ts`:
- Around line 743-762: runFinallyCallback currently swallows errors from
config.finallyCallback instead of letting them propagate like
Promise.prototype.finally; update it so synchronous exceptions are rethrown and
asynchronous rejections are returned (do not catch them). Specifically, in the
runFinallyCallback method, call this.config.finallyCallback(); if
isPromiseLike(result) return Promise.resolve(result) without a .catch so
rejections propagate, and for the synchronous path log the error when
this.config.debug is true but then rethrow the error instead of swallowing it.
Keep references to runFinallyCallback, this.config.finallyCallback, and
isPromiseLike when making the change.

Comment thread src/core/Try.ts
@w01fgang w01fgang merged commit a9f1eb2 into main Feb 1, 2026
3 of 4 checks passed
@w01fgang w01fgang deleted the try-sync-returns branch February 1, 2026 15:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant