@vx-oss/docs-twoslash 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Fuma
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.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Fumadocs Twoslash
2
+
3
+ Use Typescript Twoslash in Fumadocs.
@@ -0,0 +1,14 @@
1
+ import { TwoslashTypesCache } from "@shikijs/twoslash";
2
+ //#region src/cache-fs.d.ts
3
+ interface FileSystemTypeResultCacheOptions {
4
+ /**
5
+ * The directory to store the cache files.
6
+ *
7
+ * @default '.next/cache/twoslash'
8
+ */
9
+ dir?: string;
10
+ cwd?: string;
11
+ }
12
+ declare function createFileSystemTypesCache(options?: FileSystemTypeResultCacheOptions): TwoslashTypesCache;
13
+ //#endregion
14
+ export { FileSystemTypeResultCacheOptions, createFileSystemTypesCache };
@@ -0,0 +1,33 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import * as process from "node:process";
5
+ //#region src/cache-fs.ts
6
+ /**
7
+ * Original: https://github.com/shikijs/shiki/blob/main/packages/vitepress-twoslash/src/cache-fs.ts
8
+ */
9
+ function createFileSystemTypesCache(options = {}) {
10
+ const { cwd = process.cwd() } = options;
11
+ const dir = path.join(cwd, options.dir ?? ".next/cache/twoslash");
12
+ return {
13
+ init() {
14
+ try {
15
+ fs.mkdirSync(dir, { recursive: true });
16
+ } catch {}
17
+ },
18
+ read(code) {
19
+ const hash = createHash("SHA256").update(code).digest("hex").slice(0, 12);
20
+ const filePath = path.join(dir, `${hash}.json`);
21
+ if (!fs.existsSync(filePath)) return null;
22
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
23
+ },
24
+ write(code, data) {
25
+ const hash = createHash("SHA256").update(code).digest("hex").slice(0, 12);
26
+ const filePath = path.join(dir, `${hash}.json`);
27
+ const json = JSON.stringify(data);
28
+ fs.writeFileSync(filePath, json, "utf-8");
29
+ }
30
+ };
31
+ }
32
+ //#endregion
33
+ export { createFileSystemTypesCache };
@@ -0,0 +1,10 @@
1
+ import { TransformerTwoslashIndexOptions, TwoslashTypesCache } from "@shikijs/twoslash";
2
+ import { ShikiTransformer } from "shiki";
3
+ //#region src/index.d.ts
4
+ type TransformerTwoslashOptions = TransformerTwoslashIndexOptions;
5
+ /**
6
+ * This transformer **must** be used with the `rehype-code` plugin of Fumadocs.
7
+ */
8
+ declare function transformerTwoslash(_options?: TransformerTwoslashOptions): ShikiTransformer;
9
+ //#endregion
10
+ export { TransformerTwoslashOptions, type TwoslashTypesCache, transformerTwoslash };
package/dist/index.js ADDED
@@ -0,0 +1,120 @@
1
+ import { fromMarkdown } from "mdast-util-from-markdown";
2
+ import { gfmFromMarkdown } from "mdast-util-gfm";
3
+ import { defaultHandlers, toHast } from "mdast-util-to-hast";
4
+ import { ShikiError } from "shiki/core";
5
+ import { createTransformerFactory, rendererRich } from "@shikijs/twoslash";
6
+ import { createTwoslasher } from "twoslash";
7
+ //#region src/index.ts
8
+ let cachedInstance;
9
+ /**
10
+ * This transformer **must** be used with the `rehype-code` plugin of Fumadocs.
11
+ */
12
+ function transformerTwoslash(_options = {}) {
13
+ const ignoreClass = "nd-copy-ignore";
14
+ const { twoslashOptions = {}, rendererRich: rendererOptions, ...rest } = _options;
15
+ function lazyInstance() {
16
+ function get() {
17
+ return cachedInstance ??= createTwoslasher({
18
+ ...twoslashOptions,
19
+ compilerOptions: {
20
+ moduleResolution: 100,
21
+ baseUrl: void 0,
22
+ ...twoslashOptions.compilerOptions
23
+ }
24
+ });
25
+ }
26
+ const wrapper = (...args) => get()(...args);
27
+ wrapper.getCacheMap = () => get().getCacheMap();
28
+ return wrapper;
29
+ }
30
+ const renderer = rendererRich({
31
+ classExtra: ignoreClass,
32
+ queryRendering: "line",
33
+ renderMarkdown,
34
+ renderMarkdownInline,
35
+ ...rendererOptions,
36
+ hast: {
37
+ hoverToken: { tagName: "Popup" },
38
+ hoverPopup: {
39
+ tagName: "PopupContent",
40
+ properties: { class: ignoreClass }
41
+ },
42
+ hoverCompose: ({ popup, token }) => [popup, {
43
+ type: "element",
44
+ tagName: "PopupTrigger",
45
+ properties: {},
46
+ children: [token]
47
+ }],
48
+ popupDocs: { class: "prose twoslash-popup-docs" },
49
+ popupTypes: {
50
+ tagName: "div",
51
+ class: "twoslash shiki fd-codeblock prose-no-margin",
52
+ children: (v) => {
53
+ if (v.length === 1 && v[0].type === "element" && v[0].tagName === "pre") return v;
54
+ return [{
55
+ type: "element",
56
+ tagName: "code",
57
+ properties: { class: "twoslash-popup-code" },
58
+ children: v
59
+ }];
60
+ }
61
+ },
62
+ popupDocsTags: { class: "prose twoslash-popup-docs twoslash-popup-docs-tags" },
63
+ nodesHighlight: { class: "highlighted-word twoslash-highlighted" },
64
+ ...rendererOptions?.hast
65
+ }
66
+ });
67
+ const fn = renderer.lineQuery;
68
+ renderer.lineQuery = function(...args) {
69
+ const result = fn.call(this, ...args);
70
+ const child = result[0].children[0];
71
+ result[0].children[0] = {
72
+ type: "element",
73
+ tagName: "span",
74
+ children: [child]
75
+ };
76
+ return result;
77
+ };
78
+ return createTransformerFactory(lazyInstance(), renderer)({
79
+ explicitTrigger: true,
80
+ ...rest
81
+ });
82
+ }
83
+ function renderMarkdown(md) {
84
+ const mdast = fromMarkdown(md.replace(/{@link (?<link>[^}]*)}/g, "$1"), { mdastExtensions: [gfmFromMarkdown()] });
85
+ const onCode = (lang, node) => {
86
+ return this.codeToHast(node.value, {
87
+ ...this.options,
88
+ transformers: [],
89
+ meta: node.meta ? { __raw: node.meta } : {},
90
+ lang
91
+ }).children[0];
92
+ };
93
+ return toHast(mdast, { handlers: { code: (state, node) => {
94
+ const lang = node.lang;
95
+ if (!lang) return defaultHandlers.code(state, node);
96
+ try {
97
+ return onCode(lang, node);
98
+ } catch (e) {
99
+ const def = defaultHandlers.code(state, node);
100
+ if (e instanceof ShikiError) {
101
+ this.meta._fd_postprocess ??= [];
102
+ this.meta._fd_postprocess.push(async ({ highlighter }) => {
103
+ await highlighter.loadLanguage(lang);
104
+ Object.assign(def, onCode(lang, node));
105
+ });
106
+ return def;
107
+ }
108
+ if (e instanceof Error) console.error(`[@vx-oss/docs-twoslash] encountered an error when highlighting codeblock in a Twoslash popup: ${e.message}`);
109
+ return def;
110
+ }
111
+ } } }).children;
112
+ }
113
+ function renderMarkdownInline(md, context) {
114
+ const text = context === "tag:param" ? md.replace(/^(?<link>[\w$-]+)/, "`$1` ") : md;
115
+ const children = renderMarkdown.call(this, text);
116
+ if (children.length === 1 && children[0].type === "element" && children[0].tagName === "p") return children[0].children;
117
+ return children;
118
+ }
119
+ //#endregion
120
+ export { transformerTwoslash };
@@ -0,0 +1,11 @@
1
+ import { ComponentProps, ReactNode } from "react";
2
+ import { Popover } from "@base-ui/react/popover";
3
+ //#region src/ui/popup.d.ts
4
+ declare function Popup({ delay, children }: {
5
+ delay?: number;
6
+ children: ReactNode;
7
+ }): import("react").JSX.Element;
8
+ declare function PopupTrigger({ children, ...props }: ComponentProps<typeof Popover.Trigger>): import("react").JSX.Element;
9
+ declare function PopupContent({ className, side, align, sideOffset, ref, ...props }: React.ComponentProps<typeof Popover.Popup> & Pick<React.ComponentProps<typeof Popover.Positioner>, 'align' | 'side' | 'sideOffset'>): import("react").JSX.Element;
10
+ //#endregion
11
+ export { Popup, PopupContent, PopupTrigger };
@@ -0,0 +1,72 @@
1
+ "use client";
2
+ import { createContext, useContext, useMemo, useRef, useState } from "react";
3
+ import { Popover } from "@base-ui/react/popover";
4
+ import { cn } from "cnfast";
5
+ import { jsx } from "react/jsx-runtime";
6
+ //#region src/ui/popup.tsx
7
+ const PopupContext = createContext(void 0);
8
+ function Popup({ delay = 300, children }) {
9
+ const [open, setOpen] = useState(false);
10
+ const openTimeoutRef = useRef(void 0);
11
+ const closeTimeoutRef = useRef(void 0);
12
+ return /* @__PURE__ */ jsx(Popover.Root, {
13
+ open,
14
+ onOpenChange: setOpen,
15
+ children: /* @__PURE__ */ jsx(PopupContext.Provider, {
16
+ value: useMemo(() => ({
17
+ open,
18
+ setOpen,
19
+ handleOpen(e) {
20
+ if (e.pointerType === "touch") return;
21
+ if (closeTimeoutRef.current) clearTimeout(closeTimeoutRef.current);
22
+ openTimeoutRef.current = window.setTimeout(() => {
23
+ setOpen(true);
24
+ }, delay);
25
+ },
26
+ handleClose(e) {
27
+ if (e.pointerType === "touch") return;
28
+ if (openTimeoutRef.current) clearTimeout(openTimeoutRef.current);
29
+ closeTimeoutRef.current = window.setTimeout(() => {
30
+ setOpen(false);
31
+ }, delay);
32
+ }
33
+ }), [delay, open]),
34
+ children
35
+ })
36
+ });
37
+ }
38
+ function PopupTrigger({ children, ...props }) {
39
+ const ctx = useContext(PopupContext);
40
+ if (!ctx) throw new Error("Missing Popup Context");
41
+ return /* @__PURE__ */ jsx(Popover.Trigger, {
42
+ onPointerEnter: ctx.handleOpen,
43
+ onPointerLeave: ctx.handleClose,
44
+ render: (triggerProps) => /* @__PURE__ */ jsx("button", {
45
+ ...triggerProps,
46
+ type: "button",
47
+ className: cn("twoslash-hover", triggerProps.className),
48
+ children
49
+ }),
50
+ ...props
51
+ });
52
+ }
53
+ function PopupContent({ className, side = "bottom", align = "center", sideOffset = 4, ref, ...props }) {
54
+ const ctx = useContext(PopupContext);
55
+ if (!ctx) throw new Error("Missing Popup Context");
56
+ return /* @__PURE__ */ jsx(Popover.Portal, { children: /* @__PURE__ */ jsx(Popover.Positioner, {
57
+ side,
58
+ align,
59
+ sideOffset,
60
+ children: /* @__PURE__ */ jsx(Popover.Popup, {
61
+ ref,
62
+ className: cn("fd-twoslash-popover", className),
63
+ onPointerEnter: ctx.handleOpen,
64
+ onPointerLeave: ctx.handleClose,
65
+ initialFocus: false,
66
+ finalFocus: false,
67
+ ...props
68
+ })
69
+ }) });
70
+ }
71
+ //#endregion
72
+ export { Popup, PopupContent, PopupTrigger };
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "@vx-oss/docs-twoslash",
3
+ "version": "1.0.3",
4
+ "description": "Typescript Twoslash Integration for Fumadocs",
5
+ "keywords": [
6
+ "Docs",
7
+ "fumadocs"
8
+ ],
9
+ "homepage": "https://vezham.com",
10
+ "license": "MIT",
11
+ "author": "Fuma Nama",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/vezham/fumadocs",
15
+ "directory": "packages/twoslash"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "styles"
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ "./twoslash.css": "./styles/twoslash.css",
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./ui": {
31
+ "types": "./dist/ui/index.d.ts",
32
+ "import": "./dist/ui/index.js"
33
+ },
34
+ "./cache-fs": {
35
+ "types": "./dist/cache-fs.d.ts",
36
+ "import": "./dist/cache-fs.js"
37
+ }
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "dependencies": {
43
+ "@base-ui/react": "^1.7.0",
44
+ "@shikijs/twoslash": "^4.4.3",
45
+ "cnfast": "^0.1.0",
46
+ "mdast-util-from-markdown": "^2.0.3",
47
+ "mdast-util-gfm": "^3.1.0",
48
+ "mdast-util-to-hast": "^13.2.1",
49
+ "twoslash": "^0.3.9"
50
+ },
51
+ "devDependencies": {
52
+ "@types/hast": "^3.0.5",
53
+ "@types/mdast": "^4.0.4",
54
+ "@types/node": "26.3.0",
55
+ "@types/react": "^19.2.18",
56
+ "shiki": "4.4.3",
57
+ "tsdown": "0.22.14",
58
+ "typescript": "^6.0.3",
59
+ "@vx-oss/docs-react": "1.0.3",
60
+ "@vx-oss/docs-core": "1.0.3",
61
+ "tsconfig": "0.0.1"
62
+ },
63
+ "peerDependencies": {
64
+ "@types/react": "*",
65
+ "react": "^19.2.0",
66
+ "react-dom": "^19.2.0",
67
+ "shiki": "4.x.x",
68
+ "@vx-oss/docs-core": "^1.0.1",
69
+ "@vx-oss/docs-react": "^1.0.1"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "@types/react": {
73
+ "optional": true
74
+ }
75
+ },
76
+ "scripts": {
77
+ "build": "tsdown",
78
+ "clean": "rimraf dist",
79
+ "dev": "tsdown --watch",
80
+ "lint": "oxlint .",
81
+ "types:check": "tsc --noEmit"
82
+ }
83
+ }
@@ -0,0 +1,225 @@
1
+ /* ===== Basic ===== */
2
+ @theme {
3
+ --color-twoslash-error-foreground: #d45656;
4
+ --color-twoslash-error: #d4565620;
5
+ --color-twoslash-tag-foreground: #3772cf;
6
+ --color-twoslash-tag: #3772cf20;
7
+ --color-twoslash-tag-warn-foreground: #c37d0d;
8
+ --color-twoslash-tag-warn: #c37d0d20;
9
+ --color-twoslash-tag-annotate-foreground: #1ba673;
10
+ --color-twoslash-tag-annotate: #1ba67320;
11
+ }
12
+
13
+ .twoslash-meta-line {
14
+ display: flex;
15
+ }
16
+
17
+ .twoslash-completion-list,
18
+ .twoslash-popup-container {
19
+ position: relative;
20
+ user-select: none;
21
+ display: flex;
22
+ margin-top: 8px;
23
+ width: 20rem;
24
+ margin-right: -20rem;
25
+ flex-direction: column;
26
+ white-space: normal;
27
+ box-shadow:
28
+ 0 4px 6px -1px rgb(0 0 0 / 0.1),
29
+ 0 2px 4px -2px rgb(0 0 0 / 0.1);
30
+ border: 1px solid var(--color-fd-border);
31
+ border-radius: 6px;
32
+ padding: 8px;
33
+ z-index: 8;
34
+ color: var(--color-fd-popover-foreground);
35
+ background-color: var(--color-fd-popover);
36
+ }
37
+
38
+ .twoslash-completion-cursor {
39
+ display: inline-flex;
40
+ flex-direction: column;
41
+ }
42
+
43
+ .twoslash-completion-list:hover {
44
+ user-select: auto;
45
+ }
46
+
47
+ .twoslash-popup-arrow {
48
+ position: absolute;
49
+ top: -4px;
50
+ left: 1em;
51
+ transform: rotate(-45deg);
52
+ pointer-events: none;
53
+ width: 6px;
54
+ height: 6px;
55
+ border-top-width: 1px;
56
+ border-right-width: 1px;
57
+ border-color: var(--color-fd-primary);
58
+ background-color: var(--color-fd-popover);
59
+ }
60
+
61
+ .twoslash-popup-docs-tag {
62
+ display: flex;
63
+ flex-direction: row;
64
+ gap: 0.5em;
65
+ }
66
+
67
+ .twoslash-popup-docs-tag-name {
68
+ font-weight: 600;
69
+ }
70
+
71
+ .twoslash-popup-code {
72
+ font-size: 13px !important;
73
+ overflow-wrap: anywhere;
74
+ }
75
+
76
+ .twoslash-popup-code .line {
77
+ padding-left: 0 !important;
78
+ }
79
+
80
+ .twoslash-popup-docs,
81
+ .twoslash-popup-docs-tags {
82
+ font-size: 14px !important;
83
+ line-height: 20px !important;
84
+ margin-top: 8px !important;
85
+ }
86
+
87
+ /* ===== Hover Info ===== */
88
+ .twoslash:hover .twoslash-hover {
89
+ border-color: currentColor;
90
+ }
91
+
92
+ .twoslash .twoslash-hover {
93
+ /* Reset button styles to make it behave like inline text */
94
+ all: unset;
95
+
96
+ /* Restore the original hover indicator styles */
97
+ position: relative;
98
+ transition: border 300ms;
99
+ border-bottom: 1px dotted;
100
+ border-color: transparent;
101
+ }
102
+
103
+ /* ===== Error Line ===== */
104
+ .twoslash .twoslash-error-line {
105
+ position: relative;
106
+ background-color: var(--twoslash-error-bg);
107
+ border-left: 3px solid var(--color-twoslash-error-foreground);
108
+ color: var(--color-twoslash-error-foreground);
109
+ padding: 6px 12px;
110
+ margin: 0.2em 0;
111
+ }
112
+
113
+ .twoslash .twoslash-error {
114
+ text-decoration: wavy underline var(--color-twoslash-error-foreground);
115
+ padding-bottom: 2px;
116
+ }
117
+
118
+ /* ===== Completions ===== */
119
+ .twoslash-completion-cursor::before {
120
+ width: 1px;
121
+ height: 1.4em;
122
+ content: ' ';
123
+ background-color: var(--color-fd-foreground);
124
+ }
125
+
126
+ .twoslash-completion-list {
127
+ display: inline-flex;
128
+ }
129
+
130
+ .twoslash-completion-list li {
131
+ font-size: 13px;
132
+ display: inline-flex;
133
+ align-items: center;
134
+ overflow: hidden;
135
+ text-overflow: ellipsis;
136
+ white-space: nowrap;
137
+ gap: 0.5rem;
138
+ }
139
+
140
+ .twoslash-completion-list li span.twoslash-completions-unmatched {
141
+ color: var(--color-fd-muted-foreground);
142
+ }
143
+
144
+ .twoslash-completion-list .deprecated {
145
+ text-decoration: line-through;
146
+ opacity: 0.5;
147
+ }
148
+
149
+ /* Icons */
150
+ .twoslash-completion-list .twoslash-completions-icon {
151
+ width: 1em;
152
+ flex: none;
153
+ color: var(--color-fd-muted-foreground);
154
+ }
155
+
156
+ /* Custom Tags */
157
+ .twoslash .twoslash-tag-line {
158
+ position: relative;
159
+ background-color: var(--color-twoslash-tag);
160
+ border-left: 3px solid var(--color-twoslash-tag-foreground);
161
+ color: var(--color-twoslash-tag-foreground);
162
+ padding: 6px 10px;
163
+ margin: 0.2em 0;
164
+ display: flex;
165
+ align-items: center;
166
+ gap: 0.3em;
167
+ }
168
+
169
+ .twoslash .twoslash-tag-line .twoslash-tag-icon {
170
+ width: 1.1em;
171
+ color: inherit;
172
+ }
173
+
174
+ .twoslash .twoslash-tag-line.twoslash-tag-error-line {
175
+ background-color: var(--color-twoslash-error);
176
+ border-left: 3px solid var(--color-twoslash-error-foreground);
177
+ color: var(--color-twoslash-error-foreground);
178
+ }
179
+
180
+ .twoslash .twoslash-tag-line.twoslash-tag-warn-line {
181
+ background-color: var(--color-twoslash-tag-warn);
182
+ border-left: 3px solid var(--color-twoslash-tag-warn-foreground);
183
+ color: var(--color-twoslash-tag-warn-foreground);
184
+ }
185
+
186
+ .twoslash .twoslash-tag-line.twoslash-tag-annotate-line {
187
+ background-color: var(--color-twoslash-tag-annotate);
188
+ border-left: 3px solid var(--color-twoslash-tag-annotate-foreground);
189
+ color: var(--color-twoslash-tag-annotate-foreground);
190
+ }
191
+
192
+ /* Respect people's wishes to not have animations */
193
+ @media (prefers-reduced-motion: reduce) {
194
+ .twoslash * {
195
+ transition: none !important;
196
+ }
197
+ }
198
+
199
+ .fd-twoslash-popover {
200
+ z-index: 50;
201
+ min-width: 240px;
202
+ max-width: min(450px, 96vw);
203
+ max-height: 400px;
204
+ overflow: auto;
205
+ border-radius: var(--radius-xl);
206
+ border: 1px solid var(--color-fd-border);
207
+ background-color: var(--color-fd-popover);
208
+ padding: calc(var(--spacing) * 3);
209
+ font-size: var(--text-sm);
210
+ color: var(--color-fd-popover-foreground);
211
+ box-shadow: var(--shadow-md);
212
+ transform-origin: var(--transform-origin);
213
+ }
214
+
215
+ .fd-twoslash-popover[data-open] {
216
+ animation: var(--animate-fd-popover-in);
217
+ }
218
+
219
+ .fd-twoslash-popover[data-closed] {
220
+ animation: var(--animate-fd-popover-out);
221
+ }
222
+
223
+ .fd-twoslash-popover:focus-visible {
224
+ outline-style: none;
225
+ }