sema-cdp 0.1.1

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

API reference 17 exports

Exported declarations from this release. Parameter names and descriptions come directly from its source.

cdp/attach!

Source :281
(cdp/attach! conn target-id)
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.
View source definition
(define (cdp/attach! conn target-id)
  "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."
  (let ((sid (:sessionId (cdp/send conn "Target.attachToTarget"
                                   {:targetId target-id :flatten #t}))))
    {:conn conn :session-id sid :target-id target-id}))

cdp/browser-candidates

Source :62
(cdp/browser-candidates)
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.
View source definition
(define (cdp/browser-candidates)
  "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."
  (append static-candidates
          (windows-candidates (list (env "PROGRAMFILES")
                                    (env "PROGRAMFILES(X86)")
                                    (env "LOCALAPPDATA")))))

cdp/clear-events!

Source :338
(cdp/clear-events! target . method-rest)
Drop buffered events — all of them, or only a given method name. Scoped to the session when `target` is one.
View source definition
(define (cdp/clear-events! target . method-rest)
  "Drop buffered events — all of them, or only a given method name. Scoped to the session when `target` is one."
  (let ((conn   (conn-of target))
        (sid    (:session-id target))
        (method (if (null? method-rest) nil (first method-rest))))
    (cell-set! conn :events
               (filter (fn (m)
                         (not (and (or (nil? sid) (= sid (:sessionId m)))
                                   (or (nil? method) (= method (:method m))))))
                       (cell-get conn :events)))
    nil))

cdp/close!

Source :161
(cdp/close! conn)
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.
View source definition
(define (cdp/close! conn)
  "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."
  (try (cdp/send conn "Browser.close" {} {:timeout 3000}) (catch e nil))
  (try (ws/close (:ws conn)) (catch e nil))
  (when (:proc conn)
    (try (proc/kill (:proc conn)) (catch e nil))
    (try (proc/wait (:proc conn)) (catch e nil)))
  ;; Only remove profile dirs this package generated itself — never one the
  ;; caller passed in. The name check is a second guard against deleting
  ;; anything else by accident.
  (when (and (:owns-data-dir conn)
             (:user-data-dir conn)
             (string/contains? (:user-data-dir conn) "/sema-cdp-"))
    (try (proc/wait (proc/spawn ["rm" "-rf" (:user-data-dir conn)]))
         (catch e nil)))
  nil)

cdp/connect

Source :151
(cdp/connect url)
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.
View source definition
(define (cdp/connect url)
  "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."
  (let ((ws-url (if (string/starts-with? url "ws")
                  url
                  (let ((resp (http/get (format "~a/json/version" url))))
                    (get (json/decode (:body resp)) :webSocketDebuggerUrl)))))
    (when (nil? ws-url)
      (error (format "cdp/connect: no webSocketDebuggerUrl at ~a — is the browser running with --remote-debugging-port?" url)))
    (make-conn (ws/connect ws-url {:timeout 10000}) nil nil #f)))

cdp/detach!

Source :287
(cdp/detach! session)
Detach a session created by cdp/attach!.
View source definition
(define (cdp/detach! session)
  "Detach a session created by cdp/attach!."
  (cdp/send (:conn session) "Target.detachFromTarget"
            {:sessionId (:session-id session)})
  nil)

cdp/events

Source :330
(cdp/events target)
Return the buffered events for this connection (or, for a session, only that session's), oldest first.
View source definition
(define (cdp/events target)
  "Return the buffered events for this connection (or, for a session, only that session's), oldest first."
  (let ((all (cell-get (conn-of target) :events))
        (sid (:session-id target)))
    (if (nil? sid)
      all
      (filter (fn (m) (= sid (:sessionId m))) all))))

cdp/find-chrome

Source :76
(cdp/find-chrome)
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).
View source definition
(define (cdp/find-chrome)
  "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)."
  (let ((from-env (env "SEMA_CHROME")))
    (if (and from-env (file/exists? from-env))
      from-env
      (first-existing (cdp/browser-candidates)))))

cdp/launch

Source :116
(cdp/launch . opts-rest)
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).
View source definition
(define (cdp/launch . opts-rest)
  "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)."
  (let* ((opts     (if (null? opts-rest) {} (first opts-rest)))
         (chrome   (or (get opts :chrome) (cdp/find-chrome)))
         (own-dir  (nil? (get opts :user-data-dir)))
         (data-dir (or (get opts :user-data-dir)
                       (format "~a/sema-cdp-~a" (sys/temp-dir) (time-ms)))))
    (when (nil? chrome)
      (error "cdp/launch: no Chrome-compatible browser found — install Chrome/Chromium, set SEMA_CHROME, or pass {:chrome \"/path\"}"))
    (file/mkdir data-dir)
    (let* ((argv (append
                   (list chrome
                         "--remote-debugging-port=0"
                         (format "--user-data-dir=~a" data-dir)
                         "--no-first-run"
                         "--no-default-browser-check"
                         "--disable-background-networking"
                         ;; A page restored from the back/forward cache stops
                         ;; acking synthetic wheel events (headless), hanging
                         ;; later Input commands. Puppeteer and Playwright
                         ;; disable the cache for the same reason.
                         "--disable-features=BackForwardCache")
                   (if (get opts :headless #t) (list "--headless=new") (list))
                   (get opts :args (list))
                   (list "about:blank")))
           (pid       (proc/spawn argv))
           (port-file (format "~a/DevToolsActivePort" data-dir))
           (content   (wait-for-port-file port-file (+ (time-ms) 20000)))
           (lines     (string/split content "\n"))
           (port      (string->number (first lines)))
           (path      (first (rest lines)))
           (sock      (ws/connect (format "ws://127.0.0.1:~a~a" port path)
                                  {:timeout 10000})))
      (make-conn sock pid data-dir own-dir))))

cdp/new-target!

Source :277
(cdp/new-target! conn url)
Create a new page target navigated to url and return its target id.
View source definition
(define (cdp/new-target! conn url)
  "Create a new page target navigated to url and return its target id."
  (:targetId (cdp/send conn "Target.createTarget" {:url url})))

cdp/off!

Source :311
(cdp/off! target handler-id)
Remove an event handler registered by cdp/on!, by its returned id.
View source definition
(define (cdp/off! target handler-id)
  "Remove an event handler registered by cdp/on!, by its returned id."
  (let ((conn (conn-of target)))
    (cell-set! conn :handlers
               (filter (fn (h) (not (= (:id h) handler-id)))
                       (cell-get conn :handlers)))
    nil))

cdp/on!

Source :300
(cdp/on! target method handler)
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.
View source definition
(define (cdp/on! target method handler)
  "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."
  (let* ((conn (conn-of target))
         (id   (cell-get conn :next-handler-id)))
    (cell-set! conn :next-handler-id (+ id 1))
    (cell-set! conn :handlers
               (append (cell-get conn :handlers)
                       (list {:id id :sid (:session-id target)
                              :method method :fn handler})))
    id))

cdp/pump

Source :319
(cdp/pump target duration-ms)
Receive and dispatch events for up to duration-ms without sending anything — use it to let cdp/on! handlers run while otherwise idle.
View source definition
(define (cdp/pump target duration-ms)
  "Receive and dispatch events for up to duration-ms without sending anything — use it to let cdp/on! handlers run while otherwise idle."
  (let ((conn     (conn-of target))
        (deadline (+ (time-ms) duration-ms)))
    (let loop ()
      (let ((remaining (- deadline (time-ms))))
        (when (> remaining 0)
          (when (= :got (pump-once conn remaining))
            (loop)))))
    nil))

cdp/send

Source :248
(cdp/send target method . extra)
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.
View source definition
(define (cdp/send target method . extra)
  "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."
  (let* ((conn    (conn-of target))
         (params  (if (null? extra) {} (first extra)))
         (opts    (if (or (null? extra) (null? (rest extra))) {} (first (rest extra))))
         (timeout (get opts :timeout default-timeout))
         (id      (cell-get conn :next-id))
         (msg     {:id id :method method :params params}))
    (cell-set! conn :next-id (+ id 1))
    (ws/send (:ws conn)
             {:json (if (:session-id target)
                      (assoc msg :sessionId (:session-id target))
                      msg)})
    (let ((resp (recv-response conn id (+ (time-ms) timeout))))
      (if (:error resp)
        (error (format "cdp/send: ~a failed — ~a (code ~a)"
                       method
                       (get (:error resp) :message)
                       (get (:error resp) :code)))
        (:result resp)))))

cdp/targets

Source :273
(cdp/targets conn)
List the browser's targets (pages, workers, extensions) as maps with :targetId, :type, :url, :title.
View source definition
(define (cdp/targets conn)
  "List the browser's targets (pages, workers, extensions) as maps with :targetId, :type, :url, :title."
  (:targetInfos (cdp/send conn "Target.getTargets")))

cdp/version

Source :269
(cdp/version conn)
Return browser version info: :product, :revision, :userAgent, :jsVersion, :protocolVersion.
View source definition
(define (cdp/version conn)
  "Return browser version info: :product, :revision, :userAgent, :jsVersion, :protocolVersion."
  (cdp/send conn "Browser.getVersion"))

cdp/wait-event

Source :358
(cdp/wait-event target method . opts-rest)
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.
View source definition
(define (cdp/wait-event target method . opts-rest)
  "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."
  (let* ((conn     (conn-of target))
         (sid      (:session-id target))
         (opts     (if (null? opts-rest) {} (first opts-rest)))
         (pred     (get opts :pred))
         (deadline (+ (time-ms) (get opts :timeout default-timeout))))
    (let loop ()
      (let ((buffered (take-buffered-event! conn sid method pred)))
        (if buffered
          buffered
          (let ((remaining (- deadline (time-ms))))
            (when (<= remaining 0)
              (error (format "cdp/wait-event: timed out waiting for ~a" method)))
            (let ((msg (pump-once conn remaining)))
              (when (nil? msg)
                (error "cdp/wait-event: connection closed"))
              ;; :timeout falls through to the deadline check; a stray
              ;; response (no waiting sender) is dropped.
              (loop)))))))))
About this reference

Generated with sema-reader 1.37.0 without executing package code. These are source declarations; dynamic exports, aliases, and runtime changes are not inferred.

Archive SHA-256 f7609ffe22d6a6ef869558c7bbf895e24680b74e897236a549efb0e69e0aff1e