Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { parseWorkspaceLinkUrl } from "./parseWorkspaceLinkUrl";
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, expect, it } from "bun:test";
import { parseWorkspaceLinkUrl } from "./parseWorkspaceLinkUrl";

const WEB_URL = "https://app.superset.sh";
const OPTIONS = { protocolScheme: "superset", webUrl: WEB_URL };
const WORKSPACE_ID = "eb417a4d-96f9-4f29-89ad-5cefe15e869a";

describe("parseWorkspaceLinkUrl", () => {
it.each([
`superset://v2-workspace/${WORKSPACE_ID}`,
`superset://workspace/${WORKSPACE_ID}`,
`superset://v2-workspace/${WORKSPACE_ID}/`,
`superset://v2-workspace/${WORKSPACE_ID}?sessionId=abc#top`,
`${WEB_URL}/workspaces/${WORKSPACE_ID}`,
`${WEB_URL}/workspaces/${WORKSPACE_ID}/`,
`${WEB_URL}/workspaces/${WORKSPACE_ID}?sessionId=abc#top`,
`https://app.paradev.com/workspaces/${WORKSPACE_ID}`,
])("extracts the workspace id from %s", (url) => {
expect(parseWorkspaceLinkUrl(url, OPTIONS)).toBe(WORKSPACE_ID);
});

it("uses the app's own protocol scheme", () => {
expect(
parseWorkspaceLinkUrl(
`superset-my-branch://v2-workspace/${WORKSPACE_ID}`,
{
protocolScheme: "superset-my-branch",
webUrl: WEB_URL,
},
),
).toBe(WORKSPACE_ID);
});

it("tolerates a trailing slash on the configured web URL", () => {
expect(
parseWorkspaceLinkUrl(`${WEB_URL}/workspaces/${WORKSPACE_ID}`, {
protocolScheme: "superset",
webUrl: `${WEB_URL}/`,
}),
).toBe(WORKSPACE_ID);
});

it("decodes a percent-encoded id", () => {
expect(
parseWorkspaceLinkUrl("superset://v2-workspace/a%20b", OPTIONS),
).toBe("a b");
});

it.each([
["another app scheme", `superset-dev://v2-workspace/${WORKSPACE_ID}`],
["another deep link", `superset://tasks/${WORKSPACE_ID}`],
["a plural deep link host", `superset://workspaces/${WORKSPACE_ID}`],
["a deep link with no id", "superset://v2-workspace"],
["a deep link with an empty id", "superset://v2-workspace/"],
["a nested deep link", `superset://v2-workspace/${WORKSPACE_ID}/files`],
["another web page", `${WEB_URL}/tasks/${WORKSPACE_ID}`],
["a web workspace with no id", `${WEB_URL}/workspaces/`],
["a nested web path", `${WEB_URL}/workspaces/${WORKSPACE_ID}/settings`],
["an empty path segment", `${WEB_URL}/workspaces//${WORKSPACE_ID}`],
["another origin", `https://evil.example.com/workspaces/${WORKSPACE_ID}`],
[
"http on the web host",
`http://app.superset.sh/workspaces/${WORKSPACE_ID}`,
],
["a file URL", `file:///workspaces/${WORKSPACE_ID}`],
["text that is not a URL", "not a url"],
["an empty string", ""],
])("returns null for %s", (_case, url) => {
expect(parseWorkspaceLinkUrl(url, OPTIONS)).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { isOwnOriginTwin } from "@superset/shared/own-domains";

const DEEP_LINK_HOSTS = ["workspace", "v2-workspace"];
const SINGLE_SEGMENT = /^\/([^/]+)\/?$/;
const WEB_WORKSPACE_PATH = /^\/workspaces\/([^/]+)\/?$/;

function decode(segment: string): string {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
}

function workspaceSegment(parsed: URL, protocolScheme: string, web: URL) {
if (parsed.protocol === `${protocolScheme}:`) {
if (!DEEP_LINK_HOSTS.includes(parsed.host)) return undefined;
return parsed.pathname.match(SINGLE_SEGMENT)?.[1];
}
if (!isOwnOriginTwin(parsed.origin, web.origin)) return undefined;
return parsed.pathname.match(WEB_WORKSPACE_PATH)?.[1];
}

export function parseWorkspaceLinkUrl(
url: string,
{ protocolScheme, webUrl }: { protocolScheme: string; webUrl: string },
): string | null {
let parsed: URL;
let web: URL;
try {
parsed = new URL(url);
web = new URL(webUrl);
} catch {
return null;
}

const segment = workspaceSegment(parsed, protocolScheme, web);
return segment ? decode(segment) : null;
}
215 changes: 211 additions & 4 deletions apps/desktop/src/renderer/lib/terminal/terminal-link-manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,31 @@
import { describe, expect, it, mock } from "bun:test";
import { beforeEach, describe, expect, it, mock } from "bun:test";
import type { ILinkProvider, Terminal as XTerm } from "@xterm/xterm";
import type { StatCallback } from "./links";
import { TerminalLinkManager } from "./terminal-link-manager";

function createMockTerminal({ hasSelection = false } = {}) {
const COLS = 80;
const APP_LINKS = new Set(["superset://v2-workspace/abc"]);
const isOscAppLink = (uri: string) => APP_LINKS.has(uri);
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));

function bufferLine(text: string) {
return {
translateToString: (_trim?: boolean, start = 0, end = COLS) =>
text.substring(start, end),
isWrapped: false,
length: COLS,
getCell: (x: number) => ({
getChars: () => text.padEnd(COLS)[x],
getWidth: () => 1,
}),
};
}

function createMockTerminal({
hasSelection = false,
lines = [] as string[],
} = {}) {
const bufferLines = lines.map(bufferLine);
const registeredProviders: ILinkProvider[] = [];
const disposedProviders: ILinkProvider[] = [];
const terminal = {
Expand All @@ -19,10 +42,12 @@ function createMockTerminal({ hasSelection = false } = {}) {
},
buffer: {
active: {
getLine: () => null,
length: bufferLines.length,
viewportY: 0,
getLine: (index: number) => bufferLines[index],
},
},
cols: 80,
cols: COLS,
hasSelection: () => hasSelection,
} as unknown as XTerm;

Expand Down Expand Up @@ -93,6 +118,188 @@ describe("TerminalLinkManager", () => {
expect(onUrlClick).toHaveBeenCalledWith(modified, "https://example.com");
});

describe("with an OSC 8 app link check", () => {
const range = { start: { x: 1, y: 1 }, end: { x: 20, y: 1 } };
const event = {} as MouseEvent;
let terminal: XTerm;
let onUrlClick: ReturnType<typeof mock>;
let onLinkHover: ReturnType<typeof mock>;

beforeEach(() => {
terminal = createMockTerminal().terminal;
onUrlClick = mock();
onLinkHover = mock();
new TerminalLinkManager(terminal).setHandlers({
stat: async () => null,
onUrlClick,
onLinkHover,
isOscAppLink,
});
});

it("lets xterm create non-http OSC 8 links", () => {
expect(terminal.options.linkHandler?.allowNonHttpProtocols).toBe(true);
});

it.each([
"superset://v2-workspace/abc",
"https://example.com",
"http://example.com",
])("activates %s", (uri) => {
terminal.options.linkHandler?.activate(event, uri, range);

expect(onUrlClick).toHaveBeenCalledWith(event, uri);
});

it.each([
"https://example.com",
"http://example.com",
])("reports hover on %s", (uri) => {
terminal.options.linkHandler?.hover?.(event, uri, range);

expect(onLinkHover).toHaveBeenCalledWith(event, {
kind: "url",
url: uri,
});
});

it("reports no hover on an app link", () => {
terminal.options.linkHandler?.hover?.(
event,
"superset://v2-workspace/abc",
range,
);

expect(onLinkHover).not.toHaveBeenCalled();
});

it.each([
"file:///etc/passwd",
"javascript:alert(1)",
"superset://tasks/abc",
"not a url",
])("never sends %s to the URL handler", async (uri) => {
terminal.options.linkHandler?.activate(event, uri, range);
terminal.options.linkHandler?.hover?.(event, uri, range);
await flush();

expect(onUrlClick).not.toHaveBeenCalled();
expect(onLinkHover).not.toHaveBeenCalled();
});
});

describe("with a non-app OSC 8 link over visible text", () => {
const event = {} as MouseEvent;
let onUrlClick: ReturnType<typeof mock>;
let onFileLinkClick: ReturnType<typeof mock>;
let onLinkHover: ReturnType<typeof mock>;
let manager: TerminalLinkManager;

function setUp(lines: string[], stat: StatCallback): XTerm {
const { terminal } = createMockTerminal({ lines });
onUrlClick = mock();
onFileLinkClick = mock();
onLinkHover = mock();
manager = new TerminalLinkManager(terminal);
manager.setHandlers({
stat,
onUrlClick,
onFileLinkClick,
onLinkHover,
isOscAppLink,
});
return terminal;
}

const existingFile: StatCallback = async () => ({
isDirectory: false,
resolvedPath: "/Users/me/repo/src/index.ts",
});
const visiblePath = "/Users/me/repo/src/index.ts:12:3";
const pathRange = { start: { x: 1, y: 1 }, end: { x: 32, y: 1 } };

it.each([
"cursor:///Users/me/repo/src/index.ts",
"file:///Users/me/repo/src/index.ts",
"superset://tasks/abc",
])("opens the visible path with its position for %s", async (uri) => {
const terminal = setUp([visiblePath], existingFile);
terminal.options.linkHandler?.activate(event, uri, pathRange);
await flush();

expect(onUrlClick).not.toHaveBeenCalled();
expect(onFileLinkClick).toHaveBeenCalledWith(
event,
expect.objectContaining({
resolvedPath: "/Users/me/repo/src/index.ts",
row: 12,
col: 3,
}),
);
});

it("reports the visible path on hover", async () => {
const terminal = setUp([visiblePath], existingFile);
terminal.options.linkHandler?.hover?.(event, "cursor:///x", pathRange);
await flush();

expect(onLinkHover).toHaveBeenCalledWith(
event,
expect.objectContaining({ kind: "file", row: 12, col: 3 }),
);
});

it("reports no hover once the pointer has left", async () => {
const terminal = setUp([visiblePath], existingFile);
terminal.options.linkHandler?.hover?.(event, "cursor:///x", pathRange);
terminal.options.linkHandler?.leave?.(event, "cursor:///x", pathRange);
await flush();

expect(onLinkHover).not.toHaveBeenCalled();
});

it("reports no hover once the handlers are replaced without stat", async () => {
const terminal = setUp([visiblePath], existingFile);
terminal.options.linkHandler?.hover?.(event, "cursor:///x", pathRange);
manager.setHandlers({});
await flush();

expect(onLinkHover).not.toHaveBeenCalled();
});

it("finds a visible link on a later row of the OSC range", async () => {
const terminal = setUp(
["see", "https://example.com/page"],
async () => null,
);
terminal.options.linkHandler?.activate(event, "cursor:///x", {
start: { x: 1, y: 1 },
end: { x: 24, y: 2 },
});
await flush();

expect(onUrlClick).toHaveBeenCalledWith(
expect.anything(),
"https://example.com/page",
);
});

it("does nothing when two separate visible links overlap it", async () => {
const terminal = setUp(
["/tmp/a.ts:12:3 https://example.com"],
async (path) => ({ isDirectory: false, resolvedPath: path }),
);
terminal.options.linkHandler?.activate(event, "cursor:///x", {
start: { x: 1, y: 1 },
end: { x: 34, y: 1 },
});
await flush();

expect(onUrlClick).not.toHaveBeenCalled();
expect(onFileLinkClick).not.toHaveBeenCalled();
});
});

it("clears only the OSC link handler it installed", () => {
const { terminal, disposedProviders } = createMockTerminal();
const manager = new TerminalLinkManager(terminal);
Expand Down
Loading
Loading