
-- 확장은 로컬 바이너리를 직접 못 띄운다 — Chrome 이 manifest 를 보고 대신 띄운다
spawn :: Manifest -> ExtensionId -> Maybe Process
spawn m ext
| ext `elem` allowedOrigins m = Just (run (path m)) -- 와일드카드 불가, path 는 절대경로
| otherwise = Nothing
-- manifest = { name, description, path, type = "stdio", allowedOrigins }
-- 자리: Windows 레지스트리 · macOS ~/Library/Application Support/Google/Chrome/NativeMessagingHosts/
-- 대화는 소켓도 HTTP 도 아닌 stdin/stdout. 메시지 = 4바이트 길이(네이티브 바이트 순서) ++ UTF-8 JSON
frame :: Json -> Bytes
frame j = len (utf8 j) <> utf8 j -- 쓰고 flush
unframe :: Bytes -> Maybe (Json, Bytes)
unframe b | B.null b = Nothing -- Chrome 이 파이프를 닫았다 — 종료
| otherwise = let (n, rest) = B.splitAt 4 b
in Just (first decode (B.splitAt (fromLen n) rest))
-- stdout 에 print 한 글자가 새면 길이 자리에 낀다 → 로그는 stderr
-- 호스트가 부르는 것(yt-dlp)도 절대경로 — GUI 로 띄운 Chrome 은 .zshrc 를 안 읽고, 호스트는 사용자 셸 환경을 물려받지 않는다
limit :: Direction -> Bytes
limit HostToChrome = 1 MB -- 비대칭. 크면 잘라 보내거나 connectNative 로 나눈다
limit ChromeToHost = 64 MiB
-- 부를 수 있는 곳은 background(service worker) 뿐 — 흐름이 두 파일로 갈린다
content = sendMessage . extract -- 페이지에서 값만
background = onMessage (\m reply -> sendNativeMessage host m reply >> pure True) -- True: 비동기 응답 채널 유지
-- sendNativeMessage 는 응답 하나 뒤 프로세스가 끝난다 · 진행률을 흘리려면 connectNative 로 Port