← Back to Official Package Registry
Tier 4: FinTech, GraphQL, CDP & SSO • Chrome DevTools & E2E Automationv1.0.0 • 53 KB • Ed25519 Verified

browser_cdp@1.0.0

Chrome DevTools Protocol (CDP) JSON-RPC target multiplexer, Page/DOM/Runtime/Network automation, request mocking, and WebSocket driver.

use [browser_cdp]
veko pkg add browser_cdp@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

browser_cdp

Pure-Veko Chrome DevTools Protocol (CDP) JSON-RPC session state machine, target flat-session multiplexing, ergonomic domain command builders, homoiconic E2E script runner, RFC 6455 net/websocket client adapter, and deterministic mock CDP loopback harness (browser_cdp).

Overview

browser_cdp provides zero-dependency browser automation, end-to-end UI verification, network request interception, and headless screenshot/PDF capture over the Chrome DevTools Protocol:

  • Deterministic JSON-RPC Session State Machine: Correlates outbound command id envelopes against out-of-order responses while buffering asynchronous domain events (Page.loadEventFired, Network.responseReceived, Runtime.consoleAPICalled, Fetch.requestPaused) and multiplexing multiple browser tabs over a single WebSocket connection via flat sessionId routing.
  • Ergonomic Domain Command Builders: First-class builders for Page, DOM, Runtime, Input, Network, Fetch, and Target domains -- including Fetch.fulfillRequest network mocking with Base64 payload encoding.
  • Homoiconic E2E Script Runner & Snapshot Validator: Compiles Veko quote [...] blocks into executable E2eStep pipelines (compile-steps, run-steps) and validates DOM snapshots with unified line diffs (assert-snapshot).
  • Live RFC 6455 WebSocket Client & Headless CI Mock Harness: Connects directly to Chromium/Chrome --remote-debugging-port (ws:// and wss://) over net/websocket, and ships an in-memory + loopback WebSocket mock CDP target (new-mock-browser, serve-mock-cdp-once) so E2E test suites run deterministically in CI without requiring a browser binary installed.

Installation

powershell
veko pkg add browser_cdp@1.0.0

Import the package in .vk source files:

rebol
use [cdp = browser_cdp]

Architecture

text
+-----------------------+      masked OP-TEXT JSON       +-----------------------------+
|  E2E Script / Caller  | -----------------------------> | Chromium / MockCdpLoopback  |
|  compile-steps [...]  |                                |  Page / DOM / Runtime / Net |
+-----------+-----------+ <----------------------------- +-----------------------------+
            |             id responses + async events
            v
+-----------------------+
|      CdpSession       |
| - monotonic next_id   |
| - flat sessionId mux  |
| - pending / responses |
| - FIFO domain events  |
+-----------------------+

When flat-session mode (Target.attachToTarget with flatten = true) is active, every command emitted with /session_id carries "sessionId": "<target-session>" at the top level of the CDP JSON envelope, and ingest-message preserves session_id on both CdpResponse and CdpEvent values.

Complete API Reference

SymbolSignatureDescription
new-sessionfn [/session_id sid str = ''] CdpSessionCreates a fresh CDP JSON-RPC session state machine
with-target-sessionfn [sess CdpSession, session_id str] CdpSessionReturns a copy of sess pinned to session_id
set-target-sessionfn [mut sess CdpSession, session_id str] enumUpdates the default target sessionId in-place
next-commandfn [mut sess CdpSession, method str, params map /session_id sid str = ''] CdpCommandAllocates monotonic id and encodes a CDP JSON-RPC command
ingest-messagefn [mut sess CdpSession, raw_json str] enumRoutes inbound JSON into .response (id) or .event (method)
has-response?fn [sess CdpSession, cmd_id i64] boolChecks whether a response for cmd_id is buffered
take-responsefn [mut sess CdpSession, cmd_id i64] CdpResponseRemoves and returns the correlated CdpResponse
events-for-methodfn [sess CdpSession, method str /session_id sid str = ''] block[CdpEvent]Returns buffered events matching method and optional session_id
drain-eventsfn [mut sess CdpSession /method filter_method str = '' /session_id sid str = ''] block[CdpEvent]Drains matching events while preserving remaining events in FIFO order
extract-eval-valuefn [resp CdpResponse] anyExtracts result.result.value or surfaces exceptionDetails as err
extract-binary-datafn [resp CdpResponse] bytesDecodes Base64 result.data from screenshot or PDF responses
page-enablefn [mut sess CdpSession /session_id sid str = ''] CdpCommandBuilds Page.enable
page-navigatefn [mut sess CdpSession, target_url str /referrer ref str = '' /session_id sid str = ''] CdpCommandBuilds Page.navigate
page-capture-screenshotfn [mut sess CdpSession /format fmt str = 'png' /quality qual i64 = 0 /full_page full bool = false /session_id sid str = ''] CdpCommandBuilds Page.captureScreenshot
page-print-to-pdffn [mut sess CdpSession /landscape land bool = false /print_background bg bool = true /scale sc f64 = 1.0 /session_id sid str = ''] CdpCommandBuilds Page.printToPDF
dom-get-documentfn [mut sess CdpSession /depth d i64 = -1 /pierce p bool = false /session_id sid str = ''] CdpCommandBuilds DOM.getDocument
dom-query-selectorfn [mut sess CdpSession, node_id i64, selector str /session_id sid str = ''] CdpCommandBuilds DOM.querySelector
dom-get-outer-htmlfn [mut sess CdpSession, node_id i64 /session_id sid str = ''] CdpCommandBuilds DOM.getOuterHTML
runtime-evaluatefn [mut sess CdpSession, expression str /await_promise aw bool = true /return_by_value by_val bool = true /session_id sid str = ''] CdpCommandBuilds Runtime.evaluate
input-clickfn [mut sess CdpSession, x f64, y f64 /button btn str = 'left' /click_count cnt i64 = 1 /released rel bool = false /session_id sid str = ''] CdpCommandBuilds Input.dispatchMouseEvent
input-type-textfn [mut sess CdpSession, text str /session_id sid str = ''] CdpCommandBuilds Input.insertText
network-enablefn [mut sess CdpSession /max_total_buffer max_buf i64 = 0 /session_id sid str = ''] CdpCommandBuilds Network.enable
network-set-extra-headersfn [mut sess CdpSession, headers map[str] /session_id sid str = ''] CdpCommandBuilds Network.setExtraHTTPHeaders
fetch-enablefn [mut sess CdpSession, url_pattern str /session_id sid str = ''] CdpCommandBuilds Fetch.enable interception filter
fetch-fulfill-requestfn [mut sess CdpSession, request_id str, response_code i64, response_headers map[str], body bytes /session_id sid str = ''] CdpCommandBuilds Fetch.fulfillRequest synthetic response
target-attachfn [mut sess CdpSession, target_id str /flatten flat bool = true] CdpCommandBuilds Target.attachToTarget
compile-stepsfn [spec block] block[E2eStep]Compiles homoiconic quote [...] automation directives
assert-snapshotfn [actual_html str, rules block] SnapshotReportValidates DOM HTML against .contains, .not_contains, and .exact
dial-cdpfn [ws_url str /timeout deadline dur = 10s] CdpClientConnects to a ws:// or wss:// CDP endpoint via net/websocket
send-cdpfn [mut client CdpClient, cmd CdpCommand /max_frames limit i64 = 128] CdpResponseSends a command and awaits its correlated id response
call-cdpfn [mut client CdpClient, method str, params map /session_id sid str = ''] CdpResponseEncodes and sends a CDP method call directly on client
wait-for-eventfn [mut client CdpClient, method str /session_id sid str = '' /max_frames limit i64 = 128] CdpEventAwaits a domain event matching method and optional session_id
run-stepsfn [mut client CdpClient, steps block[E2eStep]] mapExecutes compiled E2E steps over a live CdpClient
close-cdpfn [mut client CdpClient] enumSends WebSocket CLOSE and closes the underlying stream
new-mock-browserfn [] MockBrowserCreates an in-memory mock CDP browser state
dispatch-mock-cdpfn [mut mb MockBrowser, raw_json str] block[str]Processes a CDP JSON request against MockBrowser
serve-mock-cdp-oncefn [ln any, max_commands i64] i64Serves mock CDP over a TCP RFC 6455 WebSocket listener

Idiomatic Veko Usage

rebol
use [cdp = browser_cdp]

mut client = cdp/dial-cdp 'ws://127.0.0.1:9222/devtools/page/MAIN'
defer [ _ = cdp/close-cdp mut client ]

enable_cmd = cdp/page-enable mut client.session
_ = cdp/send-cdp mut client enable_cmd

steps = cdp/compile-steps (quote [
    .navigate 'https://veko-lang.org'
    .wait_event 'Page.loadEventFired'
    .expect_eval 'document.title' 'Veko Programming Language'
    .screenshot 'png'
])

summary = cdp/run-steps mut client steps
os/write-bytes 'homepage.png' (map/get summary 'screenshot_bytes')
packages/browser_cdp/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/browser_cdp/examples/demo.vk
// Self-contained verification suite & runnable example for `browser_cdp`.

use [
	cdp = browser_cdp
	fs
	hex = codec/hex
	png = image/png
]

assert-true = fn [cond bool, label str] enum [
	if not cond [
		println (str/join ['[FAIL] ' label] '')
		os/exit 1
	]
	println (str/join ['[PASS] ' label] '')
	.ok
]

// --- 1. CDP Command Encoding & Target `sessionId` Flat Multiplexing ---
mut sess = cdp/new-session
c_en   = cdp/page-enable mut sess
c_nav  = cdp/page-navigate/referrer mut sess 'https://portal.veko.dev/dashboard' 'https://veko.dev/'
c_hdrs = cdp/network-set-extra-headers mut sess { 'X-Veko-Trace' = 'trace-9001' }
c_pdf  = cdp/page-print-to-pdf/landscape mut sess true

dec_nav = json/decode c_nav.json_wire
cmd_ok = c_en.id == 1 and c_nav.id == 2 and c_hdrs.id == 3 and c_pdf.id == 4 and dec_nav.method == 'Page.navigate' and dec_nav.params.url == 'https://portal.veko.dev/dashboard'
_ = assert-true cmd_ok 'CDP JSON-RPC command encoding and monotonic id sequencing'

// Multiplexing two target tabs (`sess-tab-a` and `sess-tab-b`) over a single flat CDP session
c_tab_a = cdp/runtime-evaluate/session_id mut sess '21 * 2' 'sess-tab-a'
c_tab_b = cdp/runtime-evaluate/session_id mut sess 'document.title' 'sess-tab-b'

// Ingest interleaved async domain events and out-of-order responses
_ = cdp/ingest-message mut sess (json/encode {
	method    = 'Network.responseReceived'
	sessionId = 'sess-tab-a'
	params    = { requestId = 'r-1', response = { status = 200, url = 'https://a.test' } }
})
_ = cdp/ingest-message mut sess (json/encode {
	method    = 'Runtime.consoleAPICalled'
	sessionId = 'sess-tab-b'
	params    = { type = 'info', args = [{ type = 'string', value = 'booted' }] }
})
_ = cdp/ingest-message mut sess (json/encode {
	id        = c_tab_b.id
	sessionId = 'sess-tab-b'
	result    = { result = { type = 'string', value = 'Tab B Dashboard' } }
})
_ = cdp/ingest-message mut sess (json/encode {
	id        = c_tab_a.id
	sessionId = 'sess-tab-a'
	result    = { result = { type = 'number', value = 42 } }
})

resp_a = cdp/take-response mut sess c_tab_a.id
resp_b = cdp/take-response mut sess c_tab_b.id
val_a  = cdp/extract-eval-value resp_a
val_b  = cdp/extract-eval-value resp_b
ev_a   = cdp/drain-events/method/session_id mut sess 'Network.responseReceived' 'sess-tab-a'
ev_b   = cdp/drain-events/method/session_id mut sess 'Runtime.consoleAPICalled' 'sess-tab-b'

mux_ok = val_a == 42 and val_b == 'Tab B Dashboard' and resp_a.session_id == 'sess-tab-a' and (len ev_a) == 1 and (len ev_b) == 1
_ = assert-true mux_ok 'target sessionId flat multiplexing, out-of-order response routing, and event buffering'

// Verify JS exception detection in `extract-eval-value`
c_throw = cdp/runtime-evaluate mut sess 'throw new Error("boom")'
_ = cdp/ingest-message mut sess (json/encode {
	id     = c_throw.id
	result = { result = { type = 'object', subtype = 'error' }, exceptionDetails = { text = 'Uncaught Error: boom' } }
})
resp_throw = cdp/take-response mut sess c_throw.id
caught_exc = cdp/extract-eval-value/or resp_throw [ '__caught_js_err__' ]
_ = assert-true (caught_exc == '__caught_js_err__') 'Runtime.evaluate exceptionDetails surfaces cleanly via /or'

// --- 2. Network Request Mocking (`Fetch.enable` -> `Fetch.requestPaused` -> `Fetch.fulfillRequest`) ---
mut mb = cdp/new-mock-browser
mut mock_sess = cdp/new-session
f_en = cdp/fetch-enable mut mock_sess 'https://api.veko.dev/*'
_ = cdp/dispatch-mock-cdp mut mb f_en.json_wire

nav_mock = cdp/page-navigate mut mock_sess 'https://api.veko.dev/v1/peers'
nav_frames = cdp/dispatch-mock-cdp mut mb nav_mock.json_wire
mut fi = 0
while fi < (len nav_frames) [
	_ = cdp/ingest-message mut mock_sess nav_frames[fi]
	fi = fi + 1
]
paused_evs = cdp/drain-events/method mut mock_sess 'Fetch.requestPaused'
paused_req_id = str/append '' (map/get paused_evs[0].params 'requestId')

mock_payload = bytes/from-str '{"peers":["node-1","node-2"]}'
fulfill_cmd = cdp/fetch-fulfill-request mut mock_sess paused_req_id 200 {
	'content-type' = 'application/json'
	'x-mocked-by'  = 'browser_cdp'
} mock_payload
fulfill_dec = json/decode fulfill_cmd.json_wire
_ = cdp/dispatch-mock-cdp mut mb fulfill_cmd.json_wire
stored_mock = map/get mb.mocked_bodies paused_req_id

mock_ok = paused_req_id == 'inter-req-1' and fulfill_dec.params.responseCode == 200 and (hex/b64-decode fulfill_dec.params.body) == mock_payload and stored_mock.status == 200
_ = assert-true mock_ok 'Fetch.requestPaused interception and Fetch.fulfillRequest network mocking'

// --- 3. Homoiconic Snapshot Assertions (`assert-snapshot`) ---
snap_pass = cdp/assert-snapshot '<html><body><h1 id="hero">Veko CDP Ready</h1></body></html>' (quote [
	.contains 'Veko CDP Ready'
	.not_contains 'Internal Server Error'
])
snap_diff = cdp/assert-snapshot '<div>v2</div>' (quote [
	.exact '<div>v1</div>'
])
_ = assert-true (snap_pass.ok and snap_pass.checked == 2 and (not snap_diff.ok) and (str/contains? snap_diff.diff_text '-<div>v1</div>')) 'homoiconic assert-snapshot validation and unified diff diagnostics'

// --- 4. Live Loopback RFC 6455 `net/websocket` CDP E2E Session + Screenshot Capture ---
tmp_dir = str/join [(os/temp-dir) '/veko_browser_cdp_demo_' (mold (time/unix))] ''
_ = fs/mkdir-all tmp_dir
defer [ _ = fs/remove-all tmp_dir ]

ln = net/listen-tcp .ip '127.0.0.1:0'
port_s = (str/split (net/addr ln) ':')[1]
ws_endpoint = str/join ['ws://127.0.0.1:' port_s '/devtools/page/veko-e2e-1'] ''

srv_worker = spawn [
	cdp/serve-mock-cdp-once ln 32
]

mut client = cdp/dial-cdp ws_endpoint

// Enable Page + Network + attach to a multiplexed target session using field loans (`mut client.session`)
en_page_cmd = cdp/page-enable mut client.session
en_net_cmd  = cdp/network-enable mut client.session
attach_cmd  = cdp/target-attach mut client.session 'checkout-tab'

_ = cdp/send-cdp mut client en_page_cmd
_ = cdp/send-cdp mut client en_net_cmd
attach_resp = cdp/send-cdp mut client attach_cmd
attached_ev = cdp/wait-for-event mut client 'Target.attachedToTarget'
tab_sid = str/append '' (map/get attach_resp.result 'sessionId')

// Compile and execute a homoiconic E2E browser workflow over the live WebSocket
e2e_script = cdp/compile-steps (quote [
	.use_session 'sess-checkout-tab'
	.navigate 'https://shop.veko.dev/checkout'
	.wait_event 'Page.loadEventFired'
	.click 140.0 260.0
	.type_text 'alice@veko.dev'
	.expect_eval 'document.title' 'Veko Control Plane'
	.expect_eval 'window.__typed' 'alice@veko.dev'
	.expect_html_contains 'alice@veko.dev'
	.screenshot 'png'
])

run_summary = cdp/run-steps mut client e2e_script

// Query DOM selector + outerHTML directly on the live session
qs_cmd = cdp/dom-query-selector/session_id mut client.session 1 '#user' tab_sid
qs_resp = cdp/send-cdp mut client qs_cmd
input_nid = as-i64 (map/get qs_resp.result 'nodeId')

oh_cmd = cdp/dom-get-outer-html/session_id mut client.session input_nid tab_sid
oh_resp = cdp/send-cdp mut client oh_cmd
outer_input = str/append '' (map/get oh_resp.result 'outerHTML')

_ = cdp/close-cdp mut client
_ = task/await srv_worker

// Verify captured PNG screenshot bytes on disk and via `image/png` decoder
shot_bytes = map/get run_summary 'screenshot_bytes'
shot_path = str/join [tmp_dir '/checkout.png'] ''
_ = fs/write-atomic shot_path shot_bytes
disk_bytes = os/read-bytes shot_path
decoded_png = png/decode-rgba disk_bytes

live_ok = tab_sid == 'sess-checkout-tab' and attached_ev.method == 'Target.attachedToTarget' and (map/get run_summary 'steps_run') == 8 and decoded_png.width == 8 and decoded_png.height == 8 and (str/contains? outer_input 'value="alice@veko.dev"')
_ = assert-true live_ok 'live loopback RFC 6455 net/websocket E2E navigation, DOM query, and PNG screenshot capture'

println 'browser_cdp: all verification checks passed'
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/browser_cdp/1.0.0.vkp
Archive SHA-256: c64a358e460db7024950e52c5d0b66598bb0d885928abc1077f95ed8695acdc1
Merkle Root: 958e7d216d48f82cbe183fc3501a24ecc1ede23f6503daa45b2817b413cc1132
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"browser_cdp","version":"1.0.0","tier":4.0,"tier_label":"Tier 4: FinTech, GraphQL, CDP & SSO","category":"Chrome DevTools & E2E Automation","description":"Chrome DevTools Protocol (CDP) JSON-RPC target multiplexer, Page/DOM/Runtime/Network automation, request mocking, and WebSocket driver.","modules":["browser_cdp"],"homepage":"https://veko-lang.org/packages/browser_cdp"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md8 KBc786c8715572acd36bb39f12c09c64bbf1b245b12cfe0faa300d9eda7e011ad4
examples/demo.vk7 KBcb86c3464df01b129c9d919a2d2bb80c545487bb6843a73e4a87baa59a73b80d
mod.vk36 KBb1d7e02079ecc3de0356685039bb69ccbc0c857ab086daac97f333ec43cc7811