sema-cdp 0.1.1

Chrome DevTools Protocol client: launch, connect, send commands, wait for events

Source

package.sema

377 lines 54f225bdb823
File details

Source stored with sema-cdp 0.1.1. Line links refer to these exact bytes.

SHA-256 54f225bdb823b3f12e1a18ce8f83a6d341e9e9b0b77a5decc8869e2d039358f9

1;; sema-cdp — Chrome DevTools Protocol client: launch, connect, send commands, wait for events
2;;
3;; Raw protocol transport. Knows nothing about pages or selectors — that layer
4;; lives in sema-browser. Works against anything speaking CDP: Chrome, Edge,
5;; Brave, chrome-headless-shell, or an already-running browser started with
6;; --remote-debugging-port.
7
8(module sema-cdp
9  (export cdp/find-chrome
10          cdp/browser-candidates
11          cdp/launch
12          cdp/connect
13          cdp/close!
14          cdp/send
15          cdp/targets
16          cdp/new-target!
17          cdp/attach!
18          cdp/detach!
19          cdp/on!
20          cdp/off!
21          cdp/pump
22          cdp/wait-event
23          cdp/events
24          cdp/clear-events!
25          cdp/version)
26
27  ;; ---------------------------------------------------------------- helpers
28
29  (define default-timeout 30000)
30  (define max-buffered-events 500)
31
32  ;; Fixed install locations, ordered Chrome, Chromium, Brave, Edge per platform.
33  (define static-candidates
34    [;; macOS
35     "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
36     "/Applications/Chromium.app/Contents/MacOS/Chromium"
37     "/opt/homebrew/bin/chromium"
38     "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"
39     "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
40     ;; Linux
41     "/usr/bin/google-chrome"
42     "/usr/bin/google-chrome-stable"
43     "/usr/bin/chromium"
44     "/usr/bin/chromium-browser"
45     "/usr/bin/brave-browser"])
46
47  ;; Windows installs live under roots named by env vars (per-machine and
48  ;; per-user); the vars are unset on other platforms, so those roots vanish.
49  (define windows-suffixes
50    ["Google/Chrome/Application/chrome.exe"
51     "Chromium/Application/chrome.exe"
52     "BraveSoftware/Brave-Browser/Application/brave.exe"
53     "Microsoft/Edge/Application/msedge.exe"])
54
55  (define (windows-candidates roots)
56    (let ((real (filter (fn (r) (not (nil? r))) roots)))
57      (foldl (fn (acc suffix)
58               (append acc (map (fn (root) (format "~a/~a" root suffix)) real)))
59             (list)
60             windows-suffixes)))
61
62  (define (cdp/browser-candidates)
63    "Return the browser binary paths cdp/find-chrome probes on this machine, in priority order (Chrome, Chromium, Brave, Edge). Entries are candidates — most will not exist."
64    (append static-candidates
65            (windows-candidates (list (env "PROGRAMFILES")
66                                      (env "PROGRAMFILES(X86)")
67                                      (env "LOCALAPPDATA")))))
68
69  (define (first-existing paths)
70    (if (null? paths)
71      nil
72      (if (file/exists? (first paths))
73        (first paths)
74        (first-existing (rest paths)))))
75
76  (define (cdp/find-chrome)
77    "Return the path of a Chrome-compatible browser binary, or nil if none is found. Checks the SEMA_CHROME env var first, then well-known install locations on macOS, Linux, and Windows (see cdp/browser-candidates)."
78    (let ((from-env (env "SEMA_CHROME")))
79      (if (and from-env (file/exists? from-env))
80        from-env
81        (first-existing (cdp/browser-candidates)))))
82
83  ;; A connection is a map:
84  ;;   {:ws <websocket> :cell <mutable-cell> :proc <pid or nil> :user-data-dir <path or nil>}
85  ;; The cell holds {:next-id int :events (list of event maps) :handlers (list of {:sid :method :fn})}.
86  ;; A session (from cdp/attach!) is {:conn conn :session-id str :target-id str} —
87  ;; cdp/send and cdp/wait-event accept either a connection or a session.
88
89  (define (conn-of target) (or (:conn target) target))
90
91  (define (make-conn sock pid data-dir owns-dir)
92    {:ws sock
93     :cell (mutable-cell/new {:next-id 1 :events (list) :handlers (list)
94                              :next-handler-id 1 :responses {}})
95     :proc pid
96     :user-data-dir data-dir
97     :owns-data-dir owns-dir})
98
99  (define (cell-get conn key) (get (mutable-cell/get (:cell conn)) key))
100
101  (define (cell-set! conn key value)
102    (mutable-cell/set! (:cell conn) (assoc (mutable-cell/get (:cell conn)) key value)))
103
104  ;; ---------------------------------------------------------------- launch / connect
105
106  (define (wait-for-port-file path deadline)
107    (cond ((file/exists? path)
108           (let ((content (string/trim (file/read path))))
109             (if (= content "")
110               (begin (sleep 50) (wait-for-port-file path deadline))
111               content)))
112          ((> (time-ms) deadline)
113           (error (format "cdp/launch: browser did not write ~a within 20s — check the binary launches, or pass {:chrome \"/path\"}" path)))
114          (else (sleep 100) (wait-for-port-file path deadline))))
115
116  (define (cdp/launch . opts-rest)
117    "Launch a Chrome-compatible browser with remote debugging and return a connection. Options map: :headless (default #t), :chrome (binary path), :args (extra CLI args), :user-data-dir (default: fresh dir under the system temp dir)."
118    (let* ((opts     (if (null? opts-rest) {} (first opts-rest)))
119           (chrome   (or (get opts :chrome) (cdp/find-chrome)))
120           (own-dir  (nil? (get opts :user-data-dir)))
121           (data-dir (or (get opts :user-data-dir)
122                         (format "~a/sema-cdp-~a" (sys/temp-dir) (time-ms)))))
123      (when (nil? chrome)
124        (error "cdp/launch: no Chrome-compatible browser found — install Chrome/Chromium, set SEMA_CHROME, or pass {:chrome \"/path\"}"))
125      (file/mkdir data-dir)
126      (let* ((argv (append
127                     (list chrome
128                           "--remote-debugging-port=0"
129                           (format "--user-data-dir=~a" data-dir)
130                           "--no-first-run"
131                           "--no-default-browser-check"
132                           "--disable-background-networking"
133                           ;; A page restored from the back/forward cache stops
134                           ;; acking synthetic wheel events (headless), hanging
135                           ;; later Input commands. Puppeteer and Playwright
136                           ;; disable the cache for the same reason.
137                           "--disable-features=BackForwardCache")
138                     (if (get opts :headless #t) (list "--headless=new") (list))
139                     (get opts :args (list))
140                     (list "about:blank")))
141             (pid       (proc/spawn argv))
142             (port-file (format "~a/DevToolsActivePort" data-dir))
143             (content   (wait-for-port-file port-file (+ (time-ms) 20000)))
144             (lines     (string/split content "\n"))
145             (port      (string->number (first lines)))
146             (path      (first (rest lines)))
147             (sock      (ws/connect (format "ws://127.0.0.1:~a~a" port path)
148                                    {:timeout 10000})))
149        (make-conn sock pid data-dir own-dir))))
150
151  (define (cdp/connect url)
152    "Connect to an already-running browser. Accepts a ws:// debugger URL, or an http:// devtools address (e.g. \"http://localhost:9222\") whose /json/version endpoint is used to discover it."
153    (let ((ws-url (if (string/starts-with? url "ws")
154                    url
155                    (let ((resp (http/get (format "~a/json/version" url))))
156                      (get (json/decode (:body resp)) :webSocketDebuggerUrl)))))
157      (when (nil? ws-url)
158        (error (format "cdp/connect: no webSocketDebuggerUrl at ~a — is the browser running with --remote-debugging-port?" url)))
159      (make-conn (ws/connect ws-url {:timeout 10000}) nil nil #f)))
160
161  (define (cdp/close! conn)
162    "Close the browser: ask it to shut down via Browser.close, close the websocket, kill the spawned process if this connection launched it, and delete the temp profile dir if cdp/launch created it."
163    (try (cdp/send conn "Browser.close" {} {:timeout 3000}) (catch e nil))
164    (try (ws/close (:ws conn)) (catch e nil))
165    (when (:proc conn)
166      (try (proc/kill (:proc conn)) (catch e nil))
167      (try (proc/wait (:proc conn)) (catch e nil)))
168    ;; Only remove profile dirs this package generated itself — never one the
169    ;; caller passed in. The name check is a second guard against deleting
170    ;; anything else by accident.
171    (when (and (:owns-data-dir conn)
172               (:user-data-dir conn)
173               (string/contains? (:user-data-dir conn) "/sema-cdp-"))
174      (try (proc/wait (proc/spawn ["rm" "-rf" (:user-data-dir conn)]))
175           (catch e nil)))
176    nil)
177
178  ;; ---------------------------------------------------------------- message pump
179
180  ;; CDP interleaves command responses and events on one websocket, so every
181  ;; receive goes through pump-once: events are buffered (and dispatched to
182  ;; cdp/on! handlers), responses are returned to the waiting sender.
183  ;; ponytail: pull-based single-threaded pump — move to an async reader task +
184  ;; channels if concurrent multi-page use ever needs it.
185
186  (define (dispatch-event! conn msg)
187    (let ((events (cell-get conn :events)))
188      (cell-set! conn :events
189                 (append (if (>= (count events) max-buffered-events)
190                           (rest events)
191                           events)
192                         (list msg))))
193    (for-each (fn (h)
194                (when (and (= (:method h) (:method msg))
195                           (or (nil? (:sid h)) (= (:sid h) (:sessionId msg))))
196                  ((:fn h) msg)))
197              (cell-get conn :handlers)))
198
199  ;; Responses are stashed by id rather than returned directly: an event
200  ;; handler may itself call cdp/send (a reentrant pump), and its receives must
201  ;; not swallow the outer command's response. The stash is capped so responses
202  ;; to commands whose sender already timed out cannot accumulate forever.
203  (define max-stashed-responses 100)
204
205  (define (stash-response! conn msg)
206    (let ((responses (assoc (cell-get conn :responses) (:id msg) msg)))
207      (cell-set! conn :responses
208                 (if (> (count responses) max-stashed-responses)
209                   (dissoc responses (apply min (keys responses)))
210                   responses))))
211
212  (define (take-response! conn id)
213    (let ((msg (get (cell-get conn :responses) id)))
214      (when msg
215        (cell-set! conn :responses (dissoc (cell-get conn :responses) id)))
216      msg))
217
218  ;; Receive one frame: events are buffered/dispatched, responses stashed.
219  ;; Returns :got when a frame was processed, :timeout when nothing arrived,
220  ;; nil when the socket closed.
221  (define (pump-once conn timeout-ms)
222    (let ((frame (ws/recv-timeout (:ws conn) timeout-ms)))
223      (cond ((= frame :timeout) :timeout)
224            ((nil? frame) nil)
225            (else
226             (let ((msg (json/decode (:text frame))))
227               (if (:method msg)
228                 (dispatch-event! conn msg)
229                 (stash-response! conn msg))
230               :got)))))
231
232  (define (recv-response conn id deadline)
233    (let ((stashed (take-response! conn id)))
234      (if stashed
235        stashed
236        (let ((remaining (- deadline (time-ms))))
237          (when (<= remaining 0)
238            (error (format "cdp/send: timed out waiting for response ~a" id)))
239          (let ((r (pump-once conn remaining)))
240            (cond ((= r :timeout)
241                   (error (format "cdp/send: timed out waiting for response ~a" id)))
242                  ((nil? r)
243                   (error "cdp/send: connection closed while waiting for response"))
244                  (else (recv-response conn id deadline))))))))
245
246  ;; ---------------------------------------------------------------- commands
247
248  (define (cdp/send target method . extra)
249    "Send a CDP command and return its result map. `target` is a connection or a session (from cdp/attach!). Optional: params map, then options map {:timeout ms}. Raises on a CDP error response, including the method, code, and message."
250    (let* ((conn    (conn-of target))
251           (params  (if (null? extra) {} (first extra)))
252           (opts    (if (or (null? extra) (null? (rest extra))) {} (first (rest extra))))
253           (timeout (get opts :timeout default-timeout))
254           (id      (cell-get conn :next-id))
255           (msg     {:id id :method method :params params}))
256      (cell-set! conn :next-id (+ id 1))
257      (ws/send (:ws conn)
258               {:json (if (:session-id target)
259                        (assoc msg :sessionId (:session-id target))
260                        msg)})
261      (let ((resp (recv-response conn id (+ (time-ms) timeout))))
262        (if (:error resp)
263          (error (format "cdp/send: ~a failed — ~a (code ~a)"
264                         method
265                         (get (:error resp) :message)
266                         (get (:error resp) :code)))
267          (:result resp)))))
268
269  (define (cdp/version conn)
270    "Return browser version info: :product, :revision, :userAgent, :jsVersion, :protocolVersion."
271    (cdp/send conn "Browser.getVersion"))
272
273  (define (cdp/targets conn)
274    "List the browser's targets (pages, workers, extensions) as maps with :targetId, :type, :url, :title."
275    (:targetInfos (cdp/send conn "Target.getTargets")))
276
277  (define (cdp/new-target! conn url)
278    "Create a new page target navigated to url and return its target id."
279    (:targetId (cdp/send conn "Target.createTarget" {:url url})))
280
281  (define (cdp/attach! conn target-id)
282    "Attach to a target (flat protocol) and return a session map. Pass the session to cdp/send / cdp/wait-event to address commands to that target."
283    (let ((sid (:sessionId (cdp/send conn "Target.attachToTarget"
284                                     {:targetId target-id :flatten #t}))))
285      {:conn conn :session-id sid :target-id target-id}))
286
287  (define (cdp/detach! session)
288    "Detach a session created by cdp/attach!."
289    (cdp/send (:conn session) "Target.detachFromTarget"
290              {:sessionId (:session-id session)})
291    nil)
292
293  ;; ---------------------------------------------------------------- events
294
295  (define (event-matches? msg sid method pred)
296    (and (= (:method msg) method)
297         (or (nil? sid) (= sid (:sessionId msg)))
298         (or (nil? pred) (pred msg))))
299
300  (define (cdp/on! target method handler)
301    "Register a handler called with each matching event map as it arrives, and return a handler id for cdp/off!. Events are only received while a cdp/send, cdp/wait-event, or cdp/pump is pumping the connection. Scoped to the session when `target` is one, otherwise connection-wide. Handlers may call cdp/send themselves."
302    (let* ((conn (conn-of target))
303           (id   (cell-get conn :next-handler-id)))
304      (cell-set! conn :next-handler-id (+ id 1))
305      (cell-set! conn :handlers
306                 (append (cell-get conn :handlers)
307                         (list {:id id :sid (:session-id target)
308                                :method method :fn handler})))
309      id))
310
311  (define (cdp/off! target handler-id)
312    "Remove an event handler registered by cdp/on!, by its returned id."
313    (let ((conn (conn-of target)))
314      (cell-set! conn :handlers
315                 (filter (fn (h) (not (= (:id h) handler-id)))
316                         (cell-get conn :handlers)))
317      nil))
318
319  (define (cdp/pump target duration-ms)
320    "Receive and dispatch events for up to duration-ms without sending anything — use it to let cdp/on! handlers run while otherwise idle."
321    (let ((conn     (conn-of target))
322          (deadline (+ (time-ms) duration-ms)))
323      (let loop ()
324        (let ((remaining (- deadline (time-ms))))
325          (when (> remaining 0)
326            (when (= :got (pump-once conn remaining))
327              (loop)))))
328      nil))
329
330  (define (cdp/events target)
331    "Return the buffered events for this connection (or, for a session, only that session's), oldest first."
332    (let ((all (cell-get (conn-of target) :events))
333          (sid (:session-id target)))
334      (if (nil? sid)
335        all
336        (filter (fn (m) (= sid (:sessionId m))) all))))
337
338  (define (cdp/clear-events! target . method-rest)
339    "Drop buffered events — all of them, or only a given method name. Scoped to the session when `target` is one."
340    (let ((conn   (conn-of target))
341          (sid    (:session-id target))
342          (method (if (null? method-rest) nil (first method-rest))))
343      (cell-set! conn :events
344                 (filter (fn (m)
345                           (not (and (or (nil? sid) (= sid (:sessionId m)))
346                                     (or (nil? method) (= method (:method m))))))
347                         (cell-get conn :events)))
348      nil))
349
350  (define (take-buffered-event! conn sid method pred)
351    (let loop ((before (list)) (remaining (cell-get conn :events)))
352      (cond ((null? remaining) nil)
353            ((event-matches? (first remaining) sid method pred)
354             (cell-set! conn :events (append before (rest remaining)))
355             (first remaining))
356            (else (loop (append before (list (first remaining))) (rest remaining))))))
357
358  (define (cdp/wait-event target method . opts-rest)
359    "Wait for an event, consuming it from the buffer, and return the event map. Checks already-buffered events first. Options: :timeout ms (default 30000), :pred (event map -> bool). Scoped to the session when `target` is one."
360    (let* ((conn     (conn-of target))
361           (sid      (:session-id target))
362           (opts     (if (null? opts-rest) {} (first opts-rest)))
363           (pred     (get opts :pred))
364           (deadline (+ (time-ms) (get opts :timeout default-timeout))))
365      (let loop ()
366        (let ((buffered (take-buffered-event! conn sid method pred)))
367          (if buffered
368            buffered
369            (let ((remaining (- deadline (time-ms))))
370              (when (<= remaining 0)
371                (error (format "cdp/wait-event: timed out waiting for ~a" method)))
372              (let ((msg (pump-once conn remaining)))
373                (when (nil? msg)
374                  (error "cdp/wait-event: connection closed"))
375                ;; :timeout falls through to the deadline check; a stray
376                ;; response (no waiting sender) is dropped.
377                (loop)))))))))