Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 90 additions & 2 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,91 @@
chrome.runtime.onInstalled.addListener(() => {
console.log('Bug Recorder service worker installed')
import { onMessage } from '@/lib/messaging'
import { clearState, getState, setState } from '@/lib/state'
import type { Status } from '@/types/messages'

const BADGE_ALARM = 'badge-tick'
const OFFSCREEN_URL = 'src/offscreen/index.html'

async function ensureOffscreen(): Promise<void> {
if (await chrome.offscreen.hasDocument()) return
await chrome.offscreen.createDocument({
url: OFFSCREEN_URL,
reasons: [chrome.offscreen.Reason.USER_MEDIA],
justification: 'Hosts MediaRecorder for tab screencast.',
})
}

async function closeOffscreen(): Promise<void> {
if (await chrome.offscreen.hasDocument()) {
await chrome.offscreen.closeDocument()
}
}

async function updateBadge(tabId: number): Promise<void> {
const state = await getState()
if (!state) {
await chrome.action.setBadgeText({ text: '', tabId })
return
}
const elapsed = Math.floor((Date.now() - state.startedAt) / 1000)
const minutes = Math.floor(elapsed / 60)
const seconds = String(elapsed % 60).padStart(2, '0')
await chrome.action.setBadgeText({ text: `${minutes}:${seconds}`, tabId })
await chrome.action.setBadgeBackgroundColor({ color: '#ec235a', tabId })
}

async function start(tabId: number, originPattern: string): Promise<void> {
await setState({ tabId, startedAt: Date.now(), originPattern })
await ensureOffscreen()
await chrome.alarms.create(BADGE_ALARM, { periodInMinutes: 1 / 60 })
await updateBadge(tabId)
console.log('[bug-recorder] start', { tabId, originPattern })
}

async function stop(): Promise<void> {
const state = await getState()
await clearState()
await chrome.alarms.clear(BADGE_ALARM)
if (state) {
await chrome.action.setBadgeText({ text: '', tabId: state.tabId })
}
await closeOffscreen()
console.log('[bug-recorder] stop')
}

onMessage(async msg => {
switch (msg.type) {
case 'START':
await start(msg.tabId, msg.originPattern)
return
case 'STOP':
await stop()
return
case 'GET_STATUS': {
const state = await getState()
const status: Status = state
? { recording: true, ...state }
: { recording: false }
return status
}
}
})

chrome.alarms.onAlarm.addListener(async alarm => {
if (alarm.name !== BADGE_ALARM) return
const state = await getState()
if (!state) {
await chrome.alarms.clear(BADGE_ALARM)
return
}
await updateBadge(state.tabId)
})

chrome.tabs.onRemoved.addListener(async tabId => {
const state = await getState()
if (state && state.tabId === tabId) {
console.log('[bug-recorder] tab closed during recording — cancelling')
await stop()
}
})

console.log('[bug-recorder] service worker loaded')
19 changes: 19 additions & 0 deletions src/lib/messaging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Request } from '@/types/messages'

export function sendMessage<R = unknown>(message: Request): Promise<R> {
return chrome.runtime.sendMessage(message)
}

type Handler = (msg: Request) => Promise<unknown>

export function onMessage(handler: Handler): void {
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
handler(msg as Request)
.then(sendResponse)
.catch(err => {
console.error('[bug-recorder] message handler error', err)
sendResponse(undefined)
})
return true
})
}
30 changes: 30 additions & 0 deletions src/lib/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const RECORDER_PERMISSIONS = ['debugger', 'tabCapture'] as const

export function originPattern(url: string): string {
const u = new URL(url)
return `${u.protocol}//${u.hostname}/*`
}

export function isRecordableUrl(url: string | undefined): boolean {
if (!url) return false
try {
const u = new URL(url)
return u.protocol === 'http:' || u.protocol === 'https:'
} catch {
return false
}
}

export function requestRecorderPermissions(origin: string): Promise<boolean> {
return chrome.permissions.request({
permissions: [...RECORDER_PERMISSIONS],
origins: [origin],
})
}

export function hasRecorderPermissions(origin: string): Promise<boolean> {
return chrome.permissions.contains({
permissions: [...RECORDER_PERMISSIONS],
origins: [origin],
})
}
20 changes: 20 additions & 0 deletions src/lib/state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export type RecordingState = {
tabId: number
startedAt: number
originPattern: string
}

const KEY = 'recordingState'

export async function getState(): Promise<RecordingState | null> {
const result = await chrome.storage.session.get(KEY)
return (result[KEY] as RecordingState | undefined) ?? null
}

export async function setState(state: RecordingState): Promise<void> {
await chrome.storage.session.set({ [KEY]: state })
}

export async function clearState(): Promise<void> {
await chrome.storage.session.remove(KEY)
}
10 changes: 10 additions & 0 deletions src/offscreen/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Bug Recorder offscreen</title>
</head>
<body>
<script type="module" src="./index.ts"></script>
</body>
</html>
1 change: 1 addition & 0 deletions src/offscreen/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('[bug-recorder] offscreen document loaded')
97 changes: 95 additions & 2 deletions src/popup/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,101 @@
import { useEffect, useState } from 'react'
import { sendMessage } from '@/lib/messaging'
import {
isRecordableUrl,
originPattern,
requestRecorderPermissions,
} from '@/lib/permissions'
import type { Status } from '@/types/messages'

type UiState =
| { kind: 'loading' }
| { kind: 'unsupported'; reason: string }
| { kind: 'idle'; tab: chrome.tabs.Tab; deniedOnce: boolean }
| { kind: 'recording' }

export default function App() {
const [ui, setUi] = useState<UiState>({ kind: 'loading' })

useEffect(() => {
void load()
}, [])

async function load() {
const status = await sendMessage<Status>({ type: 'GET_STATUS' })
if (status?.recording) {
setUi({ kind: 'recording' })
return
}
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
if (!tab || !isRecordableUrl(tab.url)) {
setUi({
kind: 'unsupported',
reason: 'Open a regular http(s) page to record.',
})
return
}
setUi({ kind: 'idle', tab, deniedOnce: false })
}

async function start(tab: chrome.tabs.Tab) {
if (!tab.id || !tab.url) return
const pattern = originPattern(tab.url)
const granted = await requestRecorderPermissions(pattern)
if (!granted) {
setUi({ kind: 'idle', tab, deniedOnce: true })
return
}
await sendMessage({
type: 'START',
tabId: tab.id,
originPattern: pattern,
})
window.close()
}

async function stop() {
await sendMessage({ type: 'STOP' })
window.close()
}

if (ui.kind === 'loading') {
return (
<div className="popup">
<p className="caption">Loading…</p>
</div>
)
}

if (ui.kind === 'unsupported') {
return (
<div className="popup">
<h1>Bug Recorder</h1>
<p className="caption">{ui.reason}</p>
</div>
)
}

if (ui.kind === 'recording') {
return (
<div className="popup">
<button className="btn btn-stop" onClick={stop}>
Stop recording
</button>
<p className="caption">Click when you have reproduced the bug.</p>
</div>
)
}

return (
<div className="popup">
<h1>Bug Recorder</h1>
<p className="caption">Scaffold ready — UI coming in stage 1.</p>
<button className="btn btn-start" onClick={() => start(ui.tab)}>
Start recording
</button>
<p className="caption">
{ui.deniedOnce
? 'Permissions are required to record. Click Start again.'
: 'This will reload the page and start recording.'}
</p>
</div>
)
}
31 changes: 30 additions & 1 deletion src/popup/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,36 @@ body {
}

.popup .caption {
margin: 0;
margin: 12px 0 0;
color: #666;
font-size: 12px;
}

.btn {
width: 180px;
height: 36px;
border: none;
border-radius: 18px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 120ms ease;
}

.btn-start {
background: #f5f5f5;
color: #ec235a;
}

.btn-start:hover {
background: #ebebeb;
}

.btn-stop {
background: #ec235a;
color: #fff;
}

.btn-stop:hover {
background: #d61e51;
}
19 changes: 19 additions & 0 deletions src/types/messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export type StartRequest = {
type: 'START'
tabId: number
originPattern: string
}

export type StopRequest = {
type: 'STOP'
}

export type GetStatusRequest = {
type: 'GET_STATUS'
}

export type Request = StartRequest | StopRequest | GetStatusRequest

export type Status =
| { recording: false }
| { recording: true; tabId: number; startedAt: number; originPattern: string }
11 changes: 8 additions & 3 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ export default defineConfig({
crx({ manifest }),
zip({ outDir: 'release', outFileName: `crx-${name}-${version}.zip` }),
],
build: {
rollupOptions: {
input: {
offscreen: 'src/offscreen/index.html',
},
},
},
server: {
cors: {
origin: [
/chrome-extension:\/\//,
],
origin: [/chrome-extension:\/\//],
},
},
})