Skip to content

TagSpaces is an offline, open source, document manager with tagging support

chore: refactoring the openLink functionality, adding tests

Ilian Sapundshiev3b934d22763e
diff --git a/src/renderer/hooks/OpenedEntryContextProvider.tsx b/src/renderer/hooks/OpenedEntryContextProvider.tsx
index f5e2a6c03..60247934a 100644
--- a/src/renderer/hooks/OpenedEntryContextProvider.tsx
+++ b/src/renderer/hooks/OpenedEntryContextProvider.tsx
@@ -45,6 +45,7 @@ import {
import { TS } from '-/tagspaces.namespace';
import { CommonLocation } from '-/utils/CommonLocation';
import { clearURLParam, getURLParameter, updateHistory } from '-/utils/dom';
+import { isPathEscape, parseTsLink, resolveRelativePath } from '-/utils/tsLink';
import useFirstRender from '-/utils/useFirstRender';
import versionMeta from '-/version.json';
import {
@@ -691,32 +692,27 @@ export const OpenedEntryContextProvider = ({
}
}
- function isRelativeLink(uri: string): boolean {
- if (!uri) return false;
- if (
- uri.startsWith('#') ||
- uri.startsWith('?') ||
- uri.startsWith('/') ||
- uri.startsWith('\\')
- ) {
- return false;
- }
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(uri)) return false; // any protocol or Windows drive letter
- return true;
- }
-
function openLink(url: string, options = { fullWidth: true }) {
try {
- const decodedURI = decodeURI(url);
- const lid = getURLParameter('tslid', url);
- const dPath = getURLParameter('tsdpath', url);
- const ePath = getURLParameter('tsepath', url);
- const cmdOpen = getURLParameter('cmdopen', url);
- const id = getURLParameter('tseid', url);
- if (cmdOpen && cmdOpen.length > 0) {
- const entryPath = decodeURIComponent(cmdOpen);
- const locationId = lid ? lid : getFirstRWLocation()?.uuid;
- getAllPropertiesPromise(entryPath, locationId)
+ const parsed = parseTsLink(
+ url,
+ window.location.origin + window.location.pathname,
+ );
+
+ const invalidLink = () =>
+ showNotification(t('core:invalidLink'), 'warning', true);
+
+ const openEntry = (fsEntry: TS.FileSystemEntry) => {
+ openFsEntry(fsEntry);
+ setSelectedEntries([fsEntry]);
+ if (options.fullWidth) {
+ setEntryInFullWidth(true);
+ }
+ };
+
+ if (parsed.kind === 'cmd' && parsed.cmdOpen) {
+ const locationId = parsed.lid || getFirstRWLocation()?.uuid;
+ getAllPropertiesPromise(parsed.cmdOpen, locationId)
.then((fsEntry: TS.FileSystemEntry) => {
if (fsEntry) {
if (fsEntry.isFile) {
@@ -729,207 +725,150 @@ export const OpenedEntryContextProvider = ({
}
return true;
})
- .catch((err) => {
- // console.log('Error opening from cmd ' + JSON.stringify(err));
+ .catch(() => {
showNotification(t('Missing file or folder'), 'warning', true);
});
- } else if (lid && lid.length > 0) {
- const locationId = decodeURIComponent(lid);
- let directoryPath = dPath && decodeURIComponent(dPath);
- const entryPath = ePath && decodeURIComponent(ePath);
- // fix for created bookmarks files without to have tsdpath in url
- if (!directoryPath && entryPath) {
- directoryPath = extractContainingDirectoryPath(entryPath);
+ return;
+ }
+
+ if (parsed.kind === 'ts' && parsed.lid) {
+ const { lid, ePath, id } = parsed;
+ let dPath = parsed.dPath;
+ // Bookmarks created without tsdpath — derive from tsepath.
+ if (!dPath && ePath) {
+ dPath = extractContainingDirectoryPath(ePath);
}
- // Check for relative paths
- const targetLocation: CommonLocation = findLocation(locationId);
- if (targetLocation) {
- //let openLocationTimer = 1000;
- const isCloudLocation =
- targetLocation.type === locationType.TYPE_CLOUD;
- if (
- !currentLocation ||
- targetLocation.uuid !== currentLocation.uuid
- ) {
- openLocation(targetLocation, true);
- } /*else {
- openLocationTimer = 0;
- }*/
- getLocationPath(targetLocation).then((path) => {
- const locationPath: string = cleanTrailingDirSeparator(path);
- // setTimeout is needed for case of a location switch, if no location swith the timer is 0
- //setTimeout(() => {
- if (isCloudLocation) {
- if (directoryPath && directoryPath.length > 0) {
- const newRelDir = getRelativeEntryPath(path, directoryPath);
- const dirFullPath =
- locationPath.length > 0
- ? locationPath + '/' + newRelDir
- : directoryPath;
- openDirectory(dirFullPath, undefined, targetLocation);
- } else {
- openDirectory(locationPath, undefined, targetLocation);
- }
+ const targetLocation: CommonLocation = findLocation(lid);
+ if (!targetLocation) {
+ invalidLink();
+ return;
+ }
- if (entryPath) {
- const filePath =
- (locationPath.length > 0 ? locationPath + '/' : '') +
- entryPath;
- getAllPropertiesPromise(filePath, lid)
- .then((fsEntry: TS.FileSystemEntry) => {
- if (fsEntry) {
- openFsEntry(fsEntry);
- setSelectedEntries([fsEntry]);
- if (options.fullWidth) {
- setEntryInFullWidth(true);
- }
- }
- return true;
- })
- .catch(() =>
- showNotification(t('core:invalidLink'), 'warning', true),
- );
- }
- // });
+ const isCloudLocation = targetLocation.type === locationType.TYPE_CLOUD;
+ if (!currentLocation || targetLocation.uuid !== currentLocation.uuid) {
+ openLocation(targetLocation, true);
+ }
+
+ getLocationPath(targetLocation).then((path) => {
+ const locationPath: string = cleanTrailingDirSeparator(path);
+
+ if (isCloudLocation) {
+ if (dPath && dPath.length > 0) {
+ const newRelDir = getRelativeEntryPath(path, dPath);
+ const dirFullPath =
+ locationPath.length > 0
+ ? locationPath + '/' + newRelDir
+ : dPath;
+ openDirectory(dirFullPath, undefined, targetLocation);
} else {
- // local files case
- let dirPath = locationPath;
- if (directoryPath && directoryPath.length > 0) {
- if (
- directoryPath.includes('../') ||
- directoryPath.includes('..\\')
- ) {
- showNotification(t('core:invalidLink'), 'warning', true);
+ openDirectory(locationPath, undefined, targetLocation);
+ }
+
+ if (ePath) {
+ const filePath =
+ (locationPath.length > 0 ? locationPath + '/' : '') + ePath;
+ getAllPropertiesPromise(filePath, lid)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ if (fsEntry) openEntry(fsEntry);
return true;
- }
+ })
+ .catch(() => invalidLink());
+ }
+ return;
+ }
- dirPath = joinPaths(
- targetLocation.getDirSeparator(),
- locationPath,
- directoryPath,
- );
+ // Local filesystem.
+ if (isPathEscape(dPath)) {
+ invalidLink();
+ return;
+ }
+ const sep = targetLocation.getDirSeparator();
+ const dirPath =
+ dPath && dPath.length > 0
+ ? joinPaths(sep, locationPath, dPath)
+ : locationPath;
+
+ targetLocation.checkDirExist(dirPath).then((exist) => {
+ if (!exist) {
+ if (id) {
+ setLinkFromSearchConfirmDialogOpened(id);
+ } else {
+ invalidLink();
}
- targetLocation.checkDirExist(dirPath).then((exist) => {
- if (exist) {
- openDirectory(dirPath, undefined, targetLocation).then(() => {
- if (entryPath && entryPath.length > 0) {
- if (
- entryPath.includes('../') ||
- entryPath.includes('..\\')
- ) {
- showNotification(
- t('core:invalidLink'),
- 'warning',
- true,
- );
- return true;
- }
- const entryFullPath =
- locationPath +
- targetLocation.getDirSeparator() +
- entryPath;
- getAllPropertiesPromise(entryFullPath, lid)
- .then((fsEntry: TS.FileSystemEntry) => {
- if (fsEntry) {
- openFsEntry(fsEntry);
- setSelectedEntries([fsEntry]);
- if (options.fullWidth) {
- setEntryInFullWidth(true);
- }
- } else if (id) {
- //ENTRY NOT EXIST maybe moved
- setLinkFromSearchConfirmDialogOpened(id);
- }
- return true;
- })
- .catch(() =>
- showNotification(
- t('core:invalidLink'),
- 'warning',
- true,
- ),
- );
- }
- });
- } else if (id) {
- //ENTRY NOT EXIST maybe moved
- setLinkFromSearchConfirmDialogOpened(id);
- } else {
- showNotification(t('core:invalidLink'), 'warning', true);
- }
- });
+ return;
}
- //}, openLocationTimer);
+ openDirectory(dirPath, undefined, targetLocation).then(() => {
+ if (!ePath || ePath.length === 0) return;
+ if (isPathEscape(ePath)) {
+ invalidLink();
+ return;
+ }
+ const entryFullPath = locationPath + sep + ePath;
+ getAllPropertiesPromise(entryFullPath, lid)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ if (fsEntry) {
+ openEntry(fsEntry);
+ } else if (id) {
+ setLinkFromSearchConfirmDialogOpened(id);
+ }
+ return true;
+ })
+ .catch(() => invalidLink());
+ });
});
- } else {
- showNotification(t('core:invalidLink'), 'warning', true);
- }
- } else if (
- decodedURI ===
- window.location.origin + window.location.pathname
- ) {
- // Ignore links that point to the current web app page itself (no ts params)
- return true;
- } else if (
- // External URL case
- decodedURI.startsWith('onenote:') ||
- decodedURI.startsWith('mailto:') ||
- decodedURI.startsWith('tel:') ||
- decodedURI.startsWith('http://') ||
- decodedURI.startsWith('https://') ||
- decodedURI.startsWith('file://')
- ) {
- openURLExternally(decodedURI);
- } else if (currentEntry.current && isRelativeLink(decodedURI)) {
- if (decodedURI.includes('../') || decodedURI.includes('..\\')) {
- showNotification(t('core:invalidLink'), 'warning', true);
- return true;
+ });
+ return;
+ }
+
+ if (parsed.kind === 'self') {
+ return;
+ }
+
+ if (parsed.kind === 'external') {
+ openURLExternally(parsed.decodedURI);
+ return;
+ }
+
+ if (parsed.kind === 'relative' && currentEntry.current) {
+ if (isPathEscape(parsed.decodedURI)) {
+ invalidLink();
+ return;
}
const entryLocation = findLocation(currentEntry.current.locationID);
if (!entryLocation) {
- showNotification(t('core:invalidLink'), 'warning', true);
- return true;
+ invalidLink();
+ return;
}
const sep = entryLocation.getDirSeparator();
const baseDir = extractContainingDirectoryPath(
currentEntry.current.path,
sep,
);
- const relPath = decodedURI
- .replace(/^\.[\/\\]/, '')
- .split(/[\/\\]/)
- .filter((p) => p.length > 0)
- .join(sep);
- const targetPath = joinPaths(sep, baseDir, relPath);
+ const targetPath = resolveRelativePath(baseDir, parsed.decodedURI, sep);
getAllPropertiesPromise(targetPath, entryLocation.uuid)
.then((fsEntry: TS.FileSystemEntry) => {
if (fsEntry) {
if (fsEntry.isFile) {
- openFsEntry(fsEntry);
- setSelectedEntries([fsEntry]);
- if (options.fullWidth) {
- setEntryInFullWidth(true);
- }
+ openEntry(fsEntry);
} else {
openDirectory(fsEntry.path, undefined, entryLocation);
}
} else {
- showNotification(t('core:invalidLink'), 'warning', true);
+ invalidLink();
}
return true;
})
- .catch(() =>
- showNotification(t('core:invalidLink'), 'warning', true),
- );
- } else {
- showNotification(
- t('core:urlNotSupported') + ': ' + decodedURI,
- 'info',
- true,
- );
- console.log('Not supported URL format: ' + decodedURI);
+ .catch(() => invalidLink());
+ return;
}
+
+ showNotification(
+ t('core:urlNotSupported') + ': ' + parsed.decodedURI,
+ 'info',
+ true,
+ );
+ console.log('Not supported URL format: ' + parsed.decodedURI);
} catch (e) {
console.log('OpenLink:', e);
}
diff --git a/src/renderer/utils/tsLink.ts b/src/renderer/utils/tsLink.ts
new file mode 100644
index 000000000..084ba064b
--- /dev/null
+++ b/src/renderer/utils/tsLink.ts
@@ -0,0 +1,151 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import { joinPaths } from '@tagspaces/tagspaces-common/paths';
+
+export type TsLinkKind =
+ | 'cmd'
+ | 'ts'
+ | 'external'
+ | 'relative'
+ | 'self'
+ | 'unsupported';
+
+export interface TsLinkParsed {
+ kind: TsLinkKind;
+ decodedURI: string;
+ lid?: string;
+ dPath?: string;
+ ePath?: string;
+ cmdOpen?: string;
+ id?: string;
+}
+
+export const EXTERNAL_PROTOCOLS = [
+ 'http://',
+ 'https://',
+ 'onenote:',
+ 'mailto:',
+ 'tel:',
+ 'file://',
+];
+
+function readParam(name: string, url: string): string | null {
+ try {
+ const param = new URL(url).searchParams.get(name);
+ // Milkdown editor workaround — it appends a trailing backslash to param values.
+ return param?.endsWith('\\') ? param.slice(0, -1) : param;
+ } catch {
+ return null;
+ }
+}
+
+function safeDecode(value: string | null): string | undefined {
+ if (value === null) return undefined;
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+export function isPathEscape(path: string | null | undefined): boolean {
+ if (!path) return false;
+ return path.includes('../') || path.includes('..\\');
+}
+
+export function isRelativeLink(uri: string): boolean {
+ if (!uri) return false;
+ if (
+ uri.startsWith('#') ||
+ uri.startsWith('?') ||
+ uri.startsWith('/') ||
+ uri.startsWith('\\')
+ ) {
+ return false;
+ }
+ // Any protocol (http:, ts:, mailto:) or Windows drive letter (C:) — not relative.
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(uri)) return false;
+ return true;
+}
+
+export function parseTsLink(
+ url: string,
+ currentPageHref?: string,
+): TsLinkParsed {
+ let decodedURI = url;
+ try {
+ decodedURI = decodeURI(url);
+ } catch {
+ // leave as-is if the URI is malformed
+ }
+
+ const cmdOpenRaw = readParam('cmdopen', url);
+ const lidRaw = readParam('tslid', url);
+ const dPathRaw = readParam('tsdpath', url);
+ const ePathRaw = readParam('tsepath', url);
+ const idRaw = readParam('tseid', url);
+
+ if (cmdOpenRaw) {
+ return {
+ kind: 'cmd',
+ decodedURI,
+ lid: lidRaw || undefined,
+ cmdOpen: safeDecode(cmdOpenRaw),
+ id: idRaw || undefined,
+ };
+ }
+
+ if (lidRaw) {
+ return {
+ kind: 'ts',
+ decodedURI,
+ lid: safeDecode(lidRaw),
+ dPath: safeDecode(dPathRaw),
+ ePath: safeDecode(ePathRaw),
+ id: idRaw || undefined,
+ };
+ }
+
+ if (currentPageHref && decodedURI === currentPageHref) {
+ return { kind: 'self', decodedURI };
+ }
+
+ if (EXTERNAL_PROTOCOLS.some((p) => decodedURI.startsWith(p))) {
+ return { kind: 'external', decodedURI };
+ }
+
+ if (isRelativeLink(decodedURI)) {
+ return { kind: 'relative', decodedURI };
+ }
+
+ return { kind: 'unsupported', decodedURI };
+}
+
+export function resolveRelativePath(
+ baseDir: string,
+ relLink: string,
+ sep: string,
+): string {
+ const relPath = relLink
+ .replace(/^\.[\/\\]/, '')
+ .split(/[\/\\]/)
+ .filter((p) => p.length > 0)
+ .join(sep);
+ return joinPaths(sep, baseDir, relPath);
+}
diff --git a/tests/unit/tsLink.test.js b/tests/unit/tsLink.test.js
new file mode 100644
index 000000000..0cf149db2
--- /dev/null
+++ b/tests/unit/tsLink.test.js
@@ -0,0 +1,270 @@
+import {
+ isPathEscape,
+ isRelativeLink,
+ parseTsLink,
+ resolveRelativePath,
+} from '-/utils/tsLink';
+import { describe, expect, test } from '@playwright/test';
+
+describe('tsLink', () => {
+ describe('isPathEscape', () => {
+ test('rejects ../ traversal', () => {
+ expect(isPathEscape('../foo/bar.md')).toBe(true);
+ });
+
+ test('rejects embedded ../ traversal', () => {
+ expect(isPathEscape('a/../b.md')).toBe(true);
+ });
+
+ test('rejects Windows ..\\ traversal', () => {
+ expect(isPathEscape('..\\foo\\bar.md')).toBe(true);
+ });
+
+ test('rejects embedded ..\\ traversal', () => {
+ expect(isPathEscape('a\\..\\b.md')).toBe(true);
+ });
+
+ test('allows filename that contains ..', () => {
+ expect(isPathEscape('file..md')).toBe(false);
+ });
+
+ test('allows filename with two dots not forming traversal', () => {
+ expect(isPathEscape('foo/ba..r/baz.md')).toBe(false);
+ });
+
+ test('allows normal paths', () => {
+ expect(isPathEscape('foo/bar.md')).toBe(false);
+ expect(isPathEscape('./foo.md')).toBe(false);
+ });
+
+ test('handles null/empty input', () => {
+ expect(isPathEscape(null)).toBe(false);
+ expect(isPathEscape(undefined)).toBe(false);
+ expect(isPathEscape('')).toBe(false);
+ });
+ });
+
+ describe('isRelativeLink', () => {
+ test('true for bare filename', () => {
+ expect(isRelativeLink('foo.md')).toBe(true);
+ });
+
+ test('true for ./foo', () => {
+ expect(isRelativeLink('./foo.md')).toBe(true);
+ });
+
+ test('true for nested relative path', () => {
+ expect(isRelativeLink('sub/folder/file.md')).toBe(true);
+ });
+
+ test('false for absolute unix path', () => {
+ expect(isRelativeLink('/abs/path')).toBe(false);
+ });
+
+ test('false for absolute windows path', () => {
+ expect(isRelativeLink('\\abs\\path')).toBe(false);
+ });
+
+ test('false for anchor', () => {
+ expect(isRelativeLink('#section')).toBe(false);
+ });
+
+ test('false for query-only', () => {
+ expect(isRelativeLink('?foo=1')).toBe(false);
+ });
+
+ test('false for http(s)', () => {
+ expect(isRelativeLink('http://example.com')).toBe(false);
+ expect(isRelativeLink('https://example.com')).toBe(false);
+ });
+
+ test('false for ts:// protocol', () => {
+ expect(isRelativeLink('ts://?tslid=abc')).toBe(false);
+ });
+
+ test('false for mailto/tel/onenote', () => {
+ expect(isRelativeLink('mailto:[email protected]')).toBe(false);
+ expect(isRelativeLink('tel:+1234')).toBe(false);
+ expect(isRelativeLink('onenote:foo')).toBe(false);
+ });
+
+ test('false for windows drive letter', () => {
+ expect(isRelativeLink('C:\\foo')).toBe(false);
+ });
+
+ test('false for empty', () => {
+ expect(isRelativeLink('')).toBe(false);
+ });
+ });
+
+ describe('parseTsLink', () => {
+ test('classifies ts:// with tslid + tsepath as ts', () => {
+ const r = parseTsLink(
+ 'ts://?tslid=japan-trip-demo&tsepath=itinerary%5Bplanning%20schedule%20japan%5D.md',
+ );
+ expect(r.kind).toBe('ts');
+ expect(r.lid).toBe('japan-trip-demo');
+ expect(r.ePath).toBe('itinerary[planning schedule japan].md');
+ expect(r.dPath).toBeUndefined();
+ });
+
+ test('classifies ts:// with tslid + tsdpath as ts', () => {
+ const r = parseTsLink(
+ 'ts://?tslid=japan-trip-demo&tsdpath=tasks',
+ );
+ expect(r.kind).toBe('ts');
+ expect(r.lid).toBe('japan-trip-demo');
+ expect(r.dPath).toBe('tasks');
+ expect(r.ePath).toBeUndefined();
+ });
+
+ test('decodes URL-encoded path segments in tsepath', () => {
+ const r = parseTsLink(
+ 'ts://?tslid=demo&tsepath=tasks%2FIn%20Progress%2Fbuy-jr-pass%5Binprogress%20transport%5D.md',
+ );
+ expect(r.ePath).toBe(
+ 'tasks/In Progress/buy-jr-pass[inprogress transport].md',
+ );
+ });
+
+ test('captures tseid for moved-entry fallback', () => {
+ const r = parseTsLink(
+ 'ts://?tslid=demo&tsepath=foo.md&tseid=abc-123',
+ );
+ expect(r.kind).toBe('ts');
+ expect(r.id).toBe('abc-123');
+ });
+
+ test('classifies cmdopen as cmd', () => {
+ const r = parseTsLink(
+ 'ts://?cmdopen=%2Fsome%2Fabsolute%2Fpath.md',
+ );
+ expect(r.kind).toBe('cmd');
+ expect(r.cmdOpen).toBe('/some/absolute/path.md');
+ });
+
+ test('cmdopen with tslid still classifies as cmd', () => {
+ const r = parseTsLink(
+ 'ts://?tslid=demo&cmdopen=%2Fabs%2Fpath',
+ );
+ expect(r.kind).toBe('cmd');
+ expect(r.lid).toBe('demo');
+ expect(r.cmdOpen).toBe('/abs/path');
+ });
+
+ test('classifies http(s) as external', () => {
+ expect(parseTsLink('http://example.com').kind).toBe('external');
+ expect(parseTsLink('https://example.com/x').kind).toBe('external');
+ });
+
+ test('classifies mailto/tel/onenote/file as external', () => {
+ expect(parseTsLink('mailto:[email protected]').kind).toBe('external');
+ expect(parseTsLink('tel:+1234').kind).toBe('external');
+ expect(parseTsLink('onenote:foo').kind).toBe('external');
+ expect(parseTsLink('file:///tmp/x').kind).toBe('external');
+ });
+
+ test('classifies bare relative path as relative', () => {
+ expect(parseTsLink('foo/bar.md').kind).toBe('relative');
+ expect(parseTsLink('./foo.md').kind).toBe('relative');
+ });
+
+ test('classifies current page URL as self when currentPageHref matches', () => {
+ const href = 'http://localhost:3000/app/';
+ const r = parseTsLink(href, href);
+ expect(r.kind).toBe('self');
+ });
+
+ test('does not mark as self when currentPageHref does not match', () => {
+ const r = parseTsLink('http://localhost:3000/other', 'http://localhost:3000/app/');
+ expect(r.kind).toBe('external');
+ });
+
+ test('classifies absolute path as unsupported', () => {
+ expect(parseTsLink('/abs/path').kind).toBe('unsupported');
+ });
+
+ test('classifies anchor as unsupported', () => {
+ expect(parseTsLink('#section').kind).toBe('unsupported');
+ });
+
+ test('handles malformed URL gracefully (no throw)', () => {
+ const r = parseTsLink('ts://not a valid url');
+ expect(r.kind).toBeDefined();
+ });
+
+ test('strips trailing backslash from params (milkdown workaround)', () => {
+ const r = parseTsLink('ts://?tslid=demo&tsepath=foo.md\\');
+ expect(r.ePath).toBe('foo.md');
+ });
+ });
+
+ describe('parseTsLink regression — japan-trip demo links', () => {
+ const cases = [
+ {
+ url: 'ts://?tslid=japan-trip-demo&tsepath=tokyo%2Fday1-arrival-shibuya%5Btokyo%20day1%20sightseeing%5D.md',
+ ePath: 'tokyo/day1-arrival-shibuya[tokyo day1 sightseeing].md',
+ },
+ {
+ url: 'ts://?tslid=japan-trip-demo&tsepath=restaurants%2Fsukiyabashi-jiro%5Bsushi%20tokyo%20food%20splurge%5D.md',
+ ePath: 'restaurants/sukiyabashi-jiro[sushi tokyo food splurge].md',
+ },
+ {
+ url: 'ts://?tslid=japan-trip-demo&tsepath=tasks%2FIn%20Progress%2Freserve-hotels%5Binprogress%20booking%5D.md',
+ ePath: 'tasks/In Progress/reserve-hotels[inprogress booking].md',
+ },
+ {
+ url: 'ts://?tslid=japan-trip-demo&tsdpath=tasks',
+ dPath: 'tasks',
+ },
+ ];
+
+ for (const c of cases) {
+ test(`parses ${c.url.slice(0, 60)}...`, () => {
+ const r = parseTsLink(c.url);
+ expect(r.kind).toBe('ts');
+ expect(r.lid).toBe('japan-trip-demo');
+ if (c.ePath) expect(r.ePath).toBe(c.ePath);
+ if (c.dPath) expect(r.dPath).toBe(c.dPath);
+ });
+ }
+ });
+
+ describe('resolveRelativePath', () => {
+ test('resolves ./file against unix base dir', () => {
+ expect(resolveRelativePath('/home/user/notes', './foo.md', '/')).toBe(
+ '/home/user/notes/foo.md',
+ );
+ });
+
+ test('resolves bare filename against unix base dir', () => {
+ expect(resolveRelativePath('/home/user/notes', 'foo.md', '/')).toBe(
+ '/home/user/notes/foo.md',
+ );
+ });
+
+ test('resolves nested relative path against unix base dir', () => {
+ expect(
+ resolveRelativePath('/home/user/notes', 'sub/a/b.md', '/'),
+ ).toBe('/home/user/notes/sub/a/b.md');
+ });
+
+ test('normalizes mixed separators in relative link to target sep', () => {
+ // joinPaths always prepends the separator to the first segment unless
+ // the segment already starts with it — leading '\' is expected here.
+ expect(
+ resolveRelativePath('\\home\\user\\notes', 'sub/a/b.md', '\\'),
+ ).toBe('\\home\\user\\notes\\sub\\a\\b.md');
+ });
+
+ test('strips leading ./ or .\\ from the relative link', () => {
+ expect(
+ resolveRelativePath('/home/user/notes', '.\\foo.md', '/'),
+ ).toBe('/home/user/notes/foo.md');
+ });
+
+ test('filters out empty segments from double slashes', () => {
+ expect(resolveRelativePath('/a/b', 'c//d.md', '/')).toBe('/a/b/c/d.md');
+ });
+ });
+});