π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
refactor: restructure project with hybrid architecture
Luis Ortiz6dbda8b6a400
diff --git a/.gitignore b/.gitignoreindex 0469ec4..a48174c 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,5 @@ node_modules/.wxt/dist/.planning/+docs/+.source/diff --git a/entrypoints/background.ts b/entrypoints/background.tsdeleted file mode 100644index 676b434..0000000--- a/entrypoints/background.ts+++ /dev/null@@ -1,345 +0,0 @@-import { defineBackground } from 'wxt/utils/define-background';-import { createActor } from 'xstate';-import { captureMachine } from '../src/background/machine';-import { captureAnnotated } from '../src/background/screenshot';-import { buildFallbackDescription } from '../src/background/step-description';-import { getAIDescription } from '../src/background/ai-description';-import { db } from '../src/shared/db-schema';--export default defineBackground(() => {- chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });-- let actorReadyResolve!: () => void;- const actorReady = new Promise<void>(resolve => {- actorReadyResolve = resolve;- });-- let actor: ReturnType<typeof createActor<typeof captureMachine>>;-- async function startActor() {- try {- const result = await chrome.storage.session.get('machineSnapshot');- const snapshot = result.machineSnapshot ?? undefined;- actor = createActor(captureMachine, { snapshot });- actor.start();- } catch (err) {- console.warn('[Mimik] Failed to restore snapshot, starting fresh', err);- await chrome.storage.session.remove('machineSnapshot');- actor = createActor(captureMachine);- actor.start();- }-- actor.subscribe(() => {- const persisted = actor.getPersistedSnapshot();- chrome.storage.session.set({ machineSnapshot: persisted });- });-- actorReadyResolve();- }-- startActor().catch((err) => {- console.error('[Mimik] startActor failed', err);- actor = createActor(captureMachine);- actor.start();- actorReadyResolve();- });-- let captureQueue: Promise<void> = Promise.resolve();-- function enqueueCaptureStep(fn: () => Promise<void>): void {- captureQueue = captureQueue.then(fn).catch(err =>- console.error('[Mimik] Capture error', err)- );- }-- function isInjectableTab(tab: chrome.tabs.Tab): boolean {- const url = tab.url || tab.pendingUrl || '';- if (!url || url.startsWith('chrome://') || url.startsWith('chrome-extension://') ||- url.startsWith('chrome.google.com/webstore') || url.startsWith('about:')) return false;- return /^https?:/.test(url);- }-- async function injectContentScript(tabId: number): Promise<void> {- try {- await chrome.tabs.sendMessage(tabId, { type: 'PING' });- } catch {- try {- await chrome.scripting.executeScript({- target: { tabId, allFrames: true },- files: ['content-scripts/content.js'],- });- } catch (err) {- }- }- }-- async function injectAllTabs(): Promise<void> {- try {- const windows = await chrome.windows.getAll({ populate: true });- for (const win of windows) {- for (const tab of win.tabs || []) {- if (tab.id && isInjectableTab(tab)) {- injectContentScript(tab.id);- }- }- }- } catch (err) {- console.warn('[Mimik] injectAllTabs failed', err);- }- }-- async function broadcastStartCapture(guideId: string): Promise<void> {- try {- const tabs = await chrome.tabs.query({});- for (const tab of tabs) {- if (tab.id && isInjectableTab(tab)) {- chrome.tabs.sendMessage(tab.id, { type: 'START_CAPTURE', guideId }).catch(() => {});- }- }- } catch (err) {- console.warn('[Mimik] broadcastStartCapture failed', err);- }- }-- async function broadcastStopCapture(): Promise<void> {- try {- const tabs = await chrome.tabs.query({});- for (const tab of tabs) {- if (tab.id) {- chrome.tabs.sendMessage(tab.id, { type: 'STOP_CAPTURE' }).catch(() => {});- }- }- } catch (err) {- console.warn('[Mimik] broadcastStopCapture failed', err);- }- }-- injectAllTabs();-- chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {- if (msg.type === 'PING') {- sendResponse({ alive: true });- return true;- }-- if (msg.type === 'GET_STATE') {- (async () => {- try {- await actorReady;- const snap = actor.getSnapshot();- sendResponse({- state: snap.value ?? 'unknown',- stepCount: snap.context.stepCount,- currentGuideId: snap.context.currentGuideId,- });- } catch (err) {- console.error('[Mimik] GET_STATE failed', err);- sendResponse({ state: 'unknown' });- }- })();- return true;- }-- if (msg.type === 'START_RECORDING') {- (async () => {- try {- await actorReady;- actor.send({ type: 'START_RECORDING', url: msg.url });-- const guideId = actor.getSnapshot().context.currentGuideId!;-- await db.guides.add({- id: guideId,- title: 'Untitled Guide',- createdAt: Date.now(),- updatedAt: Date.now(),- stepIds: [],- starred: false,- deletedAt: null,- });-- await broadcastStartCapture(guideId);-- sendResponse({ guideId });- } catch (err) {- console.error('[Mimik] START_RECORDING failed', err);- sendResponse({ error: String(err) });- }- })();- return true;- }-- if (msg.type === 'STOP_RECORDING') {- (async () => {- try {- await actorReady;-- const guideId = actor.getSnapshot().context.currentGuideId;-- await broadcastStopCapture();-- actor.send({ type: 'STOP_RECORDING' });- sendResponse({ success: true, guideId });- } catch (err) {- console.error('[Mimik] STOP_RECORDING failed', err);- sendResponse({ error: String(err) });- }- })();- return true;- }-- if (msg.type === 'USER_ACTION') {- (async () => {- await actorReady;-- const snap = actor.getSnapshot();- if (snap.value !== 'recording') {- sendResponse({ ignored: true });- return;- }-- const stepIndex = actor.getSnapshot().context.stepCount;- actor.send({ type: 'USER_ACTION' });- const guideId = snap.context.currentGuideId!;- const stepId = crypto.randomUUID();- const tabId = sender.tab?.id;-- if (!tabId) {- sendResponse({ error: 'no tabId' });- return;- }-- sendResponse({ stepId });-- enqueueCaptureStep(async () => {- const fallbackDescription = buildFallbackDescription(msg.action, msg.elementMeta);- const currentUrl = snap.context.currentUrl;-- let screenshotId: string | undefined;- let screenshotBlob: Blob | undefined;- try {- const screenshot = await captureAnnotated(tabId, stepId, msg.elementMeta);- screenshotId = screenshot.id;- screenshotBlob = screenshot.blob;- } catch (err) {- console.warn('[Mimik] Screenshot capture failed, storing step without screenshot', err);- }-- await db.steps.add({- id: stepId,- guideId,- index: stepIndex,- description: fallbackDescription,- action: msg.action,- url: currentUrl,- timestamp: Date.now(),- screenshotId,- });-- const guide = await db.guides.get(guideId);- if (guide) {- await db.guides.update(guideId, {- stepIds: [...guide.stepIds, stepId],- updatedAt: Date.now(),- });- }-- if (screenshotBlob) {- (async () => {- try {- const settings = await chrome.storage.local.get(['aiApiKey', 'aiProvider']);- if (settings.aiApiKey) {- const provider = (settings.aiProvider as 'openai' | 'anthropic') || 'openai';- const aiDescription = await getAIDescription(- screenshotBlob,- msg.action,- msg.elementMeta,- provider,- settings.aiApiKey- );- if (aiDescription) {- await db.steps.update(stepId, { description: aiDescription });- }- }- } catch (err) {- console.error('[Mimik] AI description update failed', err);- }- })();- }- });- })();- return true;- }-- if (msg.type === 'RRWEB_CHUNK') {- (async () => {- await db.rrwebEvents.add({- id: crypto.randomUUID(),- guideId: msg.guideId,- events: msg.events,- timestamp: msg.timestamp,- });- sendResponse({ stored: true });- })();- return true;- }-- return false;- });-- chrome.webNavigation.onCompleted.addListener(async (details) => {- if (details.frameId !== 0) return;- await actorReady;- const state = actor.getSnapshot();- if (state.value === 'recording') {- actor.send({ type: 'SPA_NAVIGATE', url: details.url });- }- });-- chrome.webNavigation.onHistoryStateUpdated.addListener(async (details) => {- if (details.frameId !== 0) return;- await actorReady;- const state = actor.getSnapshot();- if (state.value === 'recording') {- actor.send({ type: 'SPA_NAVIGATE', url: details.url });- }- });-- chrome.tabs.onActivated.addListener(async (activeInfo) => {- await actorReady;- const state = actor.getSnapshot();- if (state.value !== 'recording') return;-- const guideId = state.context.currentGuideId;- if (!guideId) return;-- try {- await chrome.tabs.sendMessage(activeInfo.tabId, { type: 'PING' });- } catch {- try {- const tab = await chrome.tabs.get(activeInfo.tabId);- if (isInjectableTab(tab)) {- await injectContentScript(activeInfo.tabId);- }- } catch {- }- }- });-- chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {- if (changeInfo.status !== 'complete') return;- await actorReady;- const state = actor.getSnapshot();- if (state.value !== 'recording') return;- if (!isInjectableTab(tab)) return;-- try {- await chrome.tabs.sendMessage(tabId, { type: 'PING' });- } catch {- try {- await injectContentScript(tabId);- } catch {- }- }- });-});diff --git a/src/background/ai-description.ts b/src/capture/ai-description.tssimilarity index 97%rename from src/background/ai-description.tsrename to src/capture/ai-description.tsindex 61e2f5a..7971942 100644--- a/src/background/ai-description.ts+++ b/src/capture/ai-description.ts@@ -1,5 +1,5 @@import OpenAI from 'openai';-import type { ElementMeta } from '../shared/types';+import type { ElementMeta } from '@/guides/types';export async function getAIDescription(blob: Blob,diff --git a/src/content/element-meta.ts b/src/capture/element-meta.tssimilarity index 95%rename from src/content/element-meta.tsrename to src/capture/element-meta.tsindex c4ca16e..817c0ca 100644--- a/src/content/element-meta.ts+++ b/src/capture/element-meta.ts@@ -1,5 +1,5 @@import { getCssSelector } from 'css-selector-generator';-import type { ElementMeta } from '../shared/types';+import type { ElementMeta } from '@/guides/types';export function extractElementMeta(el: HTMLElement): ElementMeta {const rect = el.getBoundingClientRect();diff --git a/src/content/events.ts b/src/capture/events.tssimilarity index 98%rename from src/content/events.tsrename to src/capture/events.tsindex 158dadb..b2aa250 100644--- a/src/content/events.ts+++ b/src/capture/events.ts@@ -1,3 +1,4 @@+import { sendMessage } from '@/lib/messaging';import { extractElementMeta } from './element-meta';const FOCUSABLE_SELECTOR = 'a[href], button, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [tabindex], [contenteditable="true"]';@@ -144,16 +145,8 @@ export function startCapture(guideId: string): () => void {}function sendAction(action: string, meta: ReturnType<typeof extractElementMeta>) {- try {- chrome.runtime.sendMessage({- type: 'USER_ACTION',- guideId,- action,- elementMeta: meta,- });- } catch (err) {- console.warn('[Mimik] Failed to send action', err);- }+ sendMessage('userAction', { guideId, action, elementMeta: meta })+ .catch(err => console.warn('[Mimik] Failed to send action', err));}function resetWindow() {diff --git a/src/background/machine.ts b/src/capture/machine.tssimilarity index 100%rename from src/background/machine.tsrename to src/capture/machine.tsdiff --git a/src/content/rrweb-recorder.ts b/src/capture/rrweb-recorder.tssimilarity index 84%rename from src/content/rrweb-recorder.tsrename to src/capture/rrweb-recorder.tsindex 236f826..7317b68 100644--- a/src/content/rrweb-recorder.ts+++ b/src/capture/rrweb-recorder.ts@@ -1,3 +1,4 @@+import { sendMessage } from '@/lib/messaging';// @ts-expect-error rrweb 1.1.3 type resolutionimport { record } from 'rrweb';@@ -10,12 +11,8 @@ export function startRrwebRecording(guideId: string): () => void {function flushChunk() {if (eventBuffer.length === 0) return;const chunk = eventBuffer.splice(0);- chrome.runtime.sendMessage({- type: 'RRWEB_CHUNK',- guideId,- events: chunk,- timestamp: Date.now(),- });+ sendMessage('rrwebChunk', { guideId, events: chunk, timestamp: Date.now() })+ .catch(() => {});}const stopRecord = record({diff --git a/src/background/screenshot.ts b/src/capture/screenshot.tssimilarity index 78%rename from src/background/screenshot.tsrename to src/capture/screenshot.tsindex 5f31886..5af311a 100644--- a/src/background/screenshot.ts+++ b/src/capture/screenshot.ts@@ -1,8 +1,9 @@-import { db } from '../shared/db-schema';-import type { Screenshot, ElementMeta } from '../shared/types';+import { captureVisibleTab } from '@/lib/browser-api';+import { db } from '@/guides/db';+import type { Screenshot, ElementMeta } from '@/guides/types';export async function captureAndStore(tabId: number, stepId: string): Promise<Screenshot> {- const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: 'jpeg', quality: 90 });+ const dataUrl = await captureVisibleTab('jpeg', 90);const blob = await fetch(dataUrl).then(r => r.blob());const screenshot: Screenshot = {id: crypto.randomUUID(), stepId, blob, mimeType: 'image/jpeg', width: 0, height: 0,@@ -20,10 +21,7 @@ export async function captureAnnotated(stepId: string,elementMeta: ElementMeta): Promise<Screenshot> {- const dataUrl = await chrome.tabs.captureVisibleTab(null, {- format: 'jpeg',- quality: 90,- });+ const dataUrl = await captureVisibleTab('jpeg', 90);const blob = await fetch(dataUrl).then(r => r.blob());const img = await createImageBitmap(blob);diff --git a/src/content/spa-nav.ts b/src/capture/spa-nav.tssimilarity index 100%rename from src/content/spa-nav.tsrename to src/capture/spa-nav.tsdiff --git a/src/background/step-description.ts b/src/capture/step-description.tssimilarity index 95%rename from src/background/step-description.tsrename to src/capture/step-description.tsindex 7864ccc..2b687cb 100644--- a/src/background/step-description.ts+++ b/src/capture/step-description.ts@@ -1,4 +1,4 @@-import type { ElementMeta } from '../shared/types';+import type { ElementMeta } from '@/guides/types';export function buildFallbackDescription(action: string, meta: ElementMeta): string {const target = meta.ariaLabeldiff --git a/src/entrypoints/background/actor.ts b/src/entrypoints/background/actor.tsnew file mode 100644index 0000000..f2fa982--- /dev/null+++ b/src/entrypoints/background/actor.ts@@ -0,0 +1,45 @@+import { sessionStorage } from '@/lib/browser-api';+import { createActor } from 'xstate';+import { captureMachine } from '@/capture/machine';+import type { ActorRef } from './types';++const STORAGE_KEY = 'machineSnapshot';++let actor: ActorRef;+let readyResolve!: () => void;++export const ready = new Promise<void>((resolve) => {+ readyResolve = resolve;+});++export function getActor(): ActorRef {+ return actor;+}++export async function initActor(): Promise<void> {+ try {+ const result = await sessionStorage.get(STORAGE_KEY);+ const snapshot = result[STORAGE_KEY] ?? undefined;+ actor = createActor(captureMachine, { snapshot });+ actor.start();+ } catch (err) {+ console.warn('[Mimik] Failed to restore snapshot, starting fresh', err);+ await sessionStorage.remove(STORAGE_KEY);+ actor = createActor(captureMachine);+ actor.start();+ }++ actor.subscribe(() => {+ const persisted = actor.getPersistedSnapshot();+ sessionStorage.set({ [STORAGE_KEY]: persisted });+ });++ readyResolve();+}++export function initActorFallback(): void {+ console.error('[Mimik] initActor failed, starting fresh');+ actor = createActor(captureMachine);+ actor.start();+ readyResolve();+}diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.tsnew file mode 100644index 0000000..8efd05e--- /dev/null+++ b/src/entrypoints/background/index.ts@@ -0,0 +1,74 @@+import { defineBackground } from '#imports';+import { setSidePanelBehavior } from '@/lib/browser-api';+import { onMessage } from '@/lib/messaging';+import { db } from '@/guides/db';+import { initActor, initActorFallback, getActor, ready } from './actor';+import { injectAllTabs, broadcastStartCapture, broadcastStopCapture } from './tab-manager';+import { handleUserAction } from './step-pipeline';+import { registerNavigationListeners } from './navigation';++export default defineBackground(() => {+ setSidePanelBehavior(true);++ initActor().catch(initActorFallback);+ injectAllTabs();+ registerNavigationListeners();++ onMessage('ping', () => {+ return { alive: true };+ });++ onMessage('getState', async () => {+ await ready;+ const snap = getActor().getSnapshot();+ return {+ state: (snap.value as string) ?? 'unknown',+ stepCount: snap.context.stepCount,+ currentGuideId: snap.context.currentGuideId,+ };+ });++ onMessage('startRecording', async ({ data }) => {+ await ready;+ const actor = getActor();+ actor.send({ type: 'START_RECORDING', url: data.url });+ const guideId = actor.getSnapshot().context.currentGuideId!;++ await db.guides.add({+ id: guideId,+ title: 'Untitled Guide',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ stepIds: [],+ starred: false,+ deletedAt: null,+ });++ await broadcastStartCapture(guideId);+ return { guideId };+ });++ onMessage('stopRecording', async () => {+ await ready;+ const actor = getActor();+ const guideId = actor.getSnapshot().context.currentGuideId;+ await broadcastStopCapture();+ actor.send({ type: 'STOP_RECORDING' });+ return { success: true, guideId: guideId ?? undefined };+ });++ onMessage('userAction', async (message) => {+ await ready;+ return handleUserAction(message.data, message.sender);+ });++ onMessage('rrwebChunk', async ({ data }) => {+ await db.rrwebEvents.add({+ id: crypto.randomUUID(),+ guideId: data.guideId,+ events: data.events,+ timestamp: data.timestamp,+ });+ return { stored: true };+ });+});diff --git a/src/entrypoints/background/navigation.ts b/src/entrypoints/background/navigation.tsnew file mode 100644index 0000000..ce4ecac--- /dev/null+++ b/src/entrypoints/background/navigation.ts@@ -0,0 +1,59 @@+import { onNavigationCompleted, onHistoryStateUpdated, onTabActivated, onTabUpdated, sendMessageToTab, getTab } from '@/lib/browser-api';+import { isInjectableTab, injectContentScript } from './tab-manager';+import { getActor, ready } from './actor';++export function registerNavigationListeners() {+ onNavigationCompleted(async (details) => {+ if (details.frameId !== 0) return;+ await ready;+ const state = getActor().getSnapshot();+ if (state.value === 'recording') {+ getActor().send({ type: 'SPA_NAVIGATE', url: details.url });+ }+ });++ onHistoryStateUpdated(async (details) => {+ if (details.frameId !== 0) return;+ await ready;+ const state = getActor().getSnapshot();+ if (state.value === 'recording') {+ getActor().send({ type: 'SPA_NAVIGATE', url: details.url });+ }+ });++ onTabActivated(async (activeInfo) => {+ await ready;+ const state = getActor().getSnapshot();+ if (state.value !== 'recording') return;+ if (!state.context.currentGuideId) return;++ try {+ await sendMessageToTab(activeInfo.tabId, { type: 'PING' });+ } catch {+ try {+ const tab = await getTab(activeInfo.tabId);+ if (isInjectableTab(tab)) {+ await injectContentScript(activeInfo.tabId);+ }+ } catch {+ }+ }+ });++ onTabUpdated(async (tabId, changeInfo, tab) => {+ if (changeInfo.status !== 'complete') return;+ await ready;+ const state = getActor().getSnapshot();+ if (state.value !== 'recording') return;+ if (!isInjectableTab(tab)) return;++ try {+ await sendMessageToTab(tabId, { type: 'PING' });+ } catch {+ try {+ await injectContentScript(tabId);+ } catch {+ }+ }+ });+}diff --git a/src/entrypoints/background/step-pipeline.ts b/src/entrypoints/background/step-pipeline.tsnew file mode 100644index 0000000..7f8b640--- /dev/null+++ b/src/entrypoints/background/step-pipeline.ts@@ -0,0 +1,103 @@+import { localStorage } from '@/lib/browser-api';+import { captureAnnotated } from '@/capture/screenshot';+import { buildFallbackDescription } from '@/capture/step-description';+import { getAIDescription } from '@/capture/ai-description';+import { db } from '@/guides/db';+import { getActor } from './actor';+import type { Browser } from '#imports';+import type { ElementMeta } from '@/guides/types';++let captureQueue: Promise<void> = Promise.resolve();++function enqueue(fn: () => Promise<void>): void {+ captureQueue = captureQueue+ .then(fn)+ .catch((err) => console.error('[Mimik] Capture error', err));+}++interface UserActionData {+ guideId: string;+ action: string;+ elementMeta: ElementMeta;+}++export function handleUserAction(+ data: UserActionData,+ sender: Browser.runtime.MessageSender,+): { stepId: string } | { ignored: true } | { error: string } {+ const actor = getActor();+ const snap = actor.getSnapshot();++ if (snap.value !== 'recording') {+ return { ignored: true };+ }++ const stepIndex = snap.context.stepCount;+ actor.send({ type: 'USER_ACTION' });+ const guideId = snap.context.currentGuideId!;+ const stepId = crypto.randomUUID();+ const tabId = sender.tab?.id;++ if (!tabId) {+ return { error: 'no tabId' };+ }++ enqueue(async () => {+ const fallbackDescription = buildFallbackDescription(data.action, data.elementMeta);+ const currentUrl = snap.context.currentUrl;++ let screenshotId: string | undefined;+ let screenshotBlob: Blob | undefined;+ try {+ const screenshot = await captureAnnotated(tabId, stepId, data.elementMeta);+ screenshotId = screenshot.id;+ screenshotBlob = screenshot.blob;+ } catch (err) {+ console.warn('[Mimik] Screenshot capture failed, storing step without screenshot', err);+ }++ await db.steps.add({+ id: stepId,+ guideId,+ index: stepIndex,+ description: fallbackDescription,+ action: data.action,+ url: currentUrl,+ timestamp: Date.now(),+ screenshotId,+ });++ const guide = await db.guides.get(guideId);+ if (guide) {+ await db.guides.update(guideId, {+ stepIds: [...guide.stepIds, stepId],+ updatedAt: Date.now(),+ });+ }++ if (screenshotBlob) {+ (async () => {+ try {+ const settings = await localStorage.get(['aiApiKey', 'aiProvider']);+ if (settings.aiApiKey) {+ const provider = (settings.aiProvider as 'openai' | 'anthropic') || 'openai';+ const aiDescription = await getAIDescription(+ screenshotBlob,+ data.action,+ data.elementMeta,+ provider,+ settings.aiApiKey as string,+ );+ if (aiDescription) {+ await db.steps.update(stepId, { description: aiDescription });+ }+ }+ } catch (err) {+ console.error('[Mimik] AI description update failed', err);+ }+ })();+ }+ });++ return { stepId };+}diff --git a/src/entrypoints/background/tab-manager.ts b/src/entrypoints/background/tab-manager.tsnew file mode 100644index 0000000..d2a87ac--- /dev/null+++ b/src/entrypoints/background/tab-manager.ts@@ -0,0 +1,66 @@+import { sendMessageToTab, executeScript, getAllWindows, queryTabs } from '@/lib/browser-api';++export function isInjectableTab(tab: { url?: string; pendingUrl?: string }): boolean {+ const url = tab.url || tab.pendingUrl || '';+ if (+ !url ||+ url.startsWith('chrome://') ||+ url.startsWith('chrome-extension://') ||+ url.startsWith('chrome.google.com/webstore') ||+ url.startsWith('about:')+ )+ return false;+ return /^https?:/.test(url);+}++export async function injectContentScript(tabId: number): Promise<void> {+ try {+ await sendMessageToTab(tabId, { type: 'PING' });+ } catch {+ try {+ await executeScript(tabId, ['/content-scripts/content.js']);+ } catch {+ }+ }+}++export async function injectAllTabs(): Promise<void> {+ try {+ const windows = await getAllWindows();+ for (const win of windows) {+ for (const tab of win.tabs || []) {+ if (tab.id && isInjectableTab(tab)) {+ injectContentScript(tab.id);+ }+ }+ }+ } catch (err) {+ console.warn('[Mimik] injectAllTabs failed', err);+ }+}++export async function broadcastStartCapture(guideId: string): Promise<void> {+ try {+ const tabs = await queryTabs({});+ for (const tab of tabs) {+ if (tab.id && isInjectableTab(tab)) {+ sendMessageToTab(tab.id, { type: 'START_CAPTURE', guideId }).catch(() => {});+ }+ }+ } catch (err) {+ console.warn('[Mimik] broadcastStartCapture failed', err);+ }+}++export async function broadcastStopCapture(): Promise<void> {+ try {+ const tabs = await queryTabs({});+ for (const tab of tabs) {+ if (tab.id) {+ sendMessageToTab(tab.id, { type: 'STOP_CAPTURE' }).catch(() => {});+ }+ }+ } catch (err) {+ console.warn('[Mimik] broadcastStopCapture failed', err);+ }+}diff --git a/src/entrypoints/background/types.ts b/src/entrypoints/background/types.tsnew file mode 100644index 0000000..01e7f71--- /dev/null+++ b/src/entrypoints/background/types.ts@@ -0,0 +1,5 @@+import type { createActor } from 'xstate';+import type { captureMachine } from '@/capture/machine';++export type ActorRef = ReturnType<typeof createActor<typeof captureMachine>>;+export type ActorReady = Promise<void>;diff --git a/entrypoints/content.ts b/src/entrypoints/content.tssimilarity index 65%rename from entrypoints/content.tsrename to src/entrypoints/content.tsindex d4b840a..c1221c6 100644--- a/entrypoints/content.ts+++ b/src/entrypoints/content.ts@@ -1,9 +1,11 @@+import { browser } from '#imports';import { defineContentScript } from 'wxt/utils/define-content-script';-import { startCapture } from '../src/content/events';-import { startRrwebRecording } from '../src/content/rrweb-recorder';-import { updateUrl } from '../src/content/spa-nav';+import { sendMessage } from '@/lib/messaging';+import { startCapture } from '@/capture/events';+import { startRrwebRecording } from '@/capture/rrweb-recorder';+import { updateUrl } from '@/capture/spa-nav';-const CLEANUP_EVENT = `mimik_remove_content_script_${chrome.runtime.id}`;+const CLEANUP_EVENT = `mimik_remove_content_script_${browser.runtime.id}`;export default defineContentScript({matches: ['<all_urls>'],@@ -36,17 +38,18 @@ export default defineContentScript({function cleanup() {destroyed = true;endCapture();- chrome.runtime.onMessage.removeListener(messageHandler);+ browser.runtime.onMessage.removeListener(messageHandler);document.removeEventListener(CLEANUP_EVENT, cleanup);}document.addEventListener(CLEANUP_EVENT, cleanup);+ window.addEventListener('beforeunload', () => endCapture());- window.addEventListener('beforeunload', () => {- endCapture();- });-- function messageHandler(msg: any, _sender: any, sendResponse: (r: any) => void) {+ function messageHandler(+ msg: Record<string, unknown>,+ _sender: unknown,+ sendResponse: (r: unknown) => void,+ ) {if (destroyed) return false;if (msg.type === 'PING') {@@ -60,7 +63,7 @@ export default defineContentScript({}if (msg.type === 'START_CAPTURE' && msg.guideId) {- beginCapture(msg.guideId);+ beginCapture(msg.guideId as string);sendResponse({ started: true });return true;}@@ -72,7 +75,7 @@ export default defineContentScript({}if (msg.type === 'SPA_NAVIGATE' && msg.url) {- updateUrl(msg.url);+ updateUrl(msg.url as string);sendResponse({ updated: true });return true;}@@ -80,18 +83,16 @@ export default defineContentScript({return false;}- chrome.runtime.onMessage.addListener(messageHandler);+ browser.runtime.onMessage.addListener(messageHandler);- try {- chrome.runtime.sendMessage({ type: 'GET_STATE' }, (response) => {- if (chrome.runtime.lastError) return; // Extension context invalid+ sendMessage('getState', undefined)+ .then(res => {if (destroyed) return;- if (response?.state === 'recording' && response.currentGuideId) {- beginCapture(response.currentGuideId);+ if (res.state === 'recording' && res.currentGuideId) {+ beginCapture(res.currentGuideId);}- });- } catch {- }+ })+ .catch(() => {});console.log('[Mimik] Content script loaded');},diff --git a/entrypoints/fullview/index.html b/src/entrypoints/fullview/index.htmlsimilarity index 100%rename from entrypoints/fullview/index.htmlrename to src/entrypoints/fullview/index.htmldiff --git a/entrypoints/fullview/index.tsx b/src/entrypoints/fullview/index.tsxsimilarity index 62%rename from entrypoints/fullview/index.tsxrename to src/entrypoints/fullview/index.tsxindex a9cd635..8224ec3 100644--- a/entrypoints/fullview/index.tsx+++ b/src/entrypoints/fullview/index.tsx@@ -1,6 +1,6 @@import React from 'react';import ReactDOM from 'react-dom/client';-import FullViewApp from '../../src/fullview/App';-import '../../src/sidepanel/index.css';+import FullViewApp from '@/fullview/App';+import '@/sidepanel/index.css';ReactDOM.createRoot(document.getElementById('root')!).render(<FullViewApp />);diff --git a/entrypoints/options/index.html b/src/entrypoints/options/index.htmlsimilarity index 100%rename from entrypoints/options/index.htmlrename to src/entrypoints/options/index.htmldiff --git a/entrypoints/options/index.tsx b/src/entrypoints/options/index.tsxsimilarity index 63%rename from entrypoints/options/index.tsxrename to src/entrypoints/options/index.tsxindex 0d3aafa..84d3999 100644--- a/entrypoints/options/index.tsx+++ b/src/entrypoints/options/index.tsx@@ -1,6 +1,6 @@import React from 'react';import ReactDOM from 'react-dom/client';-import App from '../../src/options/App';-import '../../src/options/index.css';+import App from '@/options/App';+import '@/options/index.css';ReactDOM.createRoot(document.getElementById('root')!).render(<App />);diff --git a/entrypoints/sidepanel/index.html b/src/entrypoints/sidepanel/index.htmlsimilarity index 100%rename from entrypoints/sidepanel/index.htmlrename to src/entrypoints/sidepanel/index.htmldiff --git a/entrypoints/sidepanel/index.tsx b/src/entrypoints/sidepanel/index.tsxsimilarity index 62%rename from entrypoints/sidepanel/index.tsxrename to src/entrypoints/sidepanel/index.tsxindex 8672d5d..dc1b324 100644--- a/entrypoints/sidepanel/index.tsx+++ b/src/entrypoints/sidepanel/index.tsx@@ -1,6 +1,6 @@import React from 'react';import ReactDOM from 'react-dom/client';-import App from '../../src/sidepanel/App';-import '../../src/sidepanel/index.css';+import App from '@/sidepanel/App';+import '@/sidepanel/index.css';ReactDOM.createRoot(document.getElementById('root')!).render(<App />);diff --git a/src/export/html-export.ts b/src/export/html-export.tsindex 4781a11..2618508 100644--- a/src/export/html-export.ts+++ b/src/export/html-export.ts@@ -1,4 +1,4 @@-import type { Guide, Step, Screenshot } from '../shared/types';+import type { Guide, Step, Screenshot } from '@/guides/types';function blobToBase64(blob: Blob): Promise<string> {return new Promise((resolve, reject) => {diff --git a/src/export/markdown-export.ts b/src/export/markdown-export.tsindex f86e973..ec50f35 100644--- a/src/export/markdown-export.ts+++ b/src/export/markdown-export.ts@@ -1,4 +1,4 @@-import type { Guide, Step, Screenshot } from '../shared/types';+import type { Guide, Step, Screenshot } from '@/guides/types';function blobToBase64(blob: Blob): Promise<string> {return new Promise((resolve, reject) => {diff --git a/src/export/pdf-export.ts b/src/export/pdf-export.tsindex 3125850..799e4a0 100644--- a/src/export/pdf-export.ts+++ b/src/export/pdf-export.ts@@ -1,5 +1,5 @@import { jsPDF } from 'jspdf';-import type { Guide, Step, Screenshot } from '../shared/types';+import type { Guide, Step, Screenshot } from '@/guides/types';function blobToDataUrl(blob: Blob): Promise<string> {return new Promise((resolve, reject) => {diff --git a/src/fullview/App.tsx b/src/fullview/App.tsxindex b02ede2..b866a67 100644--- a/src/fullview/App.tsx+++ b/src/fullview/App.tsx@@ -4,7 +4,7 @@ import TopNav from './TopNav';import LibraryContent from './LibraryContent';import GuideContent from './GuideContent';import GuideOutline from './GuideOutline';-import type { Step } from '../shared/types';+import type { Step } from '@/guides/types';export default function FullViewApp() {const route = useRoute();diff --git a/src/fullview/GuideContent.tsx b/src/fullview/GuideContent.tsxindex f48da4d..a680826 100644--- a/src/fullview/GuideContent.tsx+++ b/src/fullview/GuideContent.tsx@@ -1,9 +1,9 @@import { useState, useEffect, useCallback, useRef } from 'react';-import { getGuide, updateGuideTitle, updateStepDescription, deleteStep, reorderSteps, updateScreenshotBlob } from '../shared/guide-service';-import type { Guide, Step, Screenshot } from '../shared/types';-import StepCard from '../sidepanel/StepCard';-import BlurCanvas from '../sidepanel/BlurCanvas';-import ExportMenu from '../sidepanel/ExportMenu';+import { getGuide, updateGuideTitle, updateStepDescription, deleteStep, reorderSteps, updateScreenshotBlob } from '@/guides/service';+import type { Guide, Step, Screenshot } from '@/guides/types';+import StepCard from '@/sidepanel/StepCard';+import BlurCanvas from '@/sidepanel/BlurCanvas';+import ExportMenu from '@/sidepanel/ExportMenu';import { navigate } from './router';interface GuideContentProps {diff --git a/src/fullview/GuideOutline.tsx b/src/fullview/GuideOutline.tsxindex 1d65d45..a2f4950 100644--- a/src/fullview/GuideOutline.tsx+++ b/src/fullview/GuideOutline.tsx@@ -1,4 +1,4 @@-import type { Step } from '../shared/types';+import type { Step } from '@/guides/types';interface GuideOutlineProps {steps: Step[];diff --git a/src/fullview/LibraryContent.tsx b/src/fullview/LibraryContent.tsxindex 5176a7c..589a031 100644--- a/src/fullview/LibraryContent.tsx+++ b/src/fullview/LibraryContent.tsx@@ -1,9 +1,9 @@import { useState, useEffect, useCallback } from 'react';import { LayoutGrid, LayoutList, Star, Trash2, RotateCcw, FileText } from 'lucide-react';-import { getGuides, getStarredGuides, getTrashedGuides, softDeleteGuide, permanentlyDeleteGuide, restoreGuide, toggleStar, getFirstScreenshot } from '../shared/guide-service';-import type { Guide, Screenshot } from '../shared/types';+import { getGuides, getStarredGuides, getTrashedGuides, softDeleteGuide, permanentlyDeleteGuide, restoreGuide, toggleStar, getFirstScreenshot } from '@/guides/service';+import type { Guide, Screenshot } from '@/guides/types';import { navigate } from './router';-import ZoomScreenshot from '../sidepanel/ZoomScreenshot';+import ZoomScreenshot from '@/sidepanel/ZoomScreenshot';interface LibraryContentProps {category: 'all' | 'starred' | 'trash';diff --git a/src/fullview/Sidebar.tsx b/src/fullview/Sidebar.tsxindex a723ab6..ea14cf7 100644--- a/src/fullview/Sidebar.tsx+++ b/src/fullview/Sidebar.tsx@@ -1,7 +1,7 @@import { FileText, Star, Trash2, ArrowLeft } from 'lucide-react';import type { Route } from './router';import { navigate } from './router';-import type { Step } from '../shared/types';+import type { Step } from '@/guides/types';interface SidebarProps {route: Route;@@ -43,7 +43,7 @@ export default function Sidebar({onClick={() => onStepClick?.(step.id)}className={`w-full text-left px-3 py-1.5 rounded-md text-sm flex items-center gap-2 transition-colors ${activeStepId === step.id- ? 'bg-blue-50 text-blue-700'+ ? 'bg-amber-50 text-amber-700': 'text-gray-600 hover:bg-gray-50'}`}>diff --git a/src/shared/db-schema.ts b/src/guides/db.tssimilarity index 100%rename from src/shared/db-schema.tsrename to src/guides/db.tsdiff --git a/src/shared/messages.ts b/src/guides/messages.tssimilarity index 100%rename from src/shared/messages.tsrename to src/guides/messages.tsdiff --git a/src/shared/guide-service.ts b/src/guides/service.tssimilarity index 99%rename from src/shared/guide-service.tsrename to src/guides/service.tsindex 548c416..20c61db 100644--- a/src/shared/guide-service.ts+++ b/src/guides/service.ts@@ -1,4 +1,4 @@-import { db } from './db-schema';+import { db } from './db';import type { Guide, Step, Screenshot } from './types';export async function getGuides(): Promise<Guide[]> {diff --git a/src/shared/types.ts b/src/guides/types.tssimilarity index 100%rename from src/shared/types.tsrename to src/guides/types.tsdiff --git a/src/sidepanel/BlurCanvas.tsx b/src/sidepanel/BlurCanvas.tsxindex e3b8490..ddc2cc2 100644--- a/src/sidepanel/BlurCanvas.tsx+++ b/src/sidepanel/BlurCanvas.tsx@@ -1,6 +1,6 @@import { useRef, useState, useEffect, useCallback } from 'react';import { Undo, Check, X } from 'lucide-react';-import type { Screenshot } from '../shared/types';+import type { Screenshot } from '@/guides/types';interface BlurCanvasProps {screenshot: Screenshot;diff --git a/src/sidepanel/ExportMenu.tsx b/src/sidepanel/ExportMenu.tsxindex f0c25c4..cf32756 100644--- a/src/sidepanel/ExportMenu.tsx+++ b/src/sidepanel/ExportMenu.tsx@@ -1,9 +1,9 @@import { useState, useEffect, useRef } from 'react';import { Download, FileCode, FileText, FileDown, Loader2 } from 'lucide-react';-import type { Guide, Step, Screenshot } from '../shared/types';-import { exportGuideAsHTML } from '../export/html-export';-import { exportGuideAsMarkdown } from '../export/markdown-export';-import { exportGuideAsPDF } from '../export/pdf-export';+import type { Guide, Step, Screenshot } from '@/guides/types';+import { exportGuideAsHTML } from '@/export/html-export';+import { exportGuideAsMarkdown } from '@/export/markdown-export';+import { exportGuideAsPDF } from '@/export/pdf-export';interface ExportMenuProps {guideId: string;diff --git a/src/sidepanel/StepCard.tsx b/src/sidepanel/StepCard.tsxindex 69d5d7f..54bfc19 100644--- a/src/sidepanel/StepCard.tsx+++ b/src/sidepanel/StepCard.tsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import { Trash2, GripVertical, EyeOff, Copy, Check } from 'lucide-react';-import type { Step, Screenshot } from '../shared/types';+import type { Step, Screenshot } from '@/guides/types';import ZoomScreenshot from './ZoomScreenshot';interface DragHandleProps {diff --git a/src/sidepanel/ZoomScreenshot.tsx b/src/sidepanel/ZoomScreenshot.tsxindex d6bd135..3b5dc59 100644--- a/src/sidepanel/ZoomScreenshot.tsx+++ b/src/sidepanel/ZoomScreenshot.tsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef } from 'react';-import type { Screenshot } from '../shared/types';+import type { Screenshot } from '@/guides/types';interface ZoomScreenshotProps {screenshot: Screenshot;diff --git a/tsconfig.json b/tsconfig.jsonindex 26e654a..33b1608 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,19 +1,13 @@{+ "extends": "./.wxt/tsconfig.json","compilerOptions": {- "target": "ESNext",- "module": "ESNext",- "moduleResolution": "Bundler",- "strict": true,"jsx": "react-jsx","lib": ["ESNext", "DOM", "DOM.Iterable"],- "skipLibCheck": true,- "resolveJsonModule": true,"allowImportingTsExtensions": true,- "noEmit": true,+ "noExplicitAny": true,"paths": {"@/*": ["./src/*"]}},- "include": ["entrypoints*", "tests/**/*", "wxt.config.ts"],- "exclude": ["node_modules", ".output", ".wxt"]+ "include": ["src/entrypoints*", "tests/**/*", "wxt.config.ts", ".wxt/wxt.d.ts"]}diff --git a/wxt.config.ts b/wxt.config.tsindex 5606e0d..01221d2 100644--- a/wxt.config.ts+++ b/wxt.config.ts@@ -1,20 +1,34 @@-import { defineConfig } from 'wxt';-import tailwindcss from '@tailwindcss/vite';+import { defineConfig } from "wxt";+import tailwindcss from "@tailwindcss/vite";export default defineConfig({- modules: ['@wxt-dev/module-react'],+ modules: ["@wxt-dev/module-react"],+ srcDir: "src",+ imports: false,+ alias: {+ '@': 'src',+ },vite: () => ({plugins: [tailwindcss()],}),manifest: {- name: 'Mimik',- description: 'Auto-capture browser workflows and generate step-by-step guides with annotated screenshots.',- permissions: ['storage', 'activeTab', 'tabs', 'scripting', 'unlimitedStorage', 'sidePanel', 'webNavigation'],- host_permissions: ['<all_urls>'],- minimum_chrome_version: '118',+ name: "Mimik",+ description:+ "Auto-capture browser workflows and generate step-by-step guides with annotated screenshots.",+ permissions: [+ "storage",+ "activeTab",+ "tabs",+ "scripting",+ "unlimitedStorage",+ "sidePanel",+ "webNavigation",+ ],+ host_permissions: ["<all_urls>"],+ minimum_chrome_version: "118",action: {},side_panel: {- default_path: 'sidepanel/index.html',+ default_path: "sidepanel/index.html",},},});