├── .npmrc ├── .eslintignore ├── babel.config.js ├── styles.css ├── versions.json ├── .editorconfig ├── manifest.json ├── .gitignore ├── release.sh ├── tsconfig.json ├── .github └── dependabot.yml ├── .eslintrc ├── version-bump.mjs ├── lib ├── path.ts └── path.test.ts ├── package.json ├── LICENSE ├── README_zh.md ├── esbuild.config.mjs ├── README.md ├── main.ts └── jest.config.js /.npmrc: -------------------------------------------------------------------------------- 1 | tag-version-prefix="" -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | npm node_modules 2 | build -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ['@babel/preset-env', { targets: { node: 'current' } }], 4 | '@babel/preset-typescript', 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This CSS file will be included with your plugin, and 4 | available in the app when your plugin is enabled. 5 | 6 | If your plugin does not need CSS, delete this file. 7 | 8 | */ 9 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "1.0.0": "0.15.0", 3 | "1.0.3": "0.15.0", 4 | "2.0.0": "0.15.0", 5 | "2.0.1": "0.15.0", 6 | "2.1.0": "0.15.0", 7 | "2.1.1": "0.15.0", 8 | "2.1.2": "0.15.0", 9 | "2.1.3": "0.15.0" 10 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = tab 9 | indent_size = 4 10 | tab_width = 4 11 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "update-relative-links", 3 | "name": "Update Relative Links", 4 | "version": "2.1.4", 5 | "minAppVersion": "0.15.0", 6 | "description": "Update relative links.", 7 | "author": "val", 8 | "authorUrl": "https://github.com/val3344/obsidian-update-relative-links", 9 | "isDesktopOnly": false 10 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vscode 2 | .vscode 3 | 4 | # Intellij 5 | *.iml 6 | .idea 7 | 8 | # npm 9 | node_modules 10 | 11 | # Don't include the compiled main.js file in the repo. 12 | # They should be uploaded to GitHub releases instead. 13 | main.js 14 | 15 | # Exclude sourcemaps 16 | *.map 17 | 18 | # obsidian 19 | data.json 20 | 21 | # Exclude macOS Finder (System Explorer) View States 22 | .DS_Store 23 | 24 | /output/ 25 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | OUTPUT_DIR="output" 4 | PLUGIN_NAME="update-relative-links" 5 | 6 | cd "$(dirname "$0")" 7 | 8 | npm run build 9 | 10 | if [ -d "$OUTPUT_DIR" ] 11 | then 12 | rm -r "$OUTPUT_DIR" 13 | fi 14 | 15 | mkdir "$OUTPUT_DIR" 16 | mkdir "$OUTPUT_DIR/$PLUGIN_NAME" 17 | 18 | cp main.js manifest.json "$OUTPUT_DIR/$PLUGIN_NAME" 19 | 20 | cd "$OUTPUT_DIR" 21 | 22 | cp "$PLUGIN_NAME/"* . 23 | 24 | zip -r "${PLUGIN_NAME}.zip" "$PLUGIN_NAME" 25 | rm -r "$PLUGIN_NAME" 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "inlineSourceMap": true, 5 | "inlineSources": true, 6 | "module": "ESNext", 7 | "target": "ES6", 8 | "allowJs": true, 9 | "noImplicitAny": true, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "isolatedModules": true, 13 | "strictNullChecks": true, 14 | "lib": [ 15 | "DOM", 16 | "ES5", 17 | "ES6", 18 | "ES7" 19 | ] 20 | }, 21 | "include": [ 22 | "**/*.ts" 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "env": { "node": true }, 5 | "plugins": [ 6 | "@typescript-eslint" 7 | ], 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/eslint-recommended", 11 | "plugin:@typescript-eslint/recommended" 12 | ], 13 | "parserOptions": { 14 | "sourceType": "module" 15 | }, 16 | "rules": { 17 | "no-unused-vars": "off", 18 | "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], 19 | "@typescript-eslint/ban-ts-comment": "off", 20 | "no-prototype-builtins": "off", 21 | "@typescript-eslint/no-empty-function": "off" 22 | } 23 | } -------------------------------------------------------------------------------- /version-bump.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from "fs"; 2 | 3 | const targetVersion = process.env.npm_package_version; 4 | 5 | // read minAppVersion from manifest.json and bump version to target version 6 | const manifest = JSON.parse(readFileSync("manifest.json", "utf8")); 7 | const { minAppVersion } = manifest; 8 | manifest.version = targetVersion; 9 | writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t")); 10 | 11 | // update versions.json with target version and minAppVersion from manifest.json 12 | // but only if the target version is not already in versions.json 13 | const versions = JSON.parse(readFileSync('versions.json', 'utf8')); 14 | if (!Object.values(versions).includes(minAppVersion)) { 15 | versions[targetVersion] = minAppVersion; 16 | writeFileSync('versions.json', JSON.stringify(versions, null, '\t')); 17 | } 18 | -------------------------------------------------------------------------------- /lib/path.ts: -------------------------------------------------------------------------------- 1 | const SEP = '/'; 2 | 3 | function dirname(path: string): string { 4 | return stackToPath(pathToStack(path).slice(0, -1)); 5 | } 6 | 7 | function relative(from: string, to: string): string { 8 | if (!from) { 9 | return to; 10 | } 11 | 12 | const fromStack = pathToStack(from); 13 | const toStack = pathToStack(to); 14 | 15 | const firstDiffIdx = fromStack.findIndex((value, idx) => value != toStack[idx]); 16 | 17 | const resultStack: string[] = []; 18 | 19 | for (let i = firstDiffIdx; i < fromStack.length - 1; i++) { 20 | resultStack.push('..'); 21 | } 22 | 23 | for (let i = firstDiffIdx; i < toStack.length; i++) { 24 | resultStack.push(toStack[i]); 25 | } 26 | 27 | return stackToPath(resultStack); 28 | } 29 | 30 | function pathToStack(path: string): string[] { 31 | return path.split(SEP); 32 | } 33 | 34 | function stackToPath(stack: string[]): string { 35 | return stack.join(SEP); 36 | } 37 | 38 | export { dirname, relative } 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "obsidian-sample-plugin", 3 | "version": "2.1.4", 4 | "description": "This is a sample plugin for Obsidian (https://obsidian.md)", 5 | "main": "main.js", 6 | "scripts": { 7 | "dev": "node esbuild.config.mjs", 8 | "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", 9 | "version": "node version-bump.mjs && git add manifest.json versions.json", 10 | "test": "jest" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "MIT", 15 | "devDependencies": { 16 | "@babel/core": "^7.19.3", 17 | "@babel/preset-env": "^7.19.4", 18 | "@babel/preset-typescript": "^7.18.6", 19 | "@types/jest": "^30.0.0", 20 | "@types/node": "^25.0.2", 21 | "@typescript-eslint/eslint-plugin": "^8.46.1", 22 | "@typescript-eslint/parser": "^8.46.1", 23 | "babel-jest": "^30.2.0", 24 | "builtin-modules": "^5.0.0", 25 | "esbuild": "^0.27.0", 26 | "jest": "^30.2.0", 27 | "obsidian": "latest", 28 | "ts-jest": "^29.0.3", 29 | "tslib": "^2.4.0", 30 | "typescript": "^5.9.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 val3344 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | # 自动更新相对路径 2 | 3 | ## 插件作用 4 | 5 | Obsidian 的 “Automatically update internal links” 选项实现的有问题。文件移动后,只会自动更新指向这个文件的链接,不会更新这个文件内指向其他文件的链接。这个插件就是用来解决这个问题的。另外还提供了一个批量修正所有已经存在的链接的命令。 6 | 7 | 例如有两个文件如下: 8 | 9 | `dirA/fileA`: 10 | 11 | ```markdown 12 | [fileB](../dirB/fileB.md) 13 | ``` 14 | 15 | `dirB/fileB`: 16 | 17 | ```markdown 18 | [fileA](../dirA/fileA.md) 19 | ``` 20 | 21 | 将 `fileA` 从 `dirA` 移动到 `dirB` 后: 22 | 23 | `dirB/fileA`: 24 | 25 | ```markdown 26 | [fileB](../dirB/fileB.md) 27 | ``` 28 | 29 | `dirB/fileB`: 30 | 31 | ```markdown 32 | [fileA](fileA.md) 33 | ``` 34 | 35 | 这个插件的作用,就是将 `dirB/fileA` 中的 `[fileB](../dirB/fileB.md)` 修复成 `[fileB](fileB.md)`。 36 | 37 | ## 使用方法 38 | 39 | 插件包含两个功能: 40 | 41 | 第一个功能:文件移动后,自动修复链接的相对路径。安装并启用插件后,移动文件会自动触发,无需其他操作。 42 | 43 | 第二个功能:批量将所有文件中的链接修复为相对路径。打开命令面板(默认快捷键是 `Ctrl + P`),搜索“Update all relative links”,回车执行。 44 | 45 | ## 插件限制 46 | 47 | 必须关闭 `Use [[Wikilinks]]` 选项,使用 Markdown 的链接语法。使用相对路径的意义也是为了让笔记更通用,如果还使用 Wiki Links,就没必要使用相对路径了。 48 | 49 | ## 为什么使用相对路径 50 | 51 | Obsidian 的一大优势就是笔记完全由 Markdown 文件组成,不用担心迁移的问题。使用相对路径,可以使笔记有更好的通用性。例如使用其他 Markdown 编辑器查看、编辑笔记。如果使用 Git 同步笔记,还可以在网页上直接查看笔记。如果不使用相对路径,笔记中的链接,将只能在 Obsidian 中被识别。 52 | -------------------------------------------------------------------------------- /esbuild.config.mjs: -------------------------------------------------------------------------------- 1 | import esbuild from "esbuild"; 2 | import process from "process"; 3 | import builtins from "builtin-modules"; 4 | 5 | const banner = 6 | `/* 7 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD 8 | if you want to view the source, please visit the github repository of this plugin 9 | */ 10 | `; 11 | 12 | const prod = (process.argv[2] === "production"); 13 | 14 | const context = await esbuild.context({ 15 | banner: { 16 | js: banner, 17 | }, 18 | entryPoints: ["main.ts"], 19 | bundle: true, 20 | external: [ 21 | "obsidian", 22 | "electron", 23 | "@codemirror/autocomplete", 24 | "@codemirror/collab", 25 | "@codemirror/commands", 26 | "@codemirror/language", 27 | "@codemirror/lint", 28 | "@codemirror/search", 29 | "@codemirror/state", 30 | "@codemirror/view", 31 | "@lezer/common", 32 | "@lezer/highlight", 33 | "@lezer/lr", 34 | ...builtins], 35 | format: "cjs", 36 | target: "es2018", 37 | logLevel: "info", 38 | sourcemap: prod ? false : "inline", 39 | treeShaking: true, 40 | outfile: "main.js", 41 | minify: prod, 42 | }); 43 | 44 | if (prod) { 45 | await context.rebuild(); 46 | process.exit(0); 47 | } else { 48 | await context.watch(); 49 | } 50 | -------------------------------------------------------------------------------- /lib/path.test.ts: -------------------------------------------------------------------------------- 1 | import { dirname, relative } from './path'; 2 | 3 | describe('dirname', () => { 4 | it('should return dirname', () => { 5 | expect(dirname('dirname/filename.md')).toBe('dirname'); 6 | }); 7 | 8 | it('should return empty when no dirname', () => { 9 | expect(dirname('filename.md')).toBe(''); 10 | }); 11 | 12 | it('should return dirname when no filename', () => { 13 | expect(dirname('dirname/')).toBe('dirname'); 14 | }); 15 | }); 16 | 17 | describe('relative', () => { 18 | it('should return relative path', () => { 19 | expect(relative('a/b/c.md', 'a/d/e.md')).toBe('../d/e.md'); 20 | }); 21 | 22 | it('should return relative path when in same directory', () => { 23 | expect(relative('a/b.md', 'a/c.md')).toBe('c.md'); 24 | }); 25 | 26 | it('should return relative path when from no directory', () => { 27 | expect(relative('a.md', 'b/c.md')).toBe('b/c.md'); 28 | }); 29 | 30 | it('should return relative path when to no directory', () => { 31 | expect(relative('a/b.md', 'c.md')).toBe('../c.md'); 32 | }); 33 | 34 | it('should return relative path when from no directory to no directory', () => { 35 | expect(relative('a.md', 'b.md')).toBe('b.md'); 36 | }); 37 | 38 | it('should return relative path when from directory', () => { 39 | expect(relative('a/', 'b/c.md')).toBe('../b/c.md'); 40 | }); 41 | 42 | it('should return relative path when to directory', () => { 43 | expect(relative('a/b.md', 'c/')).toBe('../c/'); 44 | }); 45 | 46 | it('should return relative path when from directory to directory', () => { 47 | expect(relative('a/b/', 'c/')).toBe('../../c/'); 48 | }); 49 | 50 | it('should return relative path when from empty', () => { 51 | expect(relative('', 'a/b.md')).toBe('a/b.md'); 52 | }); 53 | 54 | it('should return relative path when to empty', () => { 55 | expect(relative('a/b.md', '')).toBe('../'); 56 | }); 57 | 58 | it('should return relative path when from empty to empty', () => { 59 | expect(relative('', '')).toBe(''); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Update Relative Links 2 | 3 | [中文](./README_zh.md) 4 | 5 | ## Plugin function 6 | 7 | Obsidian's implementation of the "Automatically update internal links" option is buggy. After the file is moved, only the links to this file will be automatically updated, and the links to other files in this file will not be updated. This plugin is used to solve this problem. There is also a command to batch fix all existing links. 8 | 9 | For example, there are two files as follows: 10 | 11 | `dirA/fileA`: 12 | 13 | ````markdown 14 | [fileB](../dirB/fileB.md) 15 | ```` 16 | 17 | `dirB/fileB`: 18 | 19 | ````markdown 20 | [fileA](../dirA/fileA.md) 21 | ```` 22 | 23 | After moving `fileA` from `dirA` to `dirB`: 24 | 25 | `dirB/fileA`: 26 | 27 | ````markdown 28 | [fileB](../dirB/fileB.md) 29 | ```` 30 | 31 | `dirB/fileB`: 32 | 33 | ````markdown 34 | [fileA](fileA.md) 35 | ```` 36 | 37 | The function of this plugin is to fix `[fileB](../dirB/fileB.md)` in `dirB/fileA` to `[fileB](fileB.md)`. 38 | 39 | ## Instructions 40 | 41 | The plugin contains two functions: 42 | 43 | The first function: After the file is moved, the relative path of the link is automatically fixed. Once the plugin is installed and enabled, moving files is triggered automatically, no further action is required. 44 | 45 | The second function: batch fix links in all files to relative paths. Open the command palette (the default shortcut is `Ctrl + P`), search for "Update all relative links", and press Enter to execute. 46 | 47 | ## Plugin restrictions 48 | 49 | The `Use [[Wikilinks]]` option must be turned off to use Markdown's link syntax. The point of using relative paths is also to make notes more generic, and if you are also using Wiki Links, there is no need to use relative paths. 50 | 51 | ## Why use relative paths 52 | 53 | One of the great advantages of Obsidian is that the notes are composed entirely of Markdown files, so there is no need to worry about migration. Use relative paths to make notes more versatile. For example, use other Markdown editors to view and edit notes. If you sync your notes with Git, you can also view your notes directly on the web. If you don't use relative paths, links in notes will only be recognized in Obsidian. 54 | -------------------------------------------------------------------------------- /main.ts: -------------------------------------------------------------------------------- 1 | import { App, Modal, Notice, Plugin, Setting, TFile } from 'obsidian'; 2 | import { dirname, relative } from './lib/path'; 3 | 4 | class ConfirmModal extends Modal { 5 | content: string; 6 | onConfirm: () => void; 7 | 8 | constructor(app: App, content: string, onConfirm: () => void) { 9 | super(app); 10 | 11 | this.content = content; 12 | this.onConfirm = onConfirm; 13 | } 14 | 15 | onOpen() { 16 | const { contentEl } = this; 17 | 18 | contentEl.createEl('h1', { text: 'Update Releate Links Plugin' }); 19 | contentEl.createEl('p', { text: this.content }); 20 | 21 | new Setting(contentEl) 22 | .addButton((btn) => btn 23 | .setButtonText('Yes') 24 | .setCta() 25 | .onClick(() => { 26 | this.close(); 27 | this.onConfirm(); 28 | })) 29 | .addButton((btn) => btn 30 | .setButtonText('No') 31 | .onClick(() => { 32 | this.close(); 33 | })); 34 | } 35 | 36 | onClose() { 37 | this.contentEl.empty(); 38 | } 39 | } 40 | 41 | export default class UpdateRelativeLinksPlugin extends Plugin { 42 | async onload() { 43 | const { app } = this; 44 | const { metadataCache, vault } = app; 45 | 46 | const message = 'This command will modify all links in the entire vault (not just the current file) to relative paths,' 47 | + ' and this action cannot be undone.' 48 | + ' It is recommended that you back up the vault in advance.' 49 | + ' Please confirm whether you want to execute the command.'; 50 | 51 | this.addCommand({ 52 | id: 'update-all-relative-links', 53 | name: 'Update all relative links', 54 | callback() { 55 | new ConfirmModal(app, message, () => { 56 | const promises = vault.getMarkdownFiles().map(file => replace(file, false)); 57 | 58 | Promise.all(promises).then(linkCounts => { 59 | const updatedLinkCounts = linkCounts.filter(count => count > 0); 60 | 61 | const linkCount = updatedLinkCounts.reduce((sum, count) => sum + count, 0); 62 | const fileCount = updatedLinkCounts.length; 63 | 64 | new Notice(`Update ${linkCount} links in ${fileCount} file${fileCount > 1 ? 's' : ''}.`); 65 | }).catch(err => { 66 | new Notice('Update links error, see console.'); 67 | console.error(err); 68 | }); 69 | }).open(); 70 | } 71 | }); 72 | 73 | this.registerEvent(vault.on('rename', (file, oldPath) => { 74 | if (!oldPath 75 | || !file.path.toLocaleLowerCase().endsWith('.md') 76 | || file.parent?.path === dirname(oldPath)) { 77 | return; 78 | } 79 | 80 | if (file instanceof TFile) { 81 | setTimeout(() => replace(file, true), 100); 82 | } 83 | })); 84 | 85 | async function replace(file: TFile, notice: boolean) { 86 | const metadata = metadataCache.getFileCache(file); 87 | const links = [...(metadata?.links ?? []), ...(metadata?.embeds ?? [])]; 88 | const replacePairs = links.map(({ link, original }) => { 89 | const linkPath = link.replace(/#.*$/, ''); 90 | 91 | if (!linkPath) { 92 | return null; 93 | } 94 | 95 | const linkFile = metadataCache.getFirstLinkpathDest(linkPath, file.path); 96 | 97 | if (!linkFile) { 98 | return null; 99 | } 100 | 101 | const newLinkPath = file.parent?.path === '/' ? linkFile.path : relative(file.path, linkFile.path); 102 | 103 | if (linkPath === newLinkPath) { 104 | return null; 105 | } 106 | 107 | const newOriginal = replaceOriginal(original, linkPath, newLinkPath); 108 | return [original, newOriginal]; 109 | }).filter(pair => pair); 110 | 111 | if (!replacePairs?.length) { 112 | return 0; 113 | } 114 | 115 | try { 116 | const content = await vault.read(file); 117 | 118 | const replacedContent = replacePairs.reduce((tmpContent, pair) => { 119 | return pair?.length === 2 ? tmpContent.replace(pair[0], pair[1]) : tmpContent; 120 | }, content); 121 | 122 | await vault.modify(file, replacedContent); 123 | 124 | const msg = `Update ${replacePairs.length} links in ${file.path}.`; 125 | console.log(msg); 126 | if (notice) { 127 | new Notice(msg); 128 | } 129 | return replacePairs.length; 130 | } catch (e) { 131 | console.error(e); 132 | if (notice) { 133 | new Notice('Update links error, see console.'); 134 | } 135 | throw e; 136 | } 137 | } 138 | 139 | function replaceOriginal(original: string, link: string, newLink: string) { 140 | let newOriginal = replaceWithFormat(original, link, newLink, s => s.replace(/ /g, '%20')); 141 | if (original === newOriginal) { 142 | newOriginal = replaceWithFormat(original, link, newLink, encodeURI); 143 | } 144 | if (original === newOriginal) { 145 | newOriginal = original.replace(/^(!?\[.*?\]).*$/, `$1(${encodeURI(newLink)})`) 146 | } 147 | return newOriginal; 148 | } 149 | 150 | function replaceWithFormat(str: string, from: string, to: string, format: (s: string) => string) { 151 | return str.replace(format(from), format(to)); 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * For a detailed explanation regarding each configuration property, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | module.exports = { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // The directory where Jest should store its cached dependency information 14 | // cacheDirectory: "/tmp/jest_rs", 15 | 16 | // Automatically clear mock calls, instances, contexts and results before every test 17 | // clearMocks: false, 18 | 19 | // Indicates whether the coverage information should be collected while executing the test 20 | // collectCoverage: false, 21 | 22 | // An array of glob patterns indicating a set of files for which coverage information should be collected 23 | // collectCoverageFrom: undefined, 24 | 25 | // The directory where Jest should output its coverage files 26 | // coverageDirectory: undefined, 27 | 28 | // An array of regexp pattern strings used to skip coverage collection 29 | // coveragePathIgnorePatterns: [ 30 | // "/node_modules/" 31 | // ], 32 | 33 | // Indicates which provider should be used to instrument code for coverage 34 | coverageProvider: "v8", 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // The default configuration for fake timers 54 | // fakeTimers: { 55 | // "enableGlobally": false 56 | // }, 57 | 58 | // Force coverage collection from ignored files using an array of glob patterns 59 | // forceCoverageMatch: [], 60 | 61 | // A path to a module which exports an async function that is triggered once before all test suites 62 | // globalSetup: undefined, 63 | 64 | // A path to a module which exports an async function that is triggered once after all test suites 65 | // globalTeardown: undefined, 66 | 67 | // A set of global variables that need to be available in all test environments 68 | // globals: {}, 69 | 70 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 71 | // maxWorkers: "50%", 72 | 73 | // An array of directory names to be searched recursively up from the requiring module's location 74 | // moduleDirectories: [ 75 | // "node_modules" 76 | // ], 77 | 78 | // An array of file extensions your modules use 79 | // moduleFileExtensions: [ 80 | // "js", 81 | // "mjs", 82 | // "cjs", 83 | // "jsx", 84 | // "ts", 85 | // "tsx", 86 | // "json", 87 | // "node" 88 | // ], 89 | 90 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 91 | // moduleNameMapper: {}, 92 | 93 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 94 | // modulePathIgnorePatterns: [], 95 | 96 | // Activates notifications for test results 97 | // notify: false, 98 | 99 | // An enum that specifies notification mode. Requires { notify: true } 100 | // notifyMode: "failure-change", 101 | 102 | // A preset that is used as a base for Jest's configuration 103 | // preset: undefined, 104 | 105 | // Run tests from one or more projects 106 | // projects: undefined, 107 | 108 | // Use this configuration option to add custom reporters to Jest 109 | // reporters: undefined, 110 | 111 | // Automatically reset mock state before every test 112 | // resetMocks: false, 113 | 114 | // Reset the module registry before running each individual test 115 | // resetModules: false, 116 | 117 | // A path to a custom resolver 118 | // resolver: undefined, 119 | 120 | // Automatically restore mock state and implementation before every test 121 | // restoreMocks: false, 122 | 123 | // The root directory that Jest should scan for tests and modules within 124 | // rootDir: undefined, 125 | 126 | // A list of paths to directories that Jest should use to search for files in 127 | // roots: [ 128 | // "" 129 | // ], 130 | 131 | // Allows you to use a custom runner instead of Jest's default test runner 132 | // runner: "jest-runner", 133 | 134 | // The paths to modules that run some code to configure or set up the testing environment before each test 135 | // setupFiles: [], 136 | 137 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 138 | // setupFilesAfterEnv: [], 139 | 140 | // The number of seconds after which a test is considered as slow and reported as such in the results. 141 | // slowTestThreshold: 5, 142 | 143 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 144 | // snapshotSerializers: [], 145 | 146 | // The test environment that will be used for testing 147 | // testEnvironment: "jest-environment-node", 148 | 149 | // Options that will be passed to the testEnvironment 150 | // testEnvironmentOptions: {}, 151 | 152 | // Adds a location field to test results 153 | // testLocationInResults: false, 154 | 155 | // The glob patterns Jest uses to detect test files 156 | // testMatch: [ 157 | // "**/__tests__/**/*.[jt]s?(x)", 158 | // "**/?(*.)+(spec|test).[tj]s?(x)" 159 | // ], 160 | 161 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 162 | // testPathIgnorePatterns: [ 163 | // "/node_modules/" 164 | // ], 165 | 166 | // The regexp pattern or array of patterns that Jest uses to detect test files 167 | // testRegex: [], 168 | 169 | // This option allows the use of a custom results processor 170 | // testResultsProcessor: undefined, 171 | 172 | // This option allows use of a custom test runner 173 | // testRunner: "jest-circus/runner", 174 | 175 | // A map from regular expressions to paths to transformers 176 | // transform: undefined, 177 | 178 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 179 | // transformIgnorePatterns: [ 180 | // "/node_modules/", 181 | // "\\.pnp\\.[^\\/]+$" 182 | // ], 183 | 184 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 185 | // unmockedModulePathPatterns: undefined, 186 | 187 | // Indicates whether each individual test should be reported during the run 188 | // verbose: undefined, 189 | 190 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 191 | // watchPathIgnorePatterns: [], 192 | 193 | // Whether to use watchman for file crawling 194 | // watchman: true, 195 | }; 196 | --------------------------------------------------------------------------------