Skip to content

Commit

Permalink
Add debug option to Spotlight
Browse files Browse the repository at this point in the history
  • Loading branch information
HazAT committed Nov 23, 2023
1 parent df5160a commit 9f9370f
Show file tree
Hide file tree
Showing 13 changed files with 62 additions and 23 deletions.
6 changes: 6 additions & 0 deletions .changeset/perfect-carrots-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@spotlightjs/astro': patch
'@spotlightjs/core': patch
---

Add debug flag to Spotlight
3 changes: 2 additions & 1 deletion packages/astro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const PKG_NAME = '@spotlightjs/astro';
export type SpotlightOptions =
| {
__debugOptions?: ClientInitOptions;
debug: boolean;
}
| undefined;

Expand All @@ -35,7 +36,7 @@ const createPlugin = (options?: SpotlightOptions): AstroIntegration => {
...(config.vite.plugins || []),
];

injectScript('page', buildClientInitSnippet({ importPath: PKG_NAME, showTriggerButton: false }));
injectScript('page', buildClientInitSnippet({ importPath: PKG_NAME, showTriggerButton: false, ...options }));
injectScript('page-ssr', SPOTLIGHT_SERVER_SNIPPET);

const importPath = path.dirname(url.fileURLToPath(import.meta.url));
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Spotlight.init({
],
showTriggerButton: ${options.showTriggerButton === false ? 'false' : 'true'},
injectImmediately: ${options.injectImmediately === true ? 'true' : 'false'},
debug: ${options.debug === true ? 'true' : 'false'},
});
`;
};
Expand Down
11 changes: 6 additions & 5 deletions packages/core/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Debugger from './components/Debugger';
import Trigger, { type Anchor } from './components/Trigger';
import type { Integration, IntegrationData } from './integrations/integration';
import { getSpotlightEventTarget } from './lib/eventTarget';
import { log } from './lib/logger';
import { connectToSidecar } from './sidecar';
import { TriggerButtonCount } from './types';

Expand All @@ -23,7 +24,7 @@ export default function App({
sidecar,
anchor,
}: AppProps) {
console.log('[Spotlight] App rerender');
log('App rerender');

const [integrationData, setIntegrationData] = useState<IntegrationData<unknown>>({});
const [isOnline, setOnline] = useState(false);
Expand Down Expand Up @@ -52,7 +53,7 @@ export default function App({
);

return () => {
console.log('[Spotlight] useeffect cleanup');
log('useEffect cleanup');
cleanupListeners();
};
}, [integrations, sidecar]);
Expand All @@ -61,12 +62,12 @@ export default function App({

useEffect(() => {
const onOpen = () => {
console.log('[Spotlight] Open');
log('Open');
setOpen(true);
};

const onClose = () => {
console.log('[Spotlight] Close');
log('Close');
setOpen(false);
};

Expand All @@ -88,7 +89,7 @@ export default function App({
}
}, [isOpen]);

console.log('[Spotlight] Integrations', integrationData);
log('Integrations', integrationData);

return (
<>
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Integration } from './integrations/integration.ts';
import { initIntegrations } from './integrations/integration.ts';
import { default as sentry } from './integrations/sentry/index.ts';
import { getSpotlightEventTarget } from './lib/eventTarget.ts';
import { activateLogger, log } from './lib/logger.ts';
import { WindowWithSpotlight } from './types.ts';

export { default as console } from './integrations/console/index.ts';
Expand Down Expand Up @@ -52,6 +53,7 @@ export async function init({
injectImmediately = false,
sidecar = DEFAULT_SIDECAR,
anchor = DEFAULT_ANCHOR,
debug = false,
}: {
integrations?: Integration[];
fullScreen?: boolean;
Expand All @@ -61,6 +63,7 @@ export async function init({
injectImmediately?: boolean;
sidecar?: string;
anchor?: Anchor;
debug?: boolean;
} = {}) {
if (typeof document === 'undefined') return;

Expand All @@ -71,6 +74,9 @@ export async function init({
return;
}

if (debug) {
activateLogger();
}
const initializedIntegrations = await initIntegrations(integrations);

// build shadow dom container to contain styles
Expand Down Expand Up @@ -107,7 +113,7 @@ export async function init({
);

function injectSpotlight() {
console.log('[spotlight] Injecting into application');
log('Injecting into application');
document.body.append(docRoot);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export default function PlatformIcon({
platform?: Platform;
event?: SentryEvent;
}) {
console.log('SDK:', platform, event?.platform);
const name = platform || event?.platform || 'unknown';
switch (name) {
case 'ruby':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ class SentryDataCache {

items.forEach(([itemHeader, itemData]) => {
if (itemHeader.type === 'event' || itemHeader.type === 'transaction') {
console.log(sdkToPlatform(sdk.name));
(itemData as SentryEvent).platform = sdkToPlatform(sdk.name);
this.pushEvent(itemData as SentryEvent);
}
Expand Down
5 changes: 0 additions & 5 deletions packages/core/src/integrations/sentry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import TracesTab from './tabs/TracesTab';
const HEADER = 'application/x-sentry-envelope';

export default function sentryIntegration() {
console.log('spotlight', sentryDataCache.getEvents());

return {
name: 'sentry',
forwardedContentType: [HEADER],
Expand Down Expand Up @@ -60,12 +58,9 @@ type WindowWithSentry = Window & {
};

export function processEnvelope({ data }: RawEventContext) {
console.log('[Spotlight] Received new envelope');
const [rawHeader, ...rawEntries] = data.split(/\n/gm);

const header = JSON.parse(rawHeader) as Envelope[0];
console.log(`[Spotlight] Received new envelope from SDK ${header.sdk?.name || '(unknown)'}`);

const items: Envelope[1][] = [];
for (let i = 0; i < rawEntries.length; i += 2) {
// guard both rawEntries[i] and rawEntries[i + 1] are defined and not empty
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/integrations/sentry/utils/traces.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { log } from '../../../lib/logger';
import { Span } from '../types';

// mutates spans in place and adds children, as well as returns the top level tree
Expand All @@ -19,9 +20,9 @@ export function groupSpans(spans: Span[]) {
} else if (span.parent_span_id) {
const parentParent = sortedSpans.find(s => !s.parent_span_id);
if (!parentParent) {
console.log(`Root span (${span.parent_span_id}) for span (${span.span_id}). Creating orphan.`);
log(`Root span (${span.parent_span_id}) for span (${span.span_id}). Creating orphan.`);
} else {
console.log(`Creating orphan for parent (${span.parent_span_id}) for span (${span.span_id})`);
log(`Creating orphan for parent (${span.parent_span_id}) for span (${span.span_id})`);
}
parent = {
trace_id: span.trace_id,
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
let loggerActive = false;

export function activateLogger() {
loggerActive = true;
}

export function deactivateLogger() {
loggerActive = false;
}

export function log(...args: unknown[]) {
if (loggerActive) {
console.log('🔎 [Spotlight]', ...args);
}
}
13 changes: 7 additions & 6 deletions packages/core/src/sidecar.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import { Integration, IntegrationData } from './integrations/integration';
import { log } from './lib/logger';
import { TriggerButtonCount } from './types';

export function connectToSidecar(
Expand All @@ -9,14 +10,14 @@ export function connectToSidecar(
setOnline: React.Dispatch<React.SetStateAction<boolean>>,
setTriggerButtonCount: React.Dispatch<React.SetStateAction<TriggerButtonCount>>,
): () => void {
console.log('[Spotlight] Connecting to sidecar at', sidecar);
log('Connecting to sidecar at', sidecar);
const source = new EventSource(sidecar);

const contentTypeListeners: [contentType: string, listener: (event: MessageEvent) => void][] = [];

for (const [contentType, integrations] of contentTypeToIntegrations.entries()) {
const listener = (event: MessageEvent): void => {
console.log(`[spotlight] Received new ${contentType} event`);
log(`Received new ${contentType} event`);
integrations.forEach(integration => {
if (integration.processEvent) {
const processedEvent = integration.processEvent({
Expand All @@ -43,7 +44,7 @@ export function connectToSidecar(
});
};

console.log('[spotlight] adding listener for', contentType, 'sum', contentTypeListeners.length);
log('Adding listener for', contentType, 'sum', contentTypeListeners.length);

// `contentType` could for example be "application/x-sentry-envelope"
contentTypeListeners.push([contentType, listener]);
Expand All @@ -52,7 +53,7 @@ export function connectToSidecar(

source.addEventListener('open', () => {
setOnline(true);
console.log('[Spotlight] open');
log('Open');
});

source.addEventListener('error', err => {
Expand All @@ -61,10 +62,10 @@ export function connectToSidecar(
});

return () => {
console.log(`[spotlight] removing ${contentTypeListeners.length} listeners`);
log(`Removing ${contentTypeListeners.length} listeners`);
contentTypeListeners.forEach(typeAndListener => {
source.removeEventListener(typeAndListener[0], typeAndListener[1]);
console.log('[spotlight] removed listner for type', typeAndListener[0]);
log('Removed listner for type', typeAndListener[0]);
});
};
}
4 changes: 3 additions & 1 deletion packages/website/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export default defineConfig({
sentry({
debug: true,
}),
spotlight(),
spotlight({
debug: true,
}),
starlight({
title: 'Spotlight',
logo: {
Expand Down
12 changes: 12 additions & 0 deletions packages/website/src/content/docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ init({
type SpotlightIntegration = {};
```

### `debug`

**type:** boolean **default:** false

Enables some debug output in console for debugging.

```ts
init({
debug: true,
});
```

### `sidecar`

**type:** string
Expand Down

0 comments on commit 9f9370f

Please sign in to comment.