# Vitest Reporter → Plugin Migration

## Summary

Converted the Vitest reporter to a plugin architecture with much simpler dashcam URL tracking.

## Key Changes

### 1. Plugin Architecture ✅

**Before (Reporter):**

```javascript
class TestDriverReporter {
  constructor(options = {}) {
    this.options = options;
    this.testRun = null;
    // ... many instance properties
  }
}
```

**After (Plugin):**

```javascript
const pluginState = {
  testRun: null,
  testRunId: null,
  dashcamUrls: new Map(), // In-memory tracking!
  // ... all state in one place
};

export default function testDriverPlugin(options = {}) {
  return {
    name: "testdriver-plugin",
    // ... hooks
  };
}
```

### 2. Dashcam URL Tracking (MUCH SIMPLER) ✅

**Before:**

- ❌ Write JSON to temp files in `/tmp/`
- ❌ Read temp files on test completion
- ❌ Complex matching logic (sessionId, taskId, filename patterns)
- ❌ Manual cleanup of temp files
- ❌ Race conditions with parallel tests
- ❌ Multiple fallback mechanisms (globalThis, registry, meta)

**After:**

- ✅ Simple in-memory Map (testId → dashcamUrl)
- ✅ Direct API: `registerDashcamUrl(testId, url, platform)`
- ✅ No file system operations
- ✅ No complex matching
- ✅ No cleanup needed
- ✅ Thread-safe for parallel tests

### 3. Usage in Tests

**Before:**

```javascript
// Tests had to write to temp files
const tempFile = path.join(
  os.tmpdir(),
  `testdriver-dashcam-${sessionId}-${taskId}-${Date.now()}.json`,
);
fs.writeFileSync(
  tempFile,
  JSON.stringify({
    dashcamUrl,
    replayObjectId,
    platform: client.os,
    timestamp: Date.now(),
    pid: process.pid,
    sessionId,
  }),
);

// AND set global variables
globalThis.__testdriverMeta.__lastDashcamUrl__ = dashcamUrl;

// AND register in registry
globalThis.__testdriverRegistry.setClient(taskId, client);

// AND store in task.meta
task.meta.testdriverDashcamUrl = dashcamUrl;
```

**After:**

```javascript
// Just one simple call
globalThis.__testdriverPlugin.registerDashcamUrl(taskId, dashcamUrl, client.os);
```

### 4. Configuration

**Before:**

```javascript
export default defineConfig({
  test: {
    reporters: [
      "default",
      [
        "./interfaces/vitest-reporter.js",
        {
          apiKey: process.env.TD_API_KEY,
          apiRoot: process.env.TD_API_ROOT,
        },
      ],
    ],
  },
});
```

**After:**

```javascript
export default defineConfig({
  plugins: [
    testDriverPlugin({
      apiKey: process.env.TD_API_KEY,
      apiRoot: process.env.TD_API_ROOT,
    }),
  ],
});
```

## Files Modified

### Plugin

- ✅ **Created**: `interfaces/vitest-plugin.mjs` (new plugin)
- ✅ **Deleted**: `interfaces/vitest-reporter.js` (old reporter)
- ✅ **Updated**: `vitest.config.mjs` (uses plugin)
- ✅ **Updated**: `vitest.config.example.js` (uses plugin)

### Test Helpers

- ✅ **Removed**: `examples/setup/` folder (legacy helpers)
  - Code moved to `lib/vitest/hooks.mjs` framework
  - Tests now use `TestDriver(context, options)` pattern directly

### Documentation

- ✅ **Updated**: `docs/QUICK_START_TEST_RECORDING.md`
- ✅ **Updated**: `docs/TEST_RECORDING.md`
- ✅ **Updated**: `docs/ARCHITECTURE.md`

## Code Removed

### From Plugin (vs old reporter)

- ❌ ~200 lines of file system operations
- ❌ `indexDashcamFiles()` - complex temp file reading
- ❌ `findReplayForTest()` - complex sessionId matching
- ❌ `findReplayForTestInline()` - complex fallback logic
- ❌ Imports: `fs`, `os` (no longer needed!)

### From Test Helpers

- ❌ ~60 lines of temp file writing
- ❌ Global registry setup
- ❌ Global meta initialization
- ❌ Multiple storage mechanisms

## Benefits

1. **Simpler**: ~300 fewer lines of complex code
2. **Faster**: No file I/O overhead
3. **More Reliable**: No file system race conditions
4. **Better DX**: Single API call to register dashcam URLs
5. **Easier to Debug**: All state in one place
6. **Thread-Safe**: Map-based storage handles parallel tests
7. **Cleaner**: No temp file cleanup needed

## Testing

```bash
# Verify plugin loads
node -e "import('./interfaces/vitest-plugin.mjs').then(m => console.log('Exports:', Object.keys(m)))"

# Run tests
TD_API_KEY=xxx vitest run
```

## Migration for Users

If you're using the TestDriver SDK in your tests:

**Old way (still works but deprecated):**

```javascript
// Multiple places to set dashcam URL
globalThis.__testdriverMeta.__lastDashcamUrl__ = dashcamUrl;
```

**New way:**

```javascript
// Single plugin API
if (globalThis.__testdriverPlugin) {
  globalThis.__testdriverPlugin.registerDashcamUrl(
    testId,
    dashcamUrl,
    platform,
  );
}
```

## Notes

- The plugin automatically makes itself available globally as `globalThis.__testdriverPlugin`
- Test helpers now use this API automatically
- No breaking changes for end users - just better internals!
