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 πŸ“–

test: add comprehensive tests for core business logic

Luis Ortiz55173d4d715f
diff --git a/src/core/blur/__tests__/regexes.test.ts b/src/core/blur/__tests__/regexes.test.ts
new file mode 100644
index 0000000..95333f3
--- /dev/null
+++ b/src/core/blur/__tests__/regexes.test.ts
@@ -0,0 +1,350 @@
+import { describe, expect, it } from 'vitest';
+import { findMatches, PRESET_LABELS, PRESET_REGEXES, type PresetKey } from '../regexes';
+
+describe('PRESET_LABELS', () => {
+ it('has a label for every preset key', () => {
+ const keys: PresetKey[] = ['email', 'phone', 'ssn', 'creditCard', 'ipAddress', 'macAddress'];
+ for (const key of keys) {
+ expect(PRESET_LABELS[key]).toBeDefined();
+ expect(typeof PRESET_LABELS[key]).toBe('string');
+ expect(PRESET_LABELS[key].length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('email regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.email;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches standard email addresses', () => {
+ expect('[email protected]').toMatch(regex());
+ expect('[email protected]').toMatch(regex());
+ expect('[email protected]').toMatch(regex());
+ });
+
+ it('matches emails with numbers and special chars in local part', () => {
+ expect('[email protected]').toMatch(regex());
+ expect('[email protected]').toMatch(regex());
+ expect('a%[email protected]').toMatch(regex());
+ });
+
+ it('matches email embedded in surrounding text', () => {
+ const r = regex();
+ const match = r.exec('Contact us at [email protected] for help');
+ expect(match).not.toBeNull();
+ expect(match![0]).toBe('[email protected]');
+ });
+
+ it('does not match strings without @', () => {
+ expect('notanemail.com').not.toMatch(regex());
+ });
+
+ it('does not match strings without TLD', () => {
+ expect('user@localhost').not.toMatch(regex());
+ });
+
+ it('is case insensitive', () => {
+ expect('[email protected]').toMatch(regex());
+ expect('[email protected]').toMatch(regex());
+ });
+});
+
+describe('phone regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.phone;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches US phone numbers', () => {
+ expect('555-123-4567').toMatch(regex());
+ expect('(555) 123-4567').toMatch(regex());
+ expect('555.123.4567').toMatch(regex());
+ });
+
+ it('matches international format with country code', () => {
+ expect('+1 555-123-4567').toMatch(regex());
+ expect('+44 20 7946 0958').toMatch(regex());
+ });
+
+ it('matches phone number embedded in text', () => {
+ const r = regex();
+ const match = r.exec('Call me at 555-123-4567 please');
+ expect(match).not.toBeNull();
+ });
+
+ it('matches numbers without separators', () => {
+ expect('5551234567').toMatch(regex());
+ });
+});
+
+describe('SSN regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.ssn;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches SSN with dashes', () => {
+ expect('123-45-6789').toMatch(regex());
+ });
+
+ it('matches SSN without dashes', () => {
+ expect('123456789').toMatch(regex());
+ });
+
+ it('matches SSN embedded in text', () => {
+ const r = regex();
+ const match = r.exec('SSN: 123-45-6789 on file');
+ expect(match).not.toBeNull();
+ expect(match![0]).toBe('123-45-6789');
+ });
+
+ it('does not match numbers with too few digits', () => {
+ expect('12-34-567').not.toMatch(regex());
+ });
+
+ it('does not match numbers with too many digits', () => {
+ const r = regex();
+ const text = '1234567890';
+ const match = r.exec(text);
+ if (match) {
+ expect(match[0]).not.toBe(text);
+ }
+ });
+
+ it('matches at line boundaries', () => {
+ const r = regex();
+ const match = r.exec('123-45-6789');
+ expect(match).not.toBeNull();
+ expect(match!.index).toBe(0);
+ });
+});
+
+describe('credit card regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.creditCard;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches 16-digit card number without separators', () => {
+ expect('4111111111111111').toMatch(regex());
+ });
+
+ it('matches card number with spaces', () => {
+ expect('4111 1111 1111 1111').toMatch(regex());
+ });
+
+ it('matches card number with dashes', () => {
+ expect('4111-1111-1111-1111').toMatch(regex());
+ });
+
+ it('matches 13-digit card numbers (old Visa)', () => {
+ expect('4222222222222').toMatch(regex());
+ });
+
+ it('matches 15-digit card numbers (Amex)', () => {
+ expect('378282246310005').toMatch(regex());
+ });
+
+ it('matches card number embedded in text', () => {
+ const r = regex();
+ const match = r.exec('Card: 4111111111111111 on file');
+ expect(match).not.toBeNull();
+ });
+});
+
+describe('IP address regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.ipAddress;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches valid IPv4 addresses', () => {
+ expect('192.168.1.1').toMatch(regex());
+ expect('10.0.0.1').toMatch(regex());
+ expect('255.255.255.255').toMatch(regex());
+ expect('0.0.0.0').toMatch(regex());
+ });
+
+ it('matches loopback address', () => {
+ expect('127.0.0.1').toMatch(regex());
+ });
+
+ it('does not match octets above 255', () => {
+ expect('256.1.1.1').not.toMatch(regex());
+ expect('1.1.1.256').not.toMatch(regex());
+ });
+
+ it('does not match incomplete IP addresses', () => {
+ expect('192.168.1').not.toMatch(regex());
+ });
+
+ it('matches IP embedded in text', () => {
+ const r = regex();
+ const match = r.exec('Server at 10.0.0.42 is down');
+ expect(match).not.toBeNull();
+ expect(match![0]).toBe('10.0.0.42');
+ });
+
+ it('does not match version numbers like 1.2.3', () => {
+ expect('1.2.3').not.toMatch(regex());
+ });
+
+ it('matches addresses with single-digit octets', () => {
+ expect('1.2.3.4').toMatch(regex());
+ });
+
+ it('matches addresses with leading zeros in octets', () => {
+ expect('01.02.03.04').toMatch(regex());
+ });
+});
+
+describe('MAC address regex', () => {
+ const regex = () => {
+ const r = PRESET_REGEXES.macAddress;
+ r.lastIndex = 0;
+ return r;
+ };
+
+ it('matches colon-separated MAC address', () => {
+ expect('00:1A:2B:3C:4D:5E').toMatch(regex());
+ });
+
+ it('matches dash-separated MAC address', () => {
+ expect('00-1A-2B-3C-4D-5E').toMatch(regex());
+ });
+
+ it('is case insensitive', () => {
+ expect('aa:bb:cc:dd:ee:ff').toMatch(regex());
+ expect('AA:BB:CC:DD:EE:FF').toMatch(regex());
+ });
+
+ it('does not match incomplete MAC addresses', () => {
+ expect('00:1A:2B:3C:4D').not.toMatch(regex());
+ });
+
+ it('matches MAC embedded in text', () => {
+ const r = regex();
+ const match = r.exec('Device MAC: AA:BB:CC:DD:EE:FF found');
+ expect(match).not.toBeNull();
+ expect(match![0]).toBe('AA:BB:CC:DD:EE:FF');
+ });
+
+ it('does not match if segments have wrong length', () => {
+ expect('0:1A:2B:3C:4D:5E').not.toMatch(regex());
+ });
+});
+
+describe('findMatches', () => {
+ it('returns empty array for empty input', () => {
+ expect(findMatches('', [PRESET_REGEXES.email])).toEqual([]);
+ });
+
+ it('returns empty array when no patterns match', () => {
+ expect(findMatches('no sensitive data here', [PRESET_REGEXES.email])).toEqual([]);
+ });
+
+ it('returns empty array when patterns list is empty', () => {
+ expect(findMatches('[email protected]', [])).toEqual([]);
+ });
+
+ it('returns correct indices for a single match', () => {
+ const text = 'Email: [email protected] here';
+ const results = findMatches(text, [PRESET_REGEXES.email]);
+ expect(results).toHaveLength(1);
+ expect(results[0].start).toBe(7);
+ expect(results[0].end).toBe(23);
+ expect(text.slice(results[0].start, results[0].end)).toBe('[email protected]');
+ });
+
+ it('returns multiple non-overlapping matches', () => {
+ const text = 'Email [email protected] and [email protected] please';
+ const results = findMatches(text, [PRESET_REGEXES.email]);
+ expect(results).toHaveLength(2);
+ expect(text.slice(results[0].start, results[0].end)).toBe('[email protected]');
+ expect(text.slice(results[1].start, results[1].end)).toBe('[email protected]');
+ });
+
+ it('merges overlapping ranges from different patterns', () => {
+ const text = '123-45-6789';
+ const results = findMatches(text, [PRESET_REGEXES.ssn, PRESET_REGEXES.phone]);
+ for (let i = 1; i < results.length; i++) {
+ expect(results[i].start).toBeGreaterThanOrEqual(results[i - 1].end);
+ }
+ });
+
+ it('merges adjacent ranges', () => {
+ const fakePattern1 = /abc/g;
+ const fakePattern2 = /bcd/g;
+ const text = 'abcd';
+ const results = findMatches(text, [fakePattern1, fakePattern2]);
+ expect(results).toHaveLength(1);
+ expect(results[0]).toEqual({ start: 0, end: 4 });
+ });
+
+ it('handles multiple pattern types simultaneously', () => {
+ const text = 'Email: [email protected] Phone: 555-123-4567 IP: 192.168.1.1';
+ const results = findMatches(text, [PRESET_REGEXES.email, PRESET_REGEXES.phone, PRESET_REGEXES.ipAddress]);
+ expect(results.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it('returns ranges sorted by start position', () => {
+ const text = 'IP: 10.0.0.1 Email: [email protected] SSN: 123-45-6789';
+ const results = findMatches(text, [PRESET_REGEXES.ssn, PRESET_REGEXES.email, PRESET_REGEXES.ipAddress]);
+ for (let i = 1; i < results.length; i++) {
+ expect(results[i].start).toBeGreaterThanOrEqual(results[i - 1].start);
+ }
+ });
+
+ it('handles text with only whitespace', () => {
+ expect(findMatches(' \n\t ', [PRESET_REGEXES.email])).toEqual([]);
+ });
+
+ it('resets lastIndex between calls', () => {
+ const text = '[email protected]';
+ findMatches(text, [PRESET_REGEXES.email]);
+ const second = findMatches(text, [PRESET_REGEXES.email]);
+ expect(second).toHaveLength(1);
+ });
+
+ it('does not produce overlapping ranges in output', () => {
+ const text = 'Contact: 123-45-6789 or 123-456-7890';
+ const results = findMatches(text, [PRESET_REGEXES.ssn, PRESET_REGEXES.phone]);
+ for (let i = 1; i < results.length; i++) {
+ expect(results[i].start).toBeGreaterThanOrEqual(results[i - 1].end);
+ }
+ });
+
+ it('handles match at the very start of the string', () => {
+ const text = '[email protected] is an email';
+ const results = findMatches(text, [PRESET_REGEXES.email]);
+ expect(results[0].start).toBe(0);
+ });
+
+ it('handles match at the very end of the string', () => {
+ const text = 'Send to [email protected]';
+ const results = findMatches(text, [PRESET_REGEXES.email]);
+ expect(results[results.length - 1].end).toBe(text.length);
+ });
+});
+
+describe('PRESET_REGEXES', () => {
+ it('has an entry for every PresetKey', () => {
+ const keys: PresetKey[] = ['email', 'phone', 'ssn', 'creditCard', 'ipAddress', 'macAddress'];
+ for (const key of keys) {
+ expect(PRESET_REGEXES[key]).toBeInstanceOf(RegExp);
+ }
+ });
+
+ it('all patterns have the global flag', () => {
+ for (const pattern of Object.values(PRESET_REGEXES)) {
+ expect(pattern.flags).toContain('g');
+ }
+ });
+});
diff --git a/src/core/capture/__tests__/machine.test.ts b/src/core/capture/__tests__/machine.test.ts
new file mode 100644
index 0000000..f1bd5d4
--- /dev/null
+++ b/src/core/capture/__tests__/machine.test.ts
@@ -0,0 +1,118 @@
+import { createActor } from 'xstate';
+import { CaptureState, captureMachine } from '../machine';
+
+function startActor() {
+ const actor = createActor(captureMachine);
+ actor.start();
+ return actor;
+}
+
+describe('captureMachine', () => {
+ it('starts in IDLE state', () => {
+ const actor = startActor();
+ expect(actor.getSnapshot().value).toBe(CaptureState.IDLE);
+ });
+
+ it('transitions IDLE β†’ RECORDING on START_RECORDING', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });
+
+ const snap = actor.getSnapshot();
+ expect(snap.value).toBe(CaptureState.RECORDING);
+ expect(snap.context.currentGuideId).toBeTypeOf('string');
+ expect(snap.context.currentGuideId).toHaveLength(36);
+ expect(snap.context.currentUrl).toBe('https://example.com');
+ expect(snap.context.stepCount).toBe(0);
+ });
+
+ it('transitions RECORDING β†’ IDLE on STOP_RECORDING and resets context', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });
+ actor.send({ type: 'USER_ACTION' });
+ actor.send({ type: 'STOP_RECORDING' });
+
+ const snap = actor.getSnapshot();
+ expect(snap.value).toBe(CaptureState.IDLE);
+ expect(snap.context.currentGuideId).toBeNull();
+ expect(snap.context.stepCount).toBe(0);
+ expect(snap.context.currentUrl).toBe('');
+ });
+
+ it('increments stepCount on USER_ACTION while RECORDING', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });
+
+ actor.send({ type: 'USER_ACTION' });
+ expect(actor.getSnapshot().context.stepCount).toBe(1);
+
+ actor.send({ type: 'USER_ACTION' });
+ expect(actor.getSnapshot().context.stepCount).toBe(2);
+
+ actor.send({ type: 'USER_ACTION' });
+ expect(actor.getSnapshot().context.stepCount).toBe(3);
+ });
+
+ it('stays IDLE when STOP_RECORDING is sent in IDLE state', () => {
+ const actor = startActor();
+ actor.send({ type: 'STOP_RECORDING' });
+
+ const snap = actor.getSnapshot();
+ expect(snap.value).toBe(CaptureState.IDLE);
+ expect(snap.context.currentGuideId).toBeNull();
+ });
+
+ it('stays RECORDING when START_RECORDING is sent while already RECORDING', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://first.com' });
+ const guideId = actor.getSnapshot().context.currentGuideId;
+
+ actor.send({ type: 'START_RECORDING', url: 'https://second.com' });
+
+ const snap = actor.getSnapshot();
+ expect(snap.value).toBe(CaptureState.RECORDING);
+ expect(snap.context.currentGuideId).toBe(guideId);
+ expect(snap.context.currentUrl).toBe('https://first.com');
+ });
+
+ it('sets currentUrl on START_RECORDING', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://app.dev/dashboard' });
+ expect(actor.getSnapshot().context.currentUrl).toBe('https://app.dev/dashboard');
+ });
+
+ it('defaults currentUrl to empty string when url is omitted', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING' });
+ expect(actor.getSnapshot().context.currentUrl).toBe('');
+ });
+
+ it('updates currentUrl on URL_CHANGED while RECORDING', () => {
+ const actor = startActor();
+ actor.send({ type: 'START_RECORDING', url: 'https://example.com/page1' });
+
+ actor.send({ type: 'URL_CHANGED', url: 'https://example.com/page2' });
+ expect(actor.getSnapshot().context.currentUrl).toBe('https://example.com/page2');
+
+ actor.send({ type: 'URL_CHANGED', url: 'https://example.com/page3' });
+ expect(actor.getSnapshot().context.currentUrl).toBe('https://example.com/page3');
+ });
+
+ it('ignores URL_CHANGED in IDLE state', () => {
+ const actor = startActor();
+ actor.send({ type: 'URL_CHANGED', url: 'https://example.com' });
+ expect(actor.getSnapshot().context.currentUrl).toBe('');
+ });
+
+ it('generates a unique guideId for each recording session', () => {
+ const actor = startActor();
+
+ actor.send({ type: 'START_RECORDING' });
+ const firstId = actor.getSnapshot().context.currentGuideId;
+
+ actor.send({ type: 'STOP_RECORDING' });
+ actor.send({ type: 'START_RECORDING' });
+ const secondId = actor.getSnapshot().context.currentGuideId;
+
+ expect(firstId).not.toBe(secondId);
+ });
+});
diff --git a/src/core/export/__tests__/markdown-export.test.ts b/src/core/export/__tests__/markdown-export.test.ts
new file mode 100644
index 0000000..3a43119
--- /dev/null
+++ b/src/core/export/__tests__/markdown-export.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import { exportGuideAsMarkdown } from '@/core/export/markdown-export';
+import type { Guide, Screenshot, Step } from '@/core/guides/types';
+
+function makeGuide(overrides: Partial<Guide> = {}): Guide {
+ return {
+ id: 'guide-1',
+ title: 'Test Guide',
+ createdAt: new Date('2025-06-01T00:00:00Z').getTime(),
+ updatedAt: new Date('2025-06-01T00:00:00Z').getTime(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ ...overrides,
+ };
+}
+
+function makeStep(overrides: Partial<Step> = {}): Step {
+ return {
+ id: 'step-1',
+ guideId: 'guide-1',
+ index: 0,
+ description: 'Click the button',
+ action: 'click',
+ url: 'https://example.com',
+ timestamp: Date.now(),
+ ...overrides,
+ };
+}
+
+function makeScreenshot(stepId: string, content = 'img'): Screenshot {
+ return {
+ id: `ss-${stepId}`,
+ stepId,
+ blob: new Blob([content], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 800,
+ height: 600,
+ };
+}
+
+describe('exportGuideAsMarkdown', () => {
+ it('creates valid markdown with H1 title', async () => {
+ const guide = makeGuide({ title: 'My Guide' });
+ const steps = [makeStep()];
+ const screenshots = new Map<string, Screenshot>();
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toMatch(/^# My Guide\n/);
+ });
+
+ it('includes metadata line with step count and created date', async () => {
+ const guide = makeGuide();
+ const steps = [makeStep(), makeStep({ id: 'step-2', index: 1, description: 'Type text' })];
+ const screenshots = new Map<string, Screenshot>();
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toContain('export.stepsCount[2]');
+ expect(md).toContain('export.createdLabel[');
+ });
+
+ it('includes step descriptions with padded step numbers', async () => {
+ const guide = makeGuide();
+ const steps = [
+ makeStep({ index: 0, description: 'First action' }),
+ makeStep({ id: 'step-2', index: 1, description: 'Second action' }),
+ ];
+ const screenshots = new Map<string, Screenshot>();
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toContain('## export.stepLabel[01]: First action');
+ expect(md).toContain('## export.stepLabel[02]: Second action');
+ });
+
+ it('includes source domain when steps have URLs', async () => {
+ const guide = makeGuide();
+ const steps = [makeStep({ url: 'https://www.example.com/page' })];
+ const screenshots = new Map<string, Screenshot>();
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toContain('export.sourceLabel[example.com]');
+ });
+
+ it('handles guide with no steps', async () => {
+ const guide = makeGuide();
+ const md = await exportGuideAsMarkdown(guide, [], new Map());
+
+ expect(md).toContain('# Test Guide');
+ expect(md).toContain('export.stepsCount[0]');
+ expect(md).not.toContain('## export.stepLabel');
+ });
+
+ it('handles steps without screenshots', async () => {
+ const guide = makeGuide();
+ const steps = [makeStep()];
+ const screenshots = new Map<string, Screenshot>();
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toContain('## export.stepLabel[01]: Click the button');
+ expect(md).not.toContain('![');
+ });
+
+ it('embeds screenshot as base64 data URL in markdown image', async () => {
+ const guide = makeGuide();
+ const step = makeStep();
+ const steps = [step];
+ const ss = makeScreenshot(step.id, 'pixel-data');
+ const screenshots = new Map<string, Screenshot>([[step.id, ss]]);
+
+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);
+ expect(md).toContain('![export.stepLabel[01]](data:image/png;base64,');
+ const b64 = btoa('pixel-data');
+ expect(md).toContain(b64);
+ });
+});
diff --git a/src/core/export/__tests__/utils.test.ts b/src/core/export/__tests__/utils.test.ts
new file mode 100644
index 0000000..a3197a9
--- /dev/null
+++ b/src/core/export/__tests__/utils.test.ts
@@ -0,0 +1,120 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import { blobToBase64, blobToDataUrl, escapeHtml, extractDomain, formatDate } from '@/core/export/utils';
+import type { Step } from '@/core/guides/types';
+
+function makeStep(overrides: Partial<Step> = {}): Step {
+ return {
+ id: 'step-1',
+ guideId: 'guide-1',
+ index: 0,
+ description: 'Click button',
+ action: 'click',
+ url: '',
+ timestamp: Date.now(),
+ ...overrides,
+ };
+}
+
+describe('escapeHtml', () => {
+ it('escapes ampersand', () => {
+ expect(escapeHtml('foo & bar')).toBe('foo &amp; bar');
+ });
+
+ it('escapes less-than', () => {
+ expect(escapeHtml('a < b')).toBe('a &lt; b');
+ });
+
+ it('escapes greater-than', () => {
+ expect(escapeHtml('a > b')).toBe('a &gt; b');
+ });
+
+ it('escapes double quotes', () => {
+ expect(escapeHtml('say "hello"')).toBe('say &quot;hello&quot;');
+ });
+
+ it('escapes multiple special characters in one string', () => {
+ expect(escapeHtml('<div class="x">&</div>')).toBe('&lt;div class=&quot;x&quot;&gt;&amp;&lt;/div&gt;');
+ });
+
+ it('returns empty string unchanged', () => {
+ expect(escapeHtml('')).toBe('');
+ });
+
+ it('passes through strings with no special characters', () => {
+ expect(escapeHtml('hello world 123')).toBe('hello world 123');
+ });
+
+ it('neutralizes script injection', () => {
+ expect(escapeHtml('<script>alert(1)</script>')).toBe('&lt;script&gt;alert(1)&lt;/script&gt;');
+ });
+
+ it('neutralizes attribute injection via double quotes', () => {
+ expect(escapeHtml('" onmouseover="alert(1)"')).toBe('&quot; onmouseover=&quot;alert(1)&quot;');
+ });
+
+ it('neutralizes img onerror payload', () => {
+ expect(escapeHtml('<img src=x onerror="alert(1)">')).toBe('&lt;img src=x onerror=&quot;alert(1)&quot;&gt;');
+ });
+
+ it('neutralizes nested script tags', () => {
+ expect(escapeHtml('<<script>>alert(1)<</script>>')).toBe('&lt;&lt;script&gt;&gt;alert(1)&lt;&lt;/script&gt;&gt;');
+ });
+});
+
+describe('extractDomain', () => {
+ it('returns the domain from the first step with a URL', () => {
+ const steps = [
+ makeStep({ url: 'https://www.example.com/page' }),
+ makeStep({ id: 'step-2', url: 'https://other.com' }),
+ ];
+ expect(extractDomain(steps)).toBe('example.com');
+ });
+
+ it('strips www prefix', () => {
+ const steps = [makeStep({ url: 'https://www.github.com/mimik' })];
+ expect(extractDomain(steps)).toBe('github.com');
+ });
+
+ it('returns null for empty array', () => {
+ expect(extractDomain([])).toBeNull();
+ });
+
+ it('returns null when no steps have URLs', () => {
+ const steps = [makeStep({ url: '' }), makeStep({ id: 'step-2', url: '' })];
+ expect(extractDomain(steps)).toBeNull();
+ });
+
+ it('skips steps without URLs and finds the first with one', () => {
+ const steps = [makeStep({ url: '' }), makeStep({ id: 'step-2', url: 'https://docs.example.org/path' })];
+ expect(extractDomain(steps)).toBe('docs.example.org');
+ });
+});
+
+describe('formatDate', () => {
+ it('returns a formatted date string', () => {
+ const ts = new Date('2025-03-15T12:00:00Z').getTime();
+ const result = formatDate(ts);
+ expect(result).toContain('2025');
+ expect(result).toContain('15');
+ });
+});
+
+describe('blobToBase64', () => {
+ it('resolves with base64 content from a blob', async () => {
+ const blob = new Blob(['test'], { type: 'text/plain' });
+ const result = await blobToBase64(blob);
+ const decoded = atob(result);
+ expect(decoded).toBe('test');
+ });
+});
+
+describe('blobToDataUrl', () => {
+ it('resolves with a data URL from a blob', async () => {
+ const blob = new Blob(['hello'], { type: 'text/plain' });
+ const result = await blobToDataUrl(blob);
+ expect(result).toMatch(/^data:text\/plain;base64,/);
+ const b64Part = result.split(',')[1];
+ expect(atob(b64Part)).toBe('hello');
+ });
+});
diff --git a/src/core/guideme/__tests__/finder.test.ts b/src/core/guideme/__tests__/finder.test.ts
new file mode 100644
index 0000000..4c891c4
--- /dev/null
+++ b/src/core/guideme/__tests__/finder.test.ts
@@ -0,0 +1,580 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import type { ElementMeta } from '@/core/guides/types';
+import { compareText, findElement, isVisible, scoreCandidate, THRESHOLD, WEIGHTS } from '../finder';
+
+function makeMeta(overrides: Partial<ElementMeta> = {}): ElementMeta {
+ return {
+ tag: 'button',
+ cssSelector: 'button.submit',
+ textContent: null,
+ ariaLabel: null,
+ placeholder: null,
+ altText: null,
+ name: null,
+ role: null,
+ href: null,
+ inputType: null,
+ dataTestId: null,
+ rect: { x: 0, y: 0, width: 100, height: 40 },
+ devicePixelRatio: 1,
+ ...overrides,
+ };
+}
+
+function makeVisible(el: HTMLElement): HTMLElement {
+ Object.defineProperty(el, 'getBoundingClientRect', {
+ value: () => ({ x: 0, y: 0, width: 100, height: 40, top: 0, left: 0, right: 100, bottom: 40 }),
+ });
+ return el;
+}
+
+function makeHidden(el: HTMLElement): HTMLElement {
+ Object.defineProperty(el, 'getBoundingClientRect', {
+ value: () => ({ x: 0, y: 0, width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0 }),
+ });
+ return el;
+}
+
+describe('WEIGHTS', () => {
+ it('has textContent as the highest weight', () => {
+ const sorted = Object.entries(WEIGHTS).sort(([, a], [, b]) => b - a);
+ expect(sorted[0][0]).toBe('textContent');
+ });
+
+ it('ranks cssSelector second', () => {
+ const sorted = Object.entries(WEIGHTS).sort(([, a], [, b]) => b - a);
+ expect(sorted[1][0]).toBe('cssSelector');
+ });
+
+ it('ranks ariaLabel third', () => {
+ const sorted = Object.entries(WEIGHTS).sort(([, a], [, b]) => b - a);
+ expect(sorted[2][0]).toBe('ariaLabel');
+ });
+
+ it('has correct weight values', () => {
+ expect(WEIGHTS.textContent).toBe(0.3);
+ expect(WEIGHTS.cssSelector).toBe(0.2);
+ expect(WEIGHTS.ariaLabel).toBe(0.15);
+ expect(WEIGHTS.dataTestId).toBe(0.1);
+ expect(WEIGHTS.name).toBe(0.08);
+ expect(WEIGHTS.placeholder).toBe(0.07);
+ expect(WEIGHTS.role).toBe(0.05);
+ expect(WEIGHTS.href).toBe(0.05);
+ });
+});
+
+describe('THRESHOLD', () => {
+ it('is 0.5', () => {
+ expect(THRESHOLD).toBe(0.5);
+ });
+});
+
+describe('compareText', () => {
+ it('returns 1.0 for exact match', () => {
+ expect(compareText('Submit', 'Submit')).toBe(1.0);
+ });
+
+ it('returns 0.8 for normalized match (case difference)', () => {
+ expect(compareText('Submit', 'submit')).toBe(0.8);
+ });
+
+ it('returns 0.8 for normalized match (extra whitespace)', () => {
+ expect(compareText(' Submit Form ', 'submit form')).toBe(0.8);
+ });
+
+ it('returns 0.6 when stored starts with candidate (prefix match)', () => {
+ expect(compareText('Submit Form Now', 'submit form')).toBe(0.6);
+ });
+
+ it('returns 0.6 when candidate starts with stored (prefix match)', () => {
+ expect(compareText('submit', 'submit form now')).toBe(0.6);
+ });
+
+ it('returns 0 for completely different strings', () => {
+ expect(compareText('Submit', 'Cancel')).toBe(0);
+ });
+
+ it('returns 0 for partial but non-prefix overlap', () => {
+ expect(compareText('Submit Form', 'The Form')).toBe(0);
+ });
+});
+
+describe('isVisible', () => {
+ it('returns true for elements with positive dimensions', () => {
+ const el = makeVisible(document.createElement('div'));
+ expect(isVisible(el)).toBe(true);
+ });
+
+ it('returns false for elements with zero width', () => {
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'getBoundingClientRect', {
+ value: () => ({ x: 0, y: 0, width: 0, height: 40, top: 0, left: 0, right: 0, bottom: 40 }),
+ });
+ expect(isVisible(el)).toBe(false);
+ });
+
+ it('returns false for elements with zero height', () => {
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'getBoundingClientRect', {
+ value: () => ({ x: 0, y: 0, width: 100, height: 0, top: 0, left: 0, right: 100, bottom: 0 }),
+ });
+ expect(isVisible(el)).toBe(false);
+ });
+});
+
+describe('scoreCandidate', () => {
+ it('still includes cssSelector as active signal even when all others are null', () => {
+ const meta = makeMeta({
+ textContent: null,
+ ariaLabel: null,
+ dataTestId: null,
+ name: null,
+ placeholder: null,
+ role: null,
+ href: null,
+ });
+
+ const el = document.createElement('button');
+ const { score, matchDetails } = scoreCandidate(meta, el);
+
+ expect(matchDetails).not.toHaveProperty('textContent');
+ expect(matchDetails).not.toHaveProperty('ariaLabel');
+ expect(matchDetails).toHaveProperty('cssSelector');
+ expect(score).toBe(0);
+ });
+
+ it('gives full score when cssSelector matches and is only active signal', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.className = 'submit';
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ cssSelector: 'button.submit',
+ textContent: null,
+ ariaLabel: null,
+ dataTestId: null,
+ name: null,
+ placeholder: null,
+ role: null,
+ href: null,
+ });
+
+ const { score, matchDetails } = scoreCandidate(meta, btn);
+
+ expect(matchDetails.cssSelector).toBe(1);
+ expect(score).toBe(1);
+
+ document.body.removeChild(btn);
+ });
+
+ it('scores textContent exact match with correct weight proportion', () => {
+ const btn = document.createElement('button');
+ btn.textContent = 'Save Changes';
+
+ const meta = makeMeta({
+ textContent: 'Save Changes',
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.textContent).toBe(1.0);
+ expect(matchDetails.cssSelector).toBe(0);
+ });
+
+ it('scores ariaLabel match', () => {
+ const btn = document.createElement('button');
+ btn.setAttribute('aria-label', 'Close dialog');
+
+ const meta = makeMeta({
+ ariaLabel: 'Close dialog',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.ariaLabel).toBe(1.0);
+ });
+
+ it('scores dataTestId from data-testid attribute', () => {
+ const btn = document.createElement('button');
+ btn.setAttribute('data-testid', 'submit-btn');
+
+ const meta = makeMeta({
+ dataTestId: 'submit-btn',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.dataTestId).toBe(1.0);
+ });
+
+ it('scores dataTestId from data-test-id attribute', () => {
+ const btn = document.createElement('button');
+ btn.setAttribute('data-test-id', 'submit-btn');
+
+ const meta = makeMeta({
+ dataTestId: 'submit-btn',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.dataTestId).toBe(1.0);
+ });
+
+ it('scores dataTestId from data-qa attribute', () => {
+ const btn = document.createElement('button');
+ btn.setAttribute('data-qa', 'submit-btn');
+
+ const meta = makeMeta({
+ dataTestId: 'submit-btn',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.dataTestId).toBe(1.0);
+ });
+
+ it('scores name attribute', () => {
+ const input = document.createElement('input');
+ input.setAttribute('name', 'email');
+
+ const meta = makeMeta({
+ tag: 'input',
+ name: 'email',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, input);
+ expect(matchDetails.name).toBe(1.0);
+ });
+
+ it('scores placeholder attribute', () => {
+ const input = document.createElement('input');
+ input.setAttribute('placeholder', 'Enter email');
+
+ const meta = makeMeta({
+ tag: 'input',
+ placeholder: 'Enter email',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, input);
+ expect(matchDetails.placeholder).toBe(1.0);
+ });
+
+ it('scores role attribute', () => {
+ const div = document.createElement('div');
+ div.setAttribute('role', 'button');
+
+ const meta = makeMeta({
+ tag: 'div',
+ role: 'button',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, div);
+ expect(matchDetails.role).toBe(1.0);
+ });
+
+ it('falls back to tagName for role when no role attribute', () => {
+ const btn = document.createElement('button');
+
+ const meta = makeMeta({
+ role: 'button',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.role).toBe(1.0);
+ });
+
+ it('scores href for anchor elements', () => {
+ const a = document.createElement('a');
+ a.href = 'https://example.com/page';
+
+ const meta = makeMeta({
+ tag: 'a',
+ href: 'https://example.com/page',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, a);
+ expect(matchDetails.href).toBeGreaterThan(0);
+ });
+
+ it('returns 0 for href on non-anchor elements', () => {
+ const btn = document.createElement('button');
+
+ const meta = makeMeta({
+ href: 'https://example.com',
+ textContent: null,
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.href).toBe(0);
+ });
+
+ it('normalizes weights to sum to 1', () => {
+ const btn = document.createElement('button');
+ btn.textContent = 'Submit';
+ btn.setAttribute('aria-label', 'Submit form');
+
+ const meta = makeMeta({
+ textContent: 'Submit',
+ ariaLabel: 'Submit form',
+ cssSelector: '#nonexistent',
+ });
+
+ const { score, matchDetails } = scoreCandidate(meta, btn);
+
+ const totalWeight = WEIGHTS.textContent + WEIGHTS.ariaLabel + WEIGHTS.cssSelector;
+ const expected =
+ (matchDetails.textContent * WEIGHTS.textContent +
+ matchDetails.ariaLabel * WEIGHTS.ariaLabel +
+ matchDetails.cssSelector * WEIGHTS.cssSelector) /
+ totalWeight;
+
+ expect(score).toBeCloseTo(expected, 10);
+ });
+
+ it('returns high score when all signals match exactly', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.className = 'all-match';
+ btn.textContent = 'Save';
+ btn.setAttribute('aria-label', 'Save document');
+ btn.setAttribute('data-testid', 'save-btn');
+ btn.setAttribute('name', 'save');
+ btn.setAttribute('placeholder', 'save');
+ btn.setAttribute('role', 'button');
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ cssSelector: 'button.all-match',
+ textContent: 'Save',
+ ariaLabel: 'Save document',
+ dataTestId: 'save-btn',
+ name: 'save',
+ placeholder: 'save',
+ role: 'button',
+ });
+
+ const { score } = scoreCandidate(meta, btn);
+ expect(score).toBe(1.0);
+
+ document.body.removeChild(btn);
+ });
+
+ it('gives partial score for normalized text matches', () => {
+ const btn = document.createElement('button');
+ btn.textContent = ' save changes ';
+
+ const meta = makeMeta({
+ textContent: 'Save Changes',
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.textContent).toBe(0.8);
+ });
+
+ it('gives partial score for prefix text matches', () => {
+ const btn = document.createElement('button');
+ btn.textContent = 'Save';
+
+ const meta = makeMeta({
+ textContent: 'Save Changes Now',
+ cssSelector: '#nonexistent',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.textContent).toBe(0.6);
+ });
+
+ it('handles invalid cssSelector gracefully', () => {
+ const btn = document.createElement('button');
+ const meta = makeMeta({
+ cssSelector: '[[[invalid',
+ textContent: 'Click me',
+ });
+
+ const { matchDetails } = scoreCandidate(meta, btn);
+ expect(matchDetails.cssSelector).toBe(0);
+ });
+});
+
+describe('findElement', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('returns the best matching element above threshold', () => {
+ const target = makeVisible(document.createElement('button'));
+ target.textContent = 'Submit Form';
+ target.setAttribute('data-testid', 'submit');
+ document.body.appendChild(target);
+
+ const decoy = makeVisible(document.createElement('button'));
+ decoy.textContent = 'Cancel';
+ document.body.appendChild(decoy);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Submit Form',
+ dataTestId: 'submit',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBe(target);
+ expect(result.score).toBeGreaterThanOrEqual(THRESHOLD);
+ });
+
+ it('returns null when no element exceeds threshold', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.textContent = 'Completely Different';
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Submit Form',
+ ariaLabel: 'Submit the form',
+ dataTestId: 'submit-btn',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBeNull();
+ expect(result.score).toBeLessThan(THRESHOLD);
+ });
+
+ it('returns null when no candidates exist for the tag', () => {
+ const meta = makeMeta({ tag: 'button' });
+ const result = findElement(meta);
+ expect(result.element).toBeNull();
+ });
+
+ it('skips hidden elements', () => {
+ const hidden = makeHidden(document.createElement('button'));
+ hidden.textContent = 'Submit';
+ hidden.setAttribute('data-testid', 'submit');
+ document.body.appendChild(hidden);
+
+ const visible = makeVisible(document.createElement('button'));
+ visible.textContent = 'Submit';
+ visible.setAttribute('data-testid', 'submit');
+ document.body.appendChild(visible);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Submit',
+ dataTestId: 'submit',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBe(visible);
+ });
+
+ it('returns null when all matching elements are hidden', () => {
+ const hidden = makeHidden(document.createElement('button'));
+ hidden.textContent = 'Submit';
+ hidden.setAttribute('data-testid', 'submit');
+ document.body.appendChild(hidden);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Submit',
+ dataTestId: 'submit',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBeNull();
+ });
+
+ it('picks the highest scoring element among multiple visible candidates', () => {
+ const weak = makeVisible(document.createElement('button'));
+ weak.textContent = 'Sub';
+ document.body.appendChild(weak);
+
+ const strong = makeVisible(document.createElement('button'));
+ strong.textContent = 'Submit';
+ strong.setAttribute('aria-label', 'Submit form');
+ strong.setAttribute('data-testid', 'submit-btn');
+ document.body.appendChild(strong);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Submit',
+ ariaLabel: 'Submit form',
+ dataTestId: 'submit-btn',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBe(strong);
+ });
+
+ it('includes matchDetails in the result', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.textContent = 'OK';
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'OK',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.matchDetails).toBeDefined();
+ expect(typeof result.matchDetails.textContent).toBe('number');
+ expect(typeof result.matchDetails.cssSelector).toBe('number');
+ });
+
+ it('returns score below threshold in result when no match', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.textContent = 'Nope';
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ tag: 'button',
+ textContent: 'Totally different text here',
+ ariaLabel: 'Something else entirely',
+ dataTestId: 'other-btn',
+ cssSelector: '#nonexistent',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBeNull();
+ expect(result.score).toBe(0);
+ expect(result.matchDetails).toBeDefined();
+ });
+
+ it('uses cssSelector match via querySelector', () => {
+ const btn = makeVisible(document.createElement('button'));
+ btn.id = 'unique-submit';
+ btn.textContent = 'Go';
+ document.body.appendChild(btn);
+
+ const meta = makeMeta({
+ tag: 'button',
+ cssSelector: '#unique-submit',
+ textContent: 'Go',
+ });
+
+ const result = findElement(meta);
+ expect(result.element).toBe(btn);
+ expect(result.matchDetails.cssSelector).toBe(1);
+ });
+});
diff --git a/src/core/guideme/finder.ts b/src/core/guideme/finder.ts
index aff5604..c9c04ca 100644
--- a/src/core/guideme/finder.ts
+++ b/src/core/guideme/finder.ts
@@ -134,4 +134,4 @@ function findElement(meta: ElementMeta): FindResult {
}
export type { FindResult };
-export { findElement, THRESHOLD };
+export { compareText, findElement, isVisible, scoreCandidate, THRESHOLD, WEIGHTS };
diff --git a/src/core/guides/__tests__/service.test.ts b/src/core/guides/__tests__/service.test.ts
new file mode 100644
index 0000000..aba50ac
--- /dev/null
+++ b/src/core/guides/__tests__/service.test.ts
@@ -0,0 +1,287 @@
+import 'fake-indexeddb/auto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { broadcastMessages } = vi.hoisted(() => {
+ const broadcastMessages: Array<unknown> = [];
+
+ globalThis.BroadcastChannel = class BroadcastChannel {
+ name: string;
+ constructor(name: string) {
+ this.name = name;
+ }
+ postMessage(data: unknown) {
+ broadcastMessages.push(data);
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+ onmessage = null;
+ onmessageerror = null;
+ dispatchEvent() {
+ return true;
+ }
+ } as unknown as typeof BroadcastChannel;
+
+ return { broadcastMessages };
+});
+
+import { db } from '../db';
+import {
+ addStepToGuide,
+ createGuide,
+ deleteStep,
+ getGuide,
+ getGuides,
+ getStarredGuides,
+ getTrashedGuides,
+ permanentlyDeleteGuide,
+ reorderSteps,
+ softDeleteGuide,
+ toggleStar,
+} from '../service';
+import type { Guide, Screenshot, Step } from '../types';
+
+function makeStep(overrides: Partial<Step> & { id: string; guideId: string }): Step {
+ return {
+ index: 0,
+ description: 'Test step',
+ action: 'click',
+ url: 'https://example.com',
+ timestamp: Date.now(),
+ ...overrides,
+ };
+}
+
+function makeScreenshot(overrides: Partial<Screenshot> & { id: string; stepId: string }): Screenshot {
+ return {
+ blob: new Blob(['img'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 800,
+ height: 600,
+ ...overrides,
+ };
+}
+
+async function seedGuide(id: string, extras?: Partial<Guide>): Promise<Guide> {
+ const guide: Guide = {
+ id,
+ title: 'Test Guide',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ ...extras,
+ };
+ await db.guides.add(guide);
+ return guide;
+}
+
+beforeEach(async () => {
+ broadcastMessages.length = 0;
+});
+
+afterEach(async () => {
+ await db.guides.clear();
+ await db.steps.clear();
+ await db.screenshots.clear();
+});
+
+describe('createGuide', () => {
+ it('creates a guide with correct defaults', async () => {
+ const guide = await createGuide('g1');
+
+ expect(guide.id).toBe('g1');
+ expect(guide.title).toBe('fullview.untitledGuide');
+ expect(guide.stepIds).toEqual([]);
+ expect(guide.starred).toBe(false);
+ expect(guide.deletedAt).toBeNull();
+ expect(guide.createdAt).toBeTypeOf('number');
+ expect(guide.updatedAt).toBeTypeOf('number');
+
+ const stored = await db.guides.get('g1');
+ expect(stored).toEqual(guide);
+ });
+});
+
+describe('getGuide', () => {
+ it('returns guide with steps and screenshots', async () => {
+ await seedGuide('g1', { stepIds: ['s1', 's2'] });
+ const step1 = makeStep({ id: 's1', guideId: 'g1', index: 0, screenshotId: 'sc1' });
+ const step2 = makeStep({ id: 's2', guideId: 'g1', index: 1, screenshotId: 'sc2' });
+ await db.steps.bulkAdd([step1, step2]);
+ const sc1 = makeScreenshot({ id: 'sc1', stepId: 's1' });
+ const sc2 = makeScreenshot({ id: 'sc2', stepId: 's2' });
+ await db.screenshots.bulkAdd([sc1, sc2]);
+
+ const result = await getGuide('g1');
+
+ expect(result).not.toBeNull();
+ expect(result!.guide.id).toBe('g1');
+ expect(result!.steps).toHaveLength(2);
+ expect(result!.steps[0].id).toBe('s1');
+ expect(result!.steps[1].id).toBe('s2');
+ expect(result!.screenshots.size).toBe(2);
+ expect(result!.screenshots.get('s1')).toBeDefined();
+ expect(result!.screenshots.get('s2')).toBeDefined();
+ });
+
+ it('returns null for non-existent guide', async () => {
+ const result = await getGuide('nope');
+ expect(result).toBeNull();
+ });
+});
+
+describe('addStepToGuide', () => {
+ it('appends stepId and updates timestamp', async () => {
+ const guide = await seedGuide('g1');
+ const beforeUpdate = guide.updatedAt;
+
+ await addStepToGuide('g1', 's1');
+
+ const updated = await db.guides.get('g1');
+ expect(updated!.stepIds).toEqual(['s1']);
+ expect(updated!.updatedAt).toBeGreaterThanOrEqual(beforeUpdate);
+
+ await addStepToGuide('g1', 's2');
+ const updated2 = await db.guides.get('g1');
+ expect(updated2!.stepIds).toEqual(['s1', 's2']);
+ });
+});
+
+describe('deleteStep', () => {
+ it('removes step, re-indexes remaining, cleans up screenshot', async () => {
+ await seedGuide('g1', { stepIds: ['s1', 's2', 's3'] });
+ await db.steps.bulkAdd([
+ makeStep({ id: 's1', guideId: 'g1', index: 0, screenshotId: 'sc1' }),
+ makeStep({ id: 's2', guideId: 'g1', index: 1 }),
+ makeStep({ id: 's3', guideId: 'g1', index: 2 }),
+ ]);
+ await db.screenshots.add(makeScreenshot({ id: 'sc1', stepId: 's1' }));
+
+ await deleteStep('g1', 's1');
+
+ expect(await db.steps.get('s1')).toBeUndefined();
+ expect(await db.screenshots.get('sc1')).toBeUndefined();
+
+ const guide = await db.guides.get('g1');
+ expect(guide!.stepIds).toEqual(['s2', 's3']);
+
+ const remaining = await db.steps.where('guideId').equals('g1').sortBy('index');
+ expect(remaining[0].index).toBe(0);
+ expect(remaining[1].index).toBe(1);
+ });
+});
+
+describe('reorderSteps', () => {
+ it('reassigns indices correctly', async () => {
+ await seedGuide('g1', { stepIds: ['s1', 's2', 's3'] });
+ await db.steps.bulkAdd([
+ makeStep({ id: 's1', guideId: 'g1', index: 0 }),
+ makeStep({ id: 's2', guideId: 'g1', index: 1 }),
+ makeStep({ id: 's3', guideId: 'g1', index: 2 }),
+ ]);
+
+ await reorderSteps('g1', ['s3', 's1', 's2']);
+
+ const guide = await db.guides.get('g1');
+ expect(guide!.stepIds).toEqual(['s3', 's1', 's2']);
+
+ const steps = await db.steps.where('guideId').equals('g1').sortBy('index');
+ expect(steps.map((s) => s.id)).toEqual(['s3', 's1', 's2']);
+ expect(steps.map((s) => s.index)).toEqual([0, 1, 2]);
+ });
+});
+
+describe('toggleStar', () => {
+ it('toggles starred boolean and broadcasts change', async () => {
+ await seedGuide('g1');
+
+ const result1 = await toggleStar('g1');
+ expect(result1).toBe(true);
+ expect((await db.guides.get('g1'))!.starred).toBe(true);
+ expect(broadcastMessages).toContainEqual({ type: 'starred', id: 'g1', starred: true });
+
+ broadcastMessages.length = 0;
+ const result2 = await toggleStar('g1');
+ expect(result2).toBe(false);
+ expect((await db.guides.get('g1'))!.starred).toBe(false);
+ expect(broadcastMessages).toContainEqual({ type: 'starred', id: 'g1', starred: false });
+ });
+
+ it('returns false for non-existent guide', async () => {
+ const result = await toggleStar('nope');
+ expect(result).toBe(false);
+ });
+});
+
+describe('softDeleteGuide', () => {
+ it('sets deletedAt and broadcasts mutated', async () => {
+ await seedGuide('g1');
+
+ await softDeleteGuide('g1');
+
+ const guide = await db.guides.get('g1');
+ expect(guide!.deletedAt).toBeTypeOf('number');
+ expect(guide!.deletedAt).not.toBeNull();
+ expect(broadcastMessages).toContainEqual({ type: 'mutated' });
+ });
+});
+
+describe('permanentlyDeleteGuide', () => {
+ it('cascade deletes steps and screenshots', async () => {
+ await seedGuide('g1', { stepIds: ['s1', 's2'] });
+ await db.steps.bulkAdd([
+ makeStep({ id: 's1', guideId: 'g1', index: 0, screenshotId: 'sc1' }),
+ makeStep({ id: 's2', guideId: 'g1', index: 1, screenshotId: 'sc2' }),
+ ]);
+ await db.screenshots.bulkAdd([
+ makeScreenshot({ id: 'sc1', stepId: 's1' }),
+ makeScreenshot({ id: 'sc2', stepId: 's2' }),
+ ]);
+
+ await permanentlyDeleteGuide('g1');
+
+ expect(await db.guides.get('g1')).toBeUndefined();
+ expect(await db.steps.where('guideId').equals('g1').count()).toBe(0);
+ expect(await db.screenshots.get('sc1')).toBeUndefined();
+ expect(await db.screenshots.get('sc2')).toBeUndefined();
+ expect(broadcastMessages).toContainEqual({ type: 'mutated' });
+ });
+});
+
+describe('getGuides', () => {
+ it('excludes trashed guides and orders by updatedAt desc', async () => {
+ await seedGuide('g1', { updatedAt: 100 });
+ await seedGuide('g2', { updatedAt: 300 });
+ await seedGuide('g3', { updatedAt: 200, deletedAt: Date.now() });
+
+ const guides = await getGuides();
+
+ expect(guides.map((g) => g.id)).toEqual(['g2', 'g1']);
+ });
+});
+
+describe('getStarredGuides', () => {
+ it('only returns starred guides, excludes trashed', async () => {
+ await seedGuide('g1', { starred: true, updatedAt: 200 });
+ await seedGuide('g2', { starred: false, updatedAt: 300 });
+ await seedGuide('g3', { starred: true, updatedAt: 100, deletedAt: Date.now() });
+
+ const guides = await getStarredGuides();
+
+ expect(guides.map((g) => g.id)).toEqual(['g1']);
+ });
+});
+
+describe('getTrashedGuides', () => {
+ it('only returns trashed guides', async () => {
+ await seedGuide('g1', { deletedAt: null });
+ await seedGuide('g2', { deletedAt: Date.now(), updatedAt: 200 });
+ await seedGuide('g3', { deletedAt: Date.now(), updatedAt: 300 });
+
+ const guides = await getTrashedGuides();
+
+ expect(guides.map((g) => g.id)).toEqual(['g3', 'g2']);
+ });
+});