Skip to content

feat: add translations for direct cookie access methods - #7070

Merged
bijin-bruno merged 4 commits into
usebruno:mainfrom
sanish-bruno:feat/new-cookie-apis
Feb 12, 2026
Merged

bijin-bruno merged 4 commits into
usebruno:mainfrom
sanish-bruno:feat/new-cookie-apis

Conversation

@sanish-bruno

@sanish-bruno sanish-bruno commented Feb 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

JIRA

Translate Postman's direct pm.cookies access methods (has, get, toObject) to composed expressions using Bruno's existing bru.cookies.jar() API during Postman collection import.

Translations

Postman API Bruno Translation
pm.cookies.has(name) await bru.cookies.jar().hasCookie(req.getUrl(), name)
pm.cookies.get(name) (await bru.cookies.jar().getCookie(req.getUrl(), name))?.value
pm.cookies.toObject() (await bru.cookies.jar().getCookies(req.getUrl())).reduce((obj, c) => ({...obj, [c.key]: c.value}), {})

These use await which is valid in Bruno scripts (they run inside async IIFEs in both QuickJS and NodeVM sandboxes).

No new Bruno APIs needed

All translations compose existing bru.cookies.jar().getCookie/getCookies with req.getUrl() — no runtime changes required.

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • New Features

    • Enhanced Postman-to-Bruno conversion to support direct cookie operations (presence, value retrieval, and object mapping) with awaited lookups.
    • Added a cookie-existence check to the runtime cookie API so scripts can synchronously/async verify if a cookie exists.
  • Tests

    • Added comprehensive unit and collection tests validating direct cookie translations, existence checks, value reads, and object-mapping behavior across usage patterns.

- Implement translations for pm.cookies.has, pm.cookies.get, and pm.cookies.toObject to their corresponding bru.cookies methods.
- Enhance the postman-to-bruno translator to handle these new cookie access patterns.
- Add unit tests to verify the correct conversion of cookie access methods in various scenarios.
@coderabbitai

coderabbitai Bot commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR adds direct Postman-to-Bruno translations for pm.cookies.has, pm.cookies.get, and pm.cookies.toObject, implements hasCookie on the Bruno cookie-jar wrapper, and introduces tests validating the new translation and runtime behavior.

Changes

Cohort / File(s) Summary
Postman Translation Entries
packages/bruno-converters/src/postman/postman-translations.js
Adds replacements mapping pm.cookies.has(name), pm.cookies.get(name), and pm.cookies.toObject() to awaited bru.cookies.jar() calls and value/object extraction patterns.
Translator Implementation
packages/bruno-converters/src/utils/postman-to-bruno-translator.js
Implements AST/text transformations to emit async/await cookie operations, adds pm.cookies to initializer replacements, and merges these replacements into existing translation logic.
Bruno Runtime — Cookie API
packages/bruno-js/src/bru.js, packages/bruno-requests/src/cookies/index.ts
Adds hasCookie(url, cookieName, callback) to the cookie-jar wrapper (runtime) and corresponding implementation in requests package supporting callback and Promise styles.
Tests — Converter & Runtime
packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js, packages/bruno-requests/src/cookies/index.spec.ts, packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru
Adds unit tests for translation cases (has/get/toObject) and runtime tests for hasCookie (true/false, promise and callback patterns) and a Bru collection exercising the API.

Sequence Diagram(s)

sequenceDiagram
    participant PostmanScript as Postman Script
    participant Translator as Converter (postman→bruno)
    participant Generated as Generated Bruno Code
    participant CookieJar as CookieJar (runtime)

    PostmanScript->>Translator: encounter pm.cookies.has/get/toObject
    Translator-->>PostmanScript: emit awaited bru.cookies.jar().hasCookie/getCookie/getCookies + value/object logic
    PostmanScript->>Generated: (runs converted script) call bru.cookies.jar().hasCookie(url, name)
    Generated->>CookieJar: hasCookie(url, name) -> internally calls getCookies(url)
    CookieJar-->>Generated: return cookies or boolean
    Generated-->>PostmanScript: resolved value (boolean / cookie value / object)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

🍪 A translator hears a cookie's plea,
From pm to bru it flows with glee,
await the jar, the value gleams,
tests applause in quiet streams,
small code, sweet runtime harmony.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding translations for direct cookie access methods (pm.cookies.has/get/toObject) to Bruno equivalents during Postman import.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@packages/bruno-converters/src/utils/postman-to-bruno-translator.js`:
- Around line 299-342: The transform building the expression for the
"pm.cookies.toObject" pattern constructs an awaitExpression (awaitExpr) and then
calls .reduce on it, which causes a precedence bug (await binds after .reduce).
Modify the transform so the awaited call is wrapped in a parenthesized
expression before creating the memberExpression for "reduce" — i.e. replace the
direct use of awaitExpr as the object of j.memberExpression with a parenthesized
form (use j.parenthesizedExpression(awaitExpr) or set j.parenthesizedExpression
true on awaitExpr) so that (await ...).reduce(...) is produced; keep the
existing reduceFn and the callExpression construction intact.
- Around line 265-297: The pm.cookies.get transform must wrap the await
expression in a parenthesized expression before applying optional chaining and
must not assign to an undeclared temp var in the fallback: replace
j.optionalMemberExpression(awaitExpr, j.identifier('value'), false, true) with
j.optionalMemberExpression(j.parenthesizedExpression(awaitExpr),
j.identifier('value'), false, true) and, in the catch fallback, declare the
temporary variable (e.g., create a var declaration via
j.variableDeclaration('var', [j.variableDeclarator(tempVar)]) where tempVar is
j.identifier('_c')) before using the assignmentExpression, or restructure the
fallback to avoid undeclared assignment so it works in strict-mode sandboxes;
target the transform block handling pm.cookies.get and the identifiers
awaitExpr, optionalMemberExpression and tempVar/_c.

In
`@packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js`:
- Around line 328-332: The test expectation for pm.cookies.get is asserting the
wrong precedence for the optional chaining on an awaited call; update the
expectedOutput in the test named "should convert pm.cookies.get(name) to await
getCookie?.value" from `await bru.cookies.jar().getCookie(req.getUrl(),
'token')?.value` to parenthesize the await result: `(await
bru.cookies.jar().getCookie(req.getUrl(), 'token'))?.value`; make the same
change for the other pm.cookies.get assertions referenced (lines with similar
expectations at the test cases around lines 351, 357, 363, and 369) so all
expectedOutput strings use (await ... )?.value.
🧹 Nitpick comments (1)
packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js (1)

334-341: toObject test uses toContain — consider verifying parenthesization too.

Using toContain makes this test resilient to formatting differences, but it won't catch the await-precedence issue discussed above. Adding a check that the output starts with (await (or using toBe with the full expected string) would strengthen this.

Proposed additional assertion
     const result = postmanTranslation(inputScript);
     expect(result).toContain('await bru.cookies.jar().getCookies(req.getUrl())');
     expect(result).toContain('.reduce(');
     expect(result).toContain('c.key');
     expect(result).toContain('c.value');
+    expect(result).toMatch(/^\(await\b/);

…bruno translator

- Streamlined the code for handling optional member expressions in the translation of cookie access methods.
- Updated unit test to verify the correct output format for pm.cookies.toObject() conversion.
- Updated the postman-to-bruno translator to wrap await expressions in parentheses for improved clarity and consistency.
- Adjusted unit tests to reflect the new output format for cookie access methods, ensuring accurate translation of pm.cookies.get calls.
- Modified translations for pm.cookies.has to utilize the new bru.cookies.hasCookie method for improved clarity and functionality.
- Updated related unit tests to reflect changes in expected output for cookie existence checks.
- Added new tests to validate the behavior of the hasCookie method in various scenarios.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 `@packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru`:
- Around line 32-37: The callback-based test nests test() inside jar.hasCookie's
callback which can run after the test runner finishes; change the spec so the
test() is the outer block and the async assertion awaits the hasCookie result
(or uses the test framework's done callback). Specifically, replace the inner
test(...) call with a top-level test that either returns a Promise which wraps
jar.hasCookie("https://testbench-sanity.usebruno.com", "existing_cookie") and
performs the expect assertions when resolved, or accept a done parameter in the
outer test and call done() (or done(err)) after performing
expect(error).to.be.null and expect(exists).to.be.true; keep references to
jar.hasCookie and the same assertion checks.
🧹 Nitpick comments (2)
packages/bruno-requests/src/cookies/index.spec.ts (1)

145-156: Consider adding an error-handling test for hasCookie.

The happy paths look good. However, the Error Handling section below covers getCookie, setCookie, and setCookies — adding a similar test for hasCookie with missing inputs would keep coverage consistent.

Suggested addition (after line 155)
+    test('hasCookie handles missing URL', async () => {
+      await expect(jar.hasCookie('', 'name')).rejects.toThrow('URL and cookie name are required');
+    });
+
+    test('hasCookie handles missing cookie name', async () => {
+      await expect(jar.hasCookie(testUrl, '')).rejects.toThrow('URL and cookie name are required');
+    });
packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru (1)

13-17: Missing await on jar.setCookie in pre-request script.

While the current setCookie implementation happens to be synchronous under the hood (setCookieSync), omitting await on a Promise-returning API is fragile — if the internals ever become truly async, this test will break silently. Same applies to jar.clear() on line 39.

Suggested fix
 script:pre-request {
   const jar = bru.cookies.jar()
 
-  jar.setCookie("https://testbench-sanity.usebruno.com", "existing_cookie", "some_value")
+  await jar.setCookie("https://testbench-sanity.usebruno.com", "existing_cookie", "some_value")
 }
-  jar.clear()
+  await jar.clear()

Comment on lines +32 to +37
jar.hasCookie("https://testbench-sanity.usebruno.com", "existing_cookie", function(error, exists) {
test("should work with callback pattern", function() {
expect(error).to.be.null;
expect(exists).to.be.true;
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Callback-based test nests test() inside the callback — assertion timing may be unreliable.

If hasCookie resolves asynchronously, the test(...) block inside the callback runs after the outer tests block has finished. The test runner may not pick it up. Consider converting this to a promise-based assertion wrapped in a proper test() block, or at minimum document that this relies on synchronous callback resolution.

🤖 Prompt for AI Agents
In `@packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru`
around lines 32 - 37, The callback-based test nests test() inside
jar.hasCookie's callback which can run after the test runner finishes; change
the spec so the test() is the outer block and the async assertion awaits the
hasCookie result (or uses the test framework's done callback). Specifically,
replace the inner test(...) call with a top-level test that either returns a
Promise which wraps jar.hasCookie("https://testbench-sanity.usebruno.com",
"existing_cookie") and performs the expect assertions when resolved, or accept a
done parameter in the outer test and call done() (or done(err)) after performing
expect(error).to.be.null and expect(exists).to.be.true; keep references to
jar.hasCookie and the same assertion checks.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

we already use similar pattern for getCookie.bru etc, so it is fine for now

@bijin-bruno
bijin-bruno merged commit d30ab4d into usebruno:main Feb 12, 2026
5 of 6 checks passed
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* feat: add translations for direct cookie access methods

- Implement translations for pm.cookies.has, pm.cookies.get, and pm.cookies.toObject to their corresponding bru.cookies methods.
- Enhance the postman-to-bruno translator to handle these new cookie access patterns.
- Add unit tests to verify the correct conversion of cookie access methods in various scenarios.

* refactor: simplify optional member expression handling in postman-to-bruno translator

- Streamlined the code for handling optional member expressions in the translation of cookie access methods.
- Updated unit test to verify the correct output format for pm.cookies.toObject() conversion.

* refactor: enhance handling of await expressions in cookie translations

- Updated the postman-to-bruno translator to wrap await expressions in parentheses for improved clarity and consistency.
- Adjusted unit tests to reflect the new output format for cookie access methods, ensuring accurate translation of pm.cookies.get calls.

* refactor: update cookie access translations to use hasCookie method

- Modified translations for pm.cookies.has to utilize the new bru.cookies.hasCookie method for improved clarity and functionality.
- Updated related unit tests to reflect changes in expected output for cookie existence checks.
- Added new tests to validate the behavior of the hasCookie method in various scenarios.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants