Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

refactor: add logger, typed state machine, and dev scripts

Luis Ortize70fe3d1e818
diff --git a/package.json b/package.json
index 61be644..1be3b32 100644
--- a/package.json
+++ b/package.json
@@ -4,6 +4,9 @@
"description": "",
"main": "index.js",
"scripts": {
+ "dev": "wxt",
+ "build": "wxt build",
+ "zip": "wxt zip",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
diff --git a/src/capture/ai-description.ts b/src/capture/ai-description.ts
index 7971942..f28bdde 100644
--- a/src/capture/ai-description.ts
+++ b/src/capture/ai-description.ts
@@ -1,3 +1,4 @@
+import { logger } from '@/lib/logger';
import OpenAI from 'openai';
import type { ElementMeta } from '@/guides/types';
@@ -50,7 +51,7 @@ export async function getAIDescription(
return block.type === 'text' ? block.text.trim() : null;
}
} catch (err) {
- console.error('[Mimik] AI description failed, using fallback', err);
+ logger.error(' AI description failed, using fallback', err);
return null;
}
}
diff --git a/src/capture/events.ts b/src/capture/events.ts
index b2aa250..56fd810 100644
--- a/src/capture/events.ts
+++ b/src/capture/events.ts
@@ -1,3 +1,4 @@
+import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { extractElementMeta } from './element-meta';
@@ -104,7 +105,7 @@ export function startCapture(guideId: string): () => void {
function enqueue(fn: () => void) {
eventQueue = eventQueue.then(() => {
- try { fn(); } catch (err) { console.warn('[Mimik] Event handler error', err); }
+ try { fn(); } catch (err) { logger.warn(' Event handler error', err); }
});
}
@@ -146,7 +147,7 @@ export function startCapture(guideId: string): () => void {
function sendAction(action: string, meta: ReturnType<typeof extractElementMeta>) {
sendMessage('userAction', { guideId, action, elementMeta: meta })
- .catch(err => console.warn('[Mimik] Failed to send action', err));
+ .catch(err => logger.warn(' Failed to send action', err));
}
function resetWindow() {
@@ -172,7 +173,7 @@ export function startCapture(guideId: string): () => void {
const meta = extractElementMeta(target);
sendAction(action, meta);
} catch (err) {
- console.warn('[Mimik] Failed to capture action', err);
+ logger.warn(' Failed to capture action', err);
}
}
@@ -227,7 +228,7 @@ export function startCapture(guideId: string): () => void {
const meta = extractElementMeta(target);
sendAction(`keydown:${e.key}`, meta);
} catch (err) {
- console.warn('[Mimik] Failed to capture keydown', err);
+ logger.warn(' Failed to capture keydown', err);
}
});
}
@@ -245,7 +246,7 @@ export function startCapture(guideId: string): () => void {
const meta = extractElementMeta(target);
sendAction('input', meta);
} catch (err) {
- console.warn('[Mimik] Failed to capture input', err);
+ logger.warn(' Failed to capture input', err);
}
});
}
@@ -260,7 +261,7 @@ export function startCapture(guideId: string): () => void {
const meta = extractElementMeta(target);
sendAction(e.type, meta); // 'copy', 'paste', or 'cut'
} catch (err) {
- console.warn('[Mimik] Failed to capture clipboard', err);
+ logger.warn(' Failed to capture clipboard', err);
}
});
}
@@ -289,7 +290,7 @@ export function startCapture(guideId: string): () => void {
const meta = extractElementMeta(target);
sendAction('drag', meta);
} catch (err) {
- console.warn('[Mimik] Failed to capture drag', err);
+ logger.warn(' Failed to capture drag', err);
}
});
}
diff --git a/src/capture/machine.ts b/src/capture/machine.ts
index 2e4c29d..d9fc743 100644
--- a/src/capture/machine.ts
+++ b/src/capture/machine.ts
@@ -1,30 +1,53 @@
-import { createMachine, assign } from 'xstate';
+import { createMachine, assign, type SnapshotFrom } from 'xstate';
+
+export const CaptureState = {
+ IDLE: 'IDLE',
+ RECORDING: 'RECORDING',
+} as const;
+
+export type CaptureStateValue = (typeof CaptureState)[keyof typeof CaptureState];
+
+type CaptureEvent =
+ | { type: 'START_RECORDING'; url?: string }
+ | { type: 'STOP_RECORDING' }
+ | { type: 'USER_ACTION' }
+ | { type: 'URL_CHANGED'; url: string };
+
+interface CaptureContext {
+ currentGuideId: string | null;
+ stepCount: number;
+ currentUrl: string;
+}
export const captureMachine = createMachine({
id: 'capture',
- initial: 'idle',
+ initial: CaptureState.IDLE,
+ types: {} as {
+ context: CaptureContext;
+ events: CaptureEvent;
+ },
context: {
- currentGuideId: null as string | null,
+ currentGuideId: null,
stepCount: 0,
- currentUrl: '' as string,
+ currentUrl: '',
},
states: {
- idle: {
+ [CaptureState.IDLE]: {
on: {
START_RECORDING: {
- target: 'recording',
+ target: CaptureState.RECORDING,
actions: assign({
currentGuideId: () => crypto.randomUUID(),
stepCount: 0,
- currentUrl: ({ event }) => (event as { type: 'START_RECORDING'; url?: string }).url ?? '',
+ currentUrl: ({ event }) => event.url ?? '',
}),
},
},
},
- recording: {
+ [CaptureState.RECORDING]: {
on: {
STOP_RECORDING: {
- target: 'idle',
+ target: CaptureState.IDLE,
actions: assign({
currentGuideId: null,
stepCount: 0,
@@ -36,12 +59,14 @@ export const captureMachine = createMachine({
stepCount: ({ context }) => context.stepCount + 1,
}),
},
- SPA_NAVIGATE: {
+ URL_CHANGED: {
actions: assign({
- currentUrl: ({ event }) => (event as { type: 'SPA_NAVIGATE'; url: string }).url,
+ currentUrl: ({ event }) => event.url,
}),
},
},
},
},
});
+
+export type CaptureSnapshot = SnapshotFrom<typeof captureMachine>;
diff --git a/src/entrypoints/background/actor.ts b/src/entrypoints/background/actor.ts
index f2fa982..e967294 100644
--- a/src/entrypoints/background/actor.ts
+++ b/src/entrypoints/background/actor.ts
@@ -1,6 +1,8 @@
+import { logger } from '@/lib/logger';
import { sessionStorage } from '@/lib/browser-api';
import { createActor } from 'xstate';
-import { captureMachine } from '@/capture/machine';
+import { captureMachine, type CaptureSnapshot, type CaptureStateValue } from '@/capture/machine';
+import type { PanelStateUpdate } from '@/lib/port';
import type { ActorRef } from './types';
const STORAGE_KEY = 'machineSnapshot';
@@ -8,10 +10,14 @@ const STORAGE_KEY = 'machineSnapshot';
let actor: ActorRef;
let readyResolve!: () => void;
-export const ready = new Promise<void>((resolve) => {
+const readyPromise = new Promise<void>((resolve) => {
readyResolve = resolve;
});
+export function waitUntilReady(): Promise<void> {
+ return readyPromise;
+}
+
export function getActor(): ActorRef {
return actor;
}
@@ -19,26 +25,39 @@ export function getActor(): ActorRef {
export async function initActor(): Promise<void> {
try {
const result = await sessionStorage.get(STORAGE_KEY);
- const snapshot = result[STORAGE_KEY] ?? undefined;
+ const snapshot = (result[STORAGE_KEY] as CaptureSnapshot) ?? undefined;
actor = createActor(captureMachine, { snapshot });
actor.start();
+ logger.info('Actor restored from snapshot β†’ state:', actor.getSnapshot().value);
} catch (err) {
- console.warn('[Mimik] Failed to restore snapshot, starting fresh', err);
+ logger.warn('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 });
+ const snap = actor.getSnapshot();
+ logger.debug('State transition β†’', snap.value, '| steps:', snap.context.stepCount);
+ sessionStorage.set({ [STORAGE_KEY]: actor.getPersistedSnapshot() });
});
readyResolve();
+ logger.info('Actor ready');
+}
+
+export function getStateUpdate(): PanelStateUpdate {
+ const snap = actor.getSnapshot();
+ return {
+ type: 'STATE_UPDATE',
+ state: snap.value as CaptureStateValue,
+ stepCount: snap.context.stepCount,
+ currentGuideId: snap.context.currentGuideId,
+ };
}
export function initActorFallback(): void {
- console.error('[Mimik] initActor failed, starting fresh');
+ logger.error(' initActor failed, starting fresh');
actor = createActor(captureMachine);
actor.start();
readyResolve();
diff --git a/src/export/pdf-export.ts b/src/export/pdf-export.ts
index 799e4a0..da113de 100644
--- a/src/export/pdf-export.ts
+++ b/src/export/pdf-export.ts
@@ -1,3 +1,4 @@
+import { logger } from '@/lib/logger';
import { jsPDF } from 'jspdf';
import type { Guide, Step, Screenshot } from '@/guides/types';
@@ -64,7 +65,7 @@ export async function exportGuideAsPDF(
doc.addImage(dataUrl, 'JPEG', margin, y, imgWidth, finalHeight);
y += finalHeight + 8;
} catch (err) {
- console.warn('[Mimik] PDF: failed to embed screenshot for step', step.index, err);
+ logger.warn(' PDF: failed to embed screenshot for step', step.index, err);
y += 4;
}
}
diff --git a/src/guides/messages.ts b/src/guides/messages.ts
index e0fd119..a6c4eae 100644
--- a/src/guides/messages.ts
+++ b/src/guides/messages.ts
@@ -26,7 +26,7 @@ export interface RrwebChunkMessage {
timestamp: number;
}
export interface SpaNavigateMessage {
- type: 'SPA_NAVIGATE';
+ type: 'URL_CHANGED';
url: string;
guideId: string;
}
diff --git a/src/lib/logger.ts b/src/lib/logger.ts
new file mode 100644
index 0000000..3ab5ba3
--- /dev/null
+++ b/src/lib/logger.ts
@@ -0,0 +1,25 @@
+/* eslint-disable no-console */
+
+const DEV = import.meta.env.COMMAND === 'serve';
+
+const STYLES = {
+ debug: 'color:gray',
+ info: 'color:green;font-weight:bold',
+ warn: 'color:orange;font-weight:bold',
+ error: 'color:red;font-weight:bold',
+} as const;
+
+type LogFn = (...args: unknown[]) => void;
+
+function bind(level: 'log' | 'info' | 'warn' | 'error', style: string): LogFn {
+ return console[level].bind(console, `%c mimik `, style);
+}
+
+const silent: LogFn = () => {};
+
+export const logger = {
+ debug: DEV ? bind('log', STYLES.debug) : silent,
+ info: DEV ? bind('info', STYLES.info) : silent,
+ warn: DEV ? bind('warn', STYLES.warn) : silent,
+ error: bind('error', STYLES.error),
+};
diff --git a/src/sidepanel/StepCard.tsx b/src/sidepanel/StepCard.tsx
index 54bfc19..59710d4 100644
--- a/src/sidepanel/StepCard.tsx
+++ b/src/sidepanel/StepCard.tsx
@@ -1,3 +1,4 @@
+import { logger } from '@/lib/logger';
import { useState, useEffect } from 'react';
import { Trash2, GripVertical, EyeOff, Copy, Check } from 'lucide-react';
import type { Step, Screenshot } from '@/guides/types';
@@ -66,7 +67,7 @@ export default function StepCard({
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch (err) {
- console.error('[Mimik] Copy to clipboard failed', err);
+ logger.error(' Copy to clipboard failed', err);
}
};
diff --git a/wxt.config.ts b/wxt.config.ts
index 01221d2..9900409 100644
--- a/wxt.config.ts
+++ b/wxt.config.ts
@@ -5,6 +5,9 @@ export default defineConfig({
modules: ["@wxt-dev/module-react"],
srcDir: "src",
imports: false,
+ webExt: {
+ chromiumArgs: ['--user-data-dir=/home/light/.config/chromium'],
+ },
alias: {
'@': 'src',
},