Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/warm-bags-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@spotlightjs/spotlight': minor
'@spotlightjs/overlay': minor
'@spotlightjs/sidecar': minor
---

Add 'open in editor' icon
12 changes: 11 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
{
"editor.formatOnSave": true,
"cSpell.words": ["Astro", "Astro's", "contextlines", "fontsource", "pageload", "spotlightjs", "tailwindcss", "uuidv"]
"cSpell.words": [
"Astro",
"Astro's",
"contextlines",
"fontsource",
"pageload",
"spotlightjs",
"svgr",
"tailwindcss",
"uuidv"
]
}
1 change: 1 addition & 0 deletions packages/overlay/src/assets/pen.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { useState } from 'react';
import { ReactComponent as PenIcon } from '~/assets/pen.svg';
import { renderValue } from '~/utils/values';
import classNames from '../../../../../lib/classNames';
import { EventFrame, FrameVars } from '../../../types';

function formatFilename(filename: string) {
const queryPos = filename.lastIndexOf('?');
if (queryPos > -1) {
filename = filename.slice(0, queryPos);
}
if (filename.indexOf('/node_modules/') === -1) return filename;
return `npm:${filename
.replace(/\/node_modules\//gi, 'npm:')
Expand Down Expand Up @@ -44,26 +49,23 @@ export default function Frame({
const [isOpen, setOpen] = useState(defaultExpand);

const hasSource = !!frame.context_line;
const fileName = platform === 'java' ? frame.module : frame.filename || frame.module;
return (
<li className="border-primary-900 bg-primary-900 border-b last:border-b-0">
<div
className={classNames(
hasSource ? 'hover:bg-primary-800 cursor-pointer' : '',
'border-primary-950 text-primary-400 border-b px-2 py-1',
)}
onClick={() => setOpen(!isOpen)}
onClick={hasSource ? () => setOpen(!isOpen) : undefined}
>
{platform === 'java' ? (
frame.module ? (
<span className="text-primary-100">{`${formatFilename(frame.module)} in `}</span>
) : frame.filename ? (
<span className="text-primary-100">{`${formatFilename(frame.filename)} in `}</span>
) : null
) : frame.filename ? (
<span className="text-primary-100">{`${formatFilename(frame.filename)} in `}</span>
) : frame.module ? (
<span className="text-primary-100">{`${formatFilename(frame.module)} in `}</span>
{fileName ? (
<span className="text-primary-100">
{formatFilename(fileName)}
{' in '}
</span>
) : null}

<span className="text-primary-100">{frame.function}</span>
{frame.lineno !== undefined && (
<>
Expand All @@ -75,6 +77,22 @@ export default function Frame({
</span>
</>
)}
{isOpen && !frame.filename?.includes(':') ? (
<PenIcon
width={18}
height={18}
title="Open in editor"
className="mx-2 inline fill-green-400 stroke-green-400 align-top"
onClick={evt => {
fetch('http://localhost:8969/open', {
method: 'POST',
body: `${frame.filename}:${frame.lineno}:${frame.colno}`,
credentials: 'omit',
});
evt.stopPropagation();
}}
/>
) : null}
</div>
{isOpen && (
<div className="bg-primary-950">
Expand Down
6 changes: 5 additions & 1 deletion packages/overlay/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ export default defineConfig({
dts({
insertTypesEntry: true,
}),
svgr(),
svgr({
svgrOptions: {
titleProp: true,
},
}),
removeReactDevToolsMessagePlugin(),
],
define: {
Expand Down
6 changes: 4 additions & 2 deletions packages/sidecar/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"license": "Apache-2.0",
"type": "module",
"scripts": {
"start": "./server.js",
"dev": "vite build --watch",
"build": "vite build && tsc",
"build:watch": "vite build --watch",
Expand Down Expand Up @@ -38,10 +39,11 @@
},
"dependencies": {},
"devDependencies": {
"source-map": "^0.7.4",
"kleur": "^4.1.5",
"@spotlightjs/tsconfig": "workspace:*",
"launch-editor": "^2.8.0",
"@types/node": "^18",
"kleur": "^4.1.5",
"source-map": "^0.7.4",
"typescript": "^5.0.2",
"vite": "^4.5.3"
},
Expand Down
6 changes: 5 additions & 1 deletion packages/sidecar/src/contextlines.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs';
import { IncomingMessage, ServerResponse } from 'node:http';
import * as os from 'node:os';
import * as path from 'node:path';
import * as SourceMap from 'source-map';

type SourceContext = {
Expand Down Expand Up @@ -50,6 +51,9 @@ async function applySourceContextToFrame(sourceMapContent: string, frame: ValidS
if (originalPosition.source && originalPosition.line && originalPosition.column) {
frame.lineno = originalPosition.line;
frame.colno = originalPosition.column;
const filePath = new URL(frame.filename).pathname.slice(1); // slice(1) is to not make it absolute path
frame.filename = path.resolve(path.join(path.dirname(filePath), originalPosition.source));

const content = consumer.sourceContentFor(originalPosition.source);
const lines = content?.split(os.EOL) ?? [];
addContextLinesToFrame(lines, frame);
Expand Down Expand Up @@ -121,7 +125,7 @@ function isValidSentryStackFrame(frame: SentryStackFrame): frame is ValidSentryS
}

export function contextLinesHandler(req: IncomingMessage, res: ServerResponse) {
// We're only interested in handling a PUT request to CONTEXT_LINES_ENDPOINT
// We're only interested in handling a PUT request
if (req.method !== 'PUT') {
res.writeHead(405);
res.end();
Expand Down
1 change: 1 addition & 0 deletions packages/sidecar/src/launch-editor.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'launch-editor';
87 changes: 61 additions & 26 deletions packages/sidecar/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import launchEditor from 'launch-editor';
import { createWriteStream, readFile } from 'node:fs';
import { IncomingMessage, Server, ServerResponse, createServer, get } from 'node:http';
import { extname, join } from 'node:path';
import { extname, join, resolve } from 'node:path';
import { createGunzip, createInflate } from 'node:zlib';
import { CONTEXT_LINES_ENDPOINT, DEFAULT_PORT, SERVER_IDENTIFIER } from './constants.js';
import { contextLinesHandler } from './contextlines.js';
Expand Down Expand Up @@ -43,6 +44,8 @@ type SideCarOptions = {
incomingPayload?: IncomingPayloadCallback;
};

type RequestHandler = (req: IncomingMessage, res: ServerResponse) => void;

function getCorsHeader(): { [name: string]: string } {
return {
'Access-Control-Allow-Origin': '*',
Expand All @@ -52,6 +55,26 @@ function getCorsHeader(): { [name: string]: string } {
};
}

function enableCORS(handler: RequestHandler): RequestHandler {
return function corsMiddleware(req: IncomingMessage, res: ServerResponse) {
const headers = {
...getCorsHeader(),
...getSpotlightHeader(),
};
for (const [header, value] of Object.entries(headers)) {
res.setHeader(header, value);
}
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Cache-Control': 'no-cache',
});
res.end();
return;
}
return handler(req, res);
};
}

function getSpotlightHeader() {
return {
'X-Powered-by': SERVER_IDENTIFIER,
Expand All @@ -64,8 +87,6 @@ function streamRequestHandler(buffer: MessageBuffer<Payload>, incomingPayload?:
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
...getCorsHeader(),
...getSpotlightHeader(),
Connection: 'keep-alive',
});
res.flushHeaders();
Expand All @@ -87,13 +108,6 @@ function streamRequestHandler(buffer: MessageBuffer<Payload>, incomingPayload?:
buffer.unsubscribe(sub);
res.end();
});
} else if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Cache-Control': 'no-cache',
...getCorsHeader(),
...getSpotlightHeader(),
});
res.end();
} else if (req.method === 'POST') {
logger.debug(`📩 Received event`);
let body: string = '';
Expand Down Expand Up @@ -136,8 +150,6 @@ function streamRequestHandler(buffer: MessageBuffer<Payload>, incomingPayload?:
// 204 would be more appropriate but returning 200 to match what /envelope returns
res.writeHead(200, {
'Cache-Control': 'no-cache',
...getCorsHeader(),
...getSpotlightHeader(),
Connection: 'keep-alive',
});
res.end();
Expand Down Expand Up @@ -189,18 +201,9 @@ function handleHealthRequest(_req: IncomingMessage, res: ServerResponse): void {
}

function handleClearRequest(req: IncomingMessage, res: ServerResponse): void {
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Cache-Control': 'no-cache',
...getCorsHeader(),
...getSpotlightHeader(),
});
res.end();
} else if (req.method === 'DELETE') {
if (req.method === 'DELETE') {
res.writeHead(200, {
'Content-Type': 'text/plain',
...getCorsHeader(),
...getSpotlightHeader(),
});
clearBuffer();
res.end('Cleared');
Expand All @@ -209,6 +212,37 @@ function handleClearRequest(req: IncomingMessage, res: ServerResponse): void {
}
}

function openRequestHandler(basePath: string = process.cwd()) {
return function (req: IncomingMessage, res: ServerResponse) {
// We're only interested in handling a POST request
if (req.method !== 'POST') {
res.writeHead(405);
res.end();
return;
}

let requestBody = '';
req.on('data', chunk => {
requestBody += chunk;
});

req.on('end', () => {
const targetPath = resolve(basePath, requestBody);
launchEditor(
// filename:line:column
// both line and column are optional
targetPath,
// callback if failed to launch (optional)
(fileName: string, errorMsg: string) => {
logger.error(`Failed to launch editor for ${fileName}: ${errorMsg}`);
},
);
res.writeHead(204);
res.end();
});
};
}

function errorResponse(code: number) {
return (_req: IncomingMessage, res: ServerResponse) => {
res.writeHead(code);
Expand All @@ -225,11 +259,12 @@ function startServer(
basePath?: string,
incomingPayload?: IncomingPayloadCallback,
): Server {
const ROUTES: [RegExp, (req: IncomingMessage, res: ServerResponse) => void][] = [
const ROUTES: [RegExp, RequestHandler][] = [
[/^\/health$/, handleHealthRequest],
[/^\/clear$/, handleClearRequest],
[/^\/stream$|^\/api\/\d+\/envelope$/, streamRequestHandler(buffer, incomingPayload)],
[RegExp(`^${CONTEXT_LINES_ENDPOINT}$`), contextLinesHandler],
[/^\/clear$/, enableCORS(handleClearRequest)],
[/^\/stream$|^\/api\/\d+\/envelope$/, enableCORS(streamRequestHandler(buffer, incomingPayload))],
[/^\/open$/, enableCORS(openRequestHandler(basePath))],
[RegExp(`^${CONTEXT_LINES_ENDPOINT}$`), enableCORS(contextLinesHandler)],
[/^.+$/, basePath != null ? fileServer(basePath) : error404],
];

Expand Down
1 change: 1 addition & 0 deletions packages/spotlight/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"license": "Apache-2.0",
"type": "module",
"scripts": {
"start": "./bin/run.js",
"dev": "vite build --watch",
"build": "vite build && vite build --config vite.overlay.config.ts && tsc",
"build:watch": "vite build --watch",
Expand Down
14 changes: 14 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.