Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(network): add request and requestFinished events to APIRequestContext by shahzad31 · Pull Request #34938 · microsoft/playwright · GitHub
Skip to content

feat(network): add request and requestFinished events to APIRequestContext - #34938

Closed
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context
Closed

feat(network): add request and requestFinished events to APIRequestContext#34938
Shahzad (shahzad31) wants to merge 8 commits into
microsoft:mainfrom
shahzad31:api-request-context

Conversation

@shahzad31

Copy link
Copy Markdown

Fixes#34924 !!

Added request and requestFinished events to APIRequestContext

Usage

 context.request.on('apiRequest', request => {
});
 context.request.on('apiRequestfinished', request => {
});

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Shahzad (@shahzad31) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@microsoft-github-policy-service agree [company="Elastic"]

@microsoft-github-policy-service agree company="Elastic"

@github-actions

This comment has been minimized.

@shahzad31

Copy link
Copy Markdown
Author

Hi, Dmitry Gozman (@dgozman) can you please take a look, i see you have review similar PR like this in the past. I would appreciate some feedback before i spent bit more time on figuring out why build is failing :)

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Test results for "tests 1"

8 failed
❌ [default] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:340:5 › should only create test run if file belongs to context vscode-extension (@vscode-extension)
❌ [default-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [default-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-reuse] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [legacy-trace] › tests/run-tests.spec.ts:1154:5 › should produce output twice vscode-extension (@vscode-extension)
❌ [webkit-page] › tests/page/page-leaks.spec.ts:161:5 › waitFor should not leak @webkit-ubuntu-22.04-node18

3 flaky⚠️ [firefox-page] › tests/page/page-evaluate.spec.ts:403:3 › should throw for too deep reference chain @firefox-ubuntu-22.04-node18
⚠️ [webkit-page] › tests/page/page-screenshot.spec.ts:345:5 › page screenshot › should work while navigating @webkit-ubuntu-22.04-node18
⚠️ [playwright-test] › tests/ui-mode-test-watch.spec.ts:145:5 › should watch all @windows-latest-node18-1

38659 passed, 793 skipped
✔️✔️✔️

Merge workflow run.

@pavelfeldman

Copy link
Copy Markdown
Member

Please wait for the supporting signal on the issue prior to sending the PRs!

@shahzad31
Shahzad (shahzad31) deleted the api-request-context branch March 4, 2025 05:38
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request May 19, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jun 15, 2026
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
Shahzad (shahzad31) added a commit to elastic/synthetics that referenced this pull request Jul 14, 2026
* fix(formatter): vendor JS codegen after Playwright 1.61 stopped exporting it
Playwright 1.61 bundles its server code into coreBundle.js and no longer
ships the codegen classes as importable modules, so the recorder's
`playwright-core/lib/server/codegen/javascript` deep import no longer
resolves. Vendor the minimal slice SyntheticsGenerator extends
(_asLocator + _generateActionCall + JavaScriptFormatter) into
src/formatter/codegen.ts, reusing the still-exported `iso` helpers
(asLocator / formatObject / escapeWithQuotes) rather than vendoring the
heavy locator logic. Formatter snapshots are unchanged.
Also bump playwright/-chromium/-core to 1.61.0 (required for the native
APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the
options test that 1.61's bundled descriptors updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: multi step api runner
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the
type-aware Runner/Gatherer/PluginManager branching needed to run API-only
journeys without launching Chromium.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback, plug data loss, add tests
Builds on the rebased api-journey commit:
- PluginManager.output() now surfaces APINetworkManager results
(previously dropped silently because of an instanceof NetworkManager
check), and onStep() uses a proper union narrow instead of a lying
cast. The browser/api branching is hidden behind a shared NetworkPlugin
contract so the manager is transparent to journey type.
- Runner only launches Chromium when at least one browser journey is
scheduled; pure API suites skip launch entirely.
- APIJourney now overrides _updateMonitor so 'synthetics push' registers
it as an HTTP monitor instead of mislabeling it as browser. Journey
base class gained a protected _setMonitor helper to make subclassing
safe.
- apiJourney.skip / apiJourney.only are now wired up.
- APINetworkManager rewritten: only patches request.fetch (Playwright's
helpers funnel through it, so the previous double-patch was
double-counting requests), restores the prototype method on stop,
handles fetch(Request, opts), wraps in try/finally so failed requests
still leave a valid entry, drops dead Page/Frame barriers, surfaces
status/headers/url/statusText.
- APIJourney class trimmed: dead #cb / #driver fields removed; subclass
now carries the http monitor override and forwards string|options
upstream.
- Reporter payload no longer carries browserDelay / browserconsole for
API journeys; common_types updated accordingly.
- Public API exports APIJourney / APIJourneyCallback /
APIJourneyCallbackOpts / APIJourneyOptions /
APIJourneyWithAnnotations.
- Tests added: dsl/api-journey, plugins/api-network round-trip against a
local HTTP server, plugins/plugin-manager API-driver coverage,
core/api-runner end-to-end with browser launch spy, core/api-journey-register
factory + skip/only wiring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(api-journey): capture TLS cert info, server.ip/port, and body bytes
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(),
or request/response timings (upstream microsoft/playwright#32647 and
microsoft/playwright#34938 were both declined; see microsoft/playwright#40905
for the current ask).
To still surface this for HTTPS API monitoring use cases (cert expiry,
remote-address alerting, response size tracking), open a side-channel
tls.connect() in parallel with each request and fold the result into
the NetworkInfo entry:
- securityDetails: issuer, subjectName, protocol, validFrom, validTo
- remoteIPAddress / remotePort
- coarse dns / connect / ssl timings
Probes are cached per host:port within a journey and silently skipped
for HTTP or on failure (timeout, refused, untrusted) so they never
affect the actual request.
Also derive request and response body bytes (Content-Length preferred,
buffer fallback) and emit server.ip / server.port in the JSON reporter.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-runner): cover empty steps, cookie isolation, and HTTPS e2e
- Empty step with no requests must not break network-event step
attribution: the next step's requests must still be assigned to
that step's reference identity (required for waterfall grouping).
- API journeys must have isolated APIRequestContexts: a cookie set in
journey A must not leak into journey B.
- HTTPS journey verifies the full pipeline emits TLS securityDetails,
remote address, and response body bytes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(api-journey): add README sections and runnable example
Splits the README usage section into "Browser journeys" and "API
journeys (no browser)" so users discover apiJourney() without having
to dig through the Elastic docs site. Adds a runnable example under
examples/todos/api.journey.ts showing OAuth-style multi-step API
checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* style(api-journey): fix lint and prettier issues
- Replace non-null assertions with explicit narrowing in api-tls and
api-runner tests so the `@typescript-eslint/no-non-null-assertion`
rule is satisfied.
- Apply prettier formatting to api-tls.ts and json.test.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): support ES module inline scripts in the CLI loader
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline
source via `--inline`. When that source uses ESM (e.g. `import` /
top-level await) — which is the natural shape for `apiJourney()` and
`step()` imports — Node's `vm.runInContext` path falls over with
`SyntaxError: Cannot use import statement outside a module`, silently
dropping the run.
Detect ESM-shaped inline source and execute it via a temporary `.mjs`
module file resolved with a `Module._resolveFilename` alias so
`@elastic/synthetics` keeps resolving to the agent-installed copy. The
CommonJS fast path is unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(api-journey): destructure params in inline ESM apiJourney test
The new ESM inline loader path compiles the source as a regular module
rather than running it through the new Function(...) wrapper, so `params`
is no longer injected as an implicit local. The test needs to pull it
out of the apiJourney callback args like the sibling browser test does.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): harden TLS reporter, IP-literal probe, inline loader
Address review findings from end-to-end review of the API journey work:
- src/reporters/json.ts: `formatTLS` previously called
`new Date(undefined * 1000).toISOString()` when a TLS probe resolved
with `protocol` set but cert dates missing (malformed `valid_from` /
`valid_to`). That throws `RangeError: Invalid time value` and sinks
the entire `journey/end` document. Route the dates through a
defensive `epochToIso` helper that returns `undefined` for non-finite
inputs, and add a regression test.
- src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event
never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded
into `connect: -1`. Treat the missing DNS phase as `dns: 0` and
measure `connect` from `dnsStart`, so the timing breakdown stays
meaningful. Add a probe test that exercises this path.
- src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>`
but initialised to `null`, contradicting the shared `NetworkPlugin`
shape. Widen the field type to `Partial<Step> | null`.
- src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from
`isModuleInlineSource`. The regex matched inside string literals
and comments, silently routing legacy inline scripts through the
ESM loader and stripping the implicit `step` / `page` / `params`
injection. Key off `import` / `export` only — that's the contract
documented in the README. Also register a best-effort `process.exit`
cleanup hook for the materialised `mkdtempSync` directory so
long-lived hosts don't accumulate tmp dirs.
- __tests__/plugins/api-network.test.ts: Add a guard that exercises
every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/
`delete`/`head`/`fetch`) so a future Playwright that bypasses
`this.fetch` on any of them stops being a silent capture loss.
- __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying
that a suite with both a `journey()` and an `apiJourney()` launches
Chromium exactly once and routes each journey through the right
driver type.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(templates): add API journey scaffold examples
Mirror the existing browser-journey scaffold examples with API-journey
counterparts so users adopting `npx @elastic/synthetics <dir>` see
both monitoring shapes side by side.
- templates/journeys/api-example.journey.ts: minimal `apiJourney` with
two GET steps and status assertions, structurally parallel to the
existing `example.journey.ts`.
- templates/journeys/advanced-api-example.journey.ts and its
`advanced-api-example-helpers.ts`: multi-step API journey
demonstrating the recommended shape — small reusable step builders,
shared state populated by earlier steps and consumed by later ones,
with a thunk-based id deletion to make the registration vs.
execution timing explicit.
- templates/synthetics.config.ts: adds `params.apiUrl` defaulting to
jsonplaceholder.typicode.com so the API examples run out of the
box; users override per-environment for their own service.
- templates/README.md: distinguishes browser vs. API journey examples
and explains when to reach for each.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): unflake json-reporter test against chunked stdout
`CLIMock.output()` returns only the last stdout chunk, and the
existing test fed that into `JSON.parse`. On Linux CI a single
chunk can hold multiple NDJSON events from the json reporter, which
makes the parse throw `SyntaxError: Unexpected non-whitespace
character after JSON at position N`. The test was therefore order-
and flush-dependent and recently started flaking.
Switch to the `cli.buffer()` accumulator (which join+split-by-line
correctly reconstructs NDJSON regardless of chunk boundaries) and
locate the `journey/start` event explicitly instead of assuming the
last chunk holds exactly one event. A defensive `tryParse` swallows
the rare partial-line case where the listener detaches mid-event,
so the lookup keeps working without resorting to longer waits.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(api-journey): use native APIResponse TLS APIs from Playwright 1.61
Playwright 1.61 (microsoft/playwright#40932) exposes
APIResponse.securityDetails() and APIResponse.serverAddr(), returning the
same shapes the browser network path already consumes. Drop the
tls.connect() side-channel (api-tls.ts), its per-origin cache, and the
probe-fold blocks in APINetworkManager in favour of reading cert info and
remote address straight off the response used by the actual request.
This gives true per-request fidelity (final hop on redirects), removes the
extra parallel TLS handshake, and now also reports server.ip/port over
plain HTTP. The synthesized dns/connect/ssl timings (which came from a
separate socket) are gone. A small normalizeTLSProtocol keeps the
"TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(api-journey): address review feedback and guard push by version
- Register API journeys as `api` monitor type (was `http`) and bundle them
like browser monitors in push (buildMonitorSchema + dry-run extraction).
- Emit ECS `server.ip`/`server.port` for API journeys only; browser output
keeps the address under `http.response`.
- Use monotonic `now()` for API network timings.
- Abort push with a clear message when API monitors target Kibana < 9.6.0.
- Tighten verbose comments across the API journey code.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for freeto 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.

[Feature]: Expose events on APIRequestContext

2 participants

@shahzad31@pavelfeldman