# StackScope SDK Troubleshooting Guide

## 🚨 Common Issues & Solutions

This guide addresses the most frequently encountered issues when integrating StackScope SDK.

## 🔍 Quick Diagnostics

**First, check these:**
1. ✅ Is the SDK initialized? Look for `[StackScope] Initialized successfully` in console
2. ✅ Are environment variables set correctly? Check your `.env*` files
3. ✅ Is the import path correct? `'stackscope'` for core, `'stackscope/react'` for React
4. ✅ Is debug mode enabled? Add `debug: true` to see console output

## 📦 Installation Issues

### ❌ "Module not found: 'stackscope'"

**Cause:** Package not installed or import path incorrect

**Solutions:**
```bash
# Reinstall package
npm install stackscope

# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install

# Check import path
import { createStackScope } from 'stackscope';        // ✅ Correct
import { createStackScope } from '@stackscope/sdk';   // ❌ Wrong
```

### ❌ "Cannot resolve 'stackscope/react'"

**Cause:** Using older version or wrong import

**Solutions:**
```javascript
// Check version (need v2.1.1+)
npm list stackscope

// Correct import
import { StackScopeProvider } from 'stackscope/react'; // ✅ Correct
import { StackScopeProvider } from 'stackscope';       // ❌ Wrong

// If still failing, clear TypeScript cache
rm -rf node_modules/.cache
npm run build
```

## 🌍 Environment Variable Issues

### ❌ "No workerUrl detected in environment variables"

**Cause:** Environment variables not set or wrong naming convention

**Framework-Specific Solutions:**

**Vite Projects:**
```bash
# .env.local (or .env)
VITE_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
VITE_STACKSCOPE_DEBUG=true
```

**Next.js Projects:**
```bash
# .env.local
NEXT_PUBLIC_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
NEXT_PUBLIC_STACKSCOPE_DEBUG=true
```

**Create React App:**
```bash
# .env.local
REACT_APP_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
REACT_APP_STACKSCOPE_DEBUG=true
```

**Manual Override:**
```javascript
const stackscope = createStackScope({
  workerUrl: 'https://your-worker.workers.dev', // Override env vars
  debug: true
});
```

### ❌ Environment variables not loading

**Solutions:**
```bash
# 1. Check file location (must be in project root)
ls -la .env*

# 2. Restart development server after changing env vars
npm run dev

# 3. Check if variables are public (need prefix)
# Vite: VITE_*
# Next.js: NEXT_PUBLIC_*  
# CRA: REACT_APP_*

# 4. Verify in browser console
console.log(import.meta.env.VITE_STACKSCOPE_WORKER_URL); // Vite
console.log(process.env.NEXT_PUBLIC_STACKSCOPE_WORKER_URL); // Next.js
```

## ⚛️ React Integration Issues

### ❌ "useStackScopeContext must be used within a StackScopeProvider"

**Cause:** Using hooks outside provider or provider not set up correctly

**Solution:**
```jsx
// ✅ Correct setup
function App() {
  return (
    <StackScopeProvider config={{ debug: true }}>
      <ComponentUsingHooks />
    </StackScopeProvider>
  );
}

function ComponentUsingHooks() {
  const logger = useStackScopeLogger(); // ✅ Inside provider
  return <div>Component</div>;
}

// ❌ Wrong - hook used outside provider
function App() {
  const logger = useStackScopeLogger(); // ❌ No provider above
  return <div>App</div>;
}
```

### ❌ React components not rendering/crashing

**Solutions:**
```jsx
// 1. Check React version (need 16.8+)
npm list react

// 2. Ensure error boundary is set up
function App() {
  return (
    <StackScopeErrorBoundary fallback={<div>Error occurred</div>}>
      <StackScopeProvider>
        <YourApp />
      </StackScopeProvider>
    </StackScopeErrorBoundary>
  );
}

// 3. Check for prop type errors
<StackScopeProvider 
  config={{ debug: true }}        // ✅ Object
  autoInit={true}                 // ✅ Boolean
>

// 4. Enable React strict mode debugging
<React.StrictMode>
  <StackScopeProvider>...</StackScopeProvider>
</React.StrictMode>
```

## 🌐 Network & Worker Issues

### ❌ "Failed to fetch" or network errors

**Cause:** Worker not deployed, wrong URL, or CORS issues

**Solutions:**
```javascript
// 1. Verify worker URL is correct
fetch('https://your-worker.workers.dev/health')
  .then(response => response.text())
  .then(console.log); // Should return "OK"

// 2. Check CORS settings in worker (if needed)
// Most Cloudflare Workers allow all origins by default

// 3. Use debug mode to see requests
const stackscope = createStackScope({
  debug: true, // Will log failed requests
  workerUrl: 'https://your-worker.workers.dev'
});

// 4. Test with curl
curl -X POST https://your-worker.workers.dev/webhook/browser \
  -H "Content-Type: application/json" \
  -d '{"test": true}'
```

### ❌ Worker responds with 404 or 500 errors

**Solutions:**
```bash
# 1. Check worker deployment
wrangler deployments list

# 2. Check worker logs
wrangler tail your-worker-name

# 3. Verify endpoint path
# Default: /webhook/browser
# Check your worker's routing configuration

# 4. Test worker health endpoint
curl https://your-worker.workers.dev/health
```

## 🔧 Build & TypeScript Issues

### ❌ TypeScript compilation errors

**Solutions:**
```bash
# 1. Update TypeScript and types
npm update typescript @types/node @types/react

# 2. Clear TypeScript cache
rm -rf node_modules/.cache/
npx tsc --build --clean
npm run build

# 3. Check tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

# 4. Add explicit types if needed
import type { SdkConfig } from 'stackscope';
```

### ❌ Bundle size warnings or build failures

**Solutions:**
```bash
# 1. Check if tree-shaking is working
import { createStackScope } from 'stackscope';          // ✅ Tree-shakable
import * as stackscope from 'stackscope';               // ❌ Imports everything

# 2. Use React imports only if needed
import { useStackScopeLogger } from 'stackscope/react'; // ✅ Separate bundle
import { createStackScope } from 'stackscope';          // ✅ Core only

# 3. Check build tool configuration
# Vite: Should work out of the box
# Webpack: Ensure ES modules enabled
```

## 🐛 Runtime Issues

### ❌ Logs not appearing in worker/console

**Debug Steps:**
```javascript
// 1. Enable debug mode
const stackscope = createStackScope({
  debug: true,     // Will log to browser console
  logLevel: 'debug' // Capture everything
});

// 2. Force a test log
import { logger } from 'stackscope';
logger.info('Test log message', { timestamp: Date.now() });

// 3. Check batch timing
setTimeout(() => {
  console.log('Check if logs were sent to worker');
}, 3000); // Wait for batch to send

// 4. Monitor network tab for POST requests
```

### ❌ Performance impact concerns

**Solutions:**
```javascript
// 1. Adjust batching for production
const stackscope = createStackScope({
  batchInterval: 5000,    // Send less frequently
  maxBatchSize: 20,       // Smaller batches
  logLevel: 'error'       // Only errors in production
});

// 2. Disable features you don't need
const stackscope = createStackScope({
  captureInteractions: false, // Disable click tracking
  capturePerformance: true,   // Keep Core Web Vitals
  captureConsole: true,       // Keep error logs
  captureNetwork: false       // Disable if not needed
});

// 3. Use worker-only logging in production
const stackscope = createStackScope({
  debug: false,              // No console logs
  workerUrl: 'https://...'   // Send to worker only
});
```

## 🚫 Worker Setup Required

StackScope requires a worker for both development and production. The worker:
- Receives and processes logs from your browser application
- Provides centralized log collection and analysis
- Enables GitHub webhook integration and monitoring

If you're having trouble setting up the worker, use the non-interactive setup script:

```bash
node node_modules/stackscope/scripts/create-worker-noninteractive.cjs my-worker
cd my-worker && npm install && node deploy.js
```

## 🔍 Debugging Checklist

When things aren't working:

```bash
# 1. Check package version
npm list stackscope

# 2. Verify environment variables
printenv | grep STACKSCOPE
# or
console.log(process.env) // Check in browser

# 3. Test basic imports
node -e "console.log(require('stackscope'))"

# 4. Check network connectivity
curl -I https://your-worker.workers.dev

# 5. Enable maximum debugging
const stackscope = createStackScope({
  debug: true,
  logLevel: 'debug',
  captureConsole: true
});

# 6. Check browser dev tools
# - Console for error messages
# - Network tab for requests
# - Application tab for storage
```

## 📱 Framework-Specific Issues

### Vite Issues
```bash
# Bundle analysis
npm run build -- --analyze

# Clear Vite cache
rm -rf node_modules/.vite
npm run dev

# Check Vite config for conflicts
export default defineConfig({
  optimizeDeps: {
    include: ['stackscope']
  }
});
```

### Next.js Issues
```bash
# Check Next.js config
module.exports = {
  transpilePackages: ['stackscope']
};

# Clear Next.js cache
rm -rf .next
npm run dev

# Check if SSR compatible
import dynamic from 'next/dynamic';
const StackScopeProvider = dynamic(
  () => import('stackscope/react').then(mod => mod.StackScopeProvider),
  { ssr: false }
);
```

### Webpack Issues
```javascript
// webpack.config.js
module.exports = {
  resolve: {
    alias: {
      'stackscope': path.resolve(__dirname, 'node_modules/stackscope')
    }
  }
};
```

## 📞 Getting Help

If these solutions don't work:

1. **GitHub Issues**: [Create new issue](https://github.com/JRGCr/StackScope/issues/new)
2. **Include Details**:
   - Package version (`npm list stackscope`)
   - Framework and versions
   - Error messages (full stack trace)
   - Code snippets showing your setup
   - Browser console logs with debug mode enabled

3. **Example Repositories**: Check `examples/` folder for working setups

## ✅ Verification Script

Test if everything is working:

```javascript
// test-stackscope.js
import { createStackScope, logger } from 'stackscope';

const stackscope = createStackScope({
  debug: true,
  workerUrl: 'https://your-worker.workers.dev' // Required for log collection
});

// Test logging
logger.info('StackScope test successful!', { 
  timestamp: new Date().toISOString(),
  test: true 
});

console.log('✅ If you see this and no errors above, StackScope is working!');
console.log('📡 Check your worker logs to confirm data is being received');
```

Run with: `node test-stackscope.js`

## 🔗 API Log Streaming Issues

### ❌ "stream-api-logs.sh: command not found"

**Cause:** Script not found or not executable

**Solutions:**
```bash
# Check if script exists
ls -la stream-api-logs.sh

# If missing, regenerate worker
node node_modules/stackscope/scripts/create-worker-noninteractive.cjs my-app-logs

# If exists but not executable
chmod +x stream-api-logs.sh
```

### ❌ "API directory not found"

**Cause:** Incorrect path to API worker directory

**Solutions:**
```bash
# Check directory structure
ls -la ../

# Use absolute path
./stream-api-logs.sh /full/path/to/your-api-worker production

# Or specify relative path
./stream-api-logs.sh ../../api-worker production
```

### ❌ "wrangler.toml not found in API directory"

**Cause:** API worker not properly configured

**Solutions:**
```bash
# Verify API worker setup
cd ../your-api-worker
ls -la wrangler.toml

# Initialize if missing
wrangler init --from-dash

# Check wrangler.toml contents
cat wrangler.toml
```

### ❌ "Not authenticated to Cloudflare"

**Cause:** Wrangler authentication required

**Solutions:**
```bash
# Authenticate with Cloudflare
wrangler auth login

# Verify authentication
wrangler whoami

# Check specific environment
cd ../your-api-worker
wrangler status
```

### ❌ "Failed to stream log (HTTP 400): Content-Type must be application/json"

**Cause:** Malformed JSON in wrangler tail output

**Solutions:**
```bash
# Test wrangler tail output manually
cd ../your-api-worker
wrangler tail --env production --format json | head -5

# Check for valid JSON lines
wrangler tail --env production --format json | jq '.'

# Restart streaming with debug
./stream-api-logs.sh ../your-api-worker production 2>&1 | tee debug.log
```

### ❌ "curl: command not found"

**Cause:** curl not installed (common on minimal containers)

**Solutions:**
```bash
# Install curl (Ubuntu/Debian)
sudo apt-get update && sudo apt-get install curl

# Install curl (Alpine)
apk add curl

# Install curl (macOS)
brew install curl

# Alternative: use wget
sed -i 's/curl -s/wget -O- --header/g' stream-api-logs.sh
```

### ❌ No API logs appearing in StackScope

**Cause:** Multiple potential issues

**Solutions:**
```bash
# 1. Verify API worker is getting traffic
cd ../your-api-worker
wrangler tail --env production

# 2. Check StackScope worker is receiving data
cd ../your-stackscope-worker  
wrangler tail --env production --search "api"

# 3. Test API endpoint directly
curl -X POST https://your-stackscope.workers.dev/webhook/api \
  -H "Content-Type: application/json" \
  -H "X-Source: test" \
  -d '{"eventTimestamp":123456789,"outcome":"ok","scriptName":"test"}'

# 4. Verify environment and URLs
echo "API Worker URL: $(wrangler status | grep -o 'https://[^[:space:]]*')"
echo "StackScope URL: $(cd ../stackscope-logs && wrangler status | grep -o 'https://[^[:space:]]*')"
```

### ❌ "Worker script not found" during wrangler tail

**Cause:** Worker not deployed or wrong environment

**Solutions:**
```bash
# Check deployments
cd ../your-api-worker
wrangler deployments list

# Deploy if needed
wrangler deploy --env production

# Check correct environment name
wrangler status

# List available environments
grep -A10 "\[env\." wrangler.toml
```

### ⚠️ High CPU usage from streaming script

**Cause:** Too many log events or inefficient parsing

**Solutions:**
```bash
# Add rate limiting to script
./stream-api-logs.sh ../your-api-worker production | head -100

# Use background mode with log rotation
nohup ./stream-api-logs.sh ../your-api-worker production > stream.log 2>&1 &

# Monitor resource usage
top -p $(pgrep -f stream-api-logs)

# Filter high-frequency logs at source
cd ../your-api-worker
wrangler tail --env production --format json --sampling-rate 0.1
```

### 🐛 Debugging Streaming Issues

**Enable verbose logging:**
```bash
# Add debug output to streaming script
STACKSCOPE_DEBUG=1 ./stream-api-logs.sh ../your-api-worker production

# Monitor all network requests
./stream-api-logs.sh ../your-api-worker production 2>&1 | grep -E "(HTTP|curl|POST)"

# Check JSON parsing
wrangler tail --env production --format json | jq -c '.' | head -5
```