Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

utils.ts

238 lines6.1 KB

1import * as path from "node:path";
2​
3import { Node, type JSDoc } from "ts-morph";
4​
5import type {
6 ExampleDoc,
7 ExampleSection,
8 JSDocInfo,
9 PropertyDoc,
10} from "./types.ts";
11​
12export const repoRoot = path.resolve(import.meta.dir, "../..");
13export const packageRoot = path.join(repoRoot, "alchemy");
14export const srcRoot = path.join(packageRoot, "src");
15export const docsRoot = path.join(packageRoot, "docs");
16export const tsConfigPath = path.join(packageRoot, "tsconfig.json");
17​
18export function toPosix(filePath: string) {
19 return filePath.split(path.sep).join("/");
21​
22export function relativeSourcePath(filePath: string) {
23 return toPosix(path.relative(packageRoot, filePath));
25​
26export function titleFromRelativePath(relativePath: string) {
27 const baseName = path.basename(relativePath, ".ts");
28 if (baseName !== "index") {
29 return baseName;
30 }
31 const directory = path.dirname(relativePath);
32 return directory === "." ? "API Reference" : path.basename(directory);
34​
35export function labelFromDocRelativePath(relativePath: string) {
36 return titleFromRelativePath(relativePath);
38​
39export function lowerPathKey(relativePath: string) {
40 return toPosix(relativePath).toLowerCase();
42​
43export function canonicalScore(relativePath: string) {
44 const baseName = path.basename(relativePath);
45 const uppercaseCount = [...relativePath].filter(
46 (char) => char >= "A" && char <= "Z",
47 ).length;
48 return (
49 (baseName === "index.ts" ? 1000 : 0) +
50 (/^[A-Z]/.test(baseName) ? 100 : 0) +
51 uppercaseCount * 5 +
52 (relativePath === relativePath.toLowerCase() ? -20 : 0)
53 );
55​
56export function escapeMarkdown(value: string) {
57 return value.replace(/\|/g, "\\|");
59​
60export function normalizeWhitespace(value: string) {
61 return value.replace(/\s+/g, " ").trim();
63​
64export function formatTypeText(value: string | undefined) {
65 return value
66 ? value
67 .replace(/\/\*\*[\s\S]*?\*\//g, " ")
68 .replace(/\/\*[\s\S]*?\*\//g, " ")
69 .replace(/\/\/.*$/gm, " ")
70 .replace(/\s+/g, " ")
71 .trim()
72 : "unknown";
74​
75export function truncateInline(value: string, maxLength = 120) {
76 const normalized = formatTypeText(value);
77 return normalized.length <= maxLength
78 ? normalized
79 : `${normalized.slice(0, maxLength - 3)}...`;
81​
82export function lowerCamel(name: string) {
83 return name.charAt(0).toLowerCase() + name.slice(1);
85​
86export function docOutputPath(relativePath: string) {
87 return path.join(docsRoot, relativePath.replace(/\.ts$/, ".md"));
89​
90export function relativeDocLink(fromDocPath: string, toDocPath: string) {
91 return toPosix(path.relative(path.dirname(fromDocPath), toDocPath));
93​
94/**
95 * Convert JSDoc `{@link url | label}` into standard markdown links.
96 * Absolute `https://alchemy.run/...` URLs are rewritten to relative
97 * paths so the links work in any deployment (localhost, preview, prod).
98 */
99function resolveJSDocLinks(text: string): string {
100 return text.replace(
101 /\{@link\s+(https?:\/\/alchemy\.run(\/[^\s|}]*))\s*\|\s*([^}]+)\}/g,
102 (_match, _url, pathname, label) => `[${label.trim()}](${pathname})`,
103 );
105​
106export function cleanDocComment(raw: string) {
107 const cleaned = raw
108 .replace(/^\/\*\*?/, "")
109 .replace(/\*\/$/, "")
110 .split("\n")
111 .map((line) => line.replace(/^\s*\*\s?/, ""))
112 .join("\n");
113 return resolveJSDocLinks(cleaned);
115​
116function getJsDocBlocks(node: Node) {
117 const getter = (node as Node & { getJsDocs?: () => JSDoc[] }).getJsDocs;
118 return getter ? getter.call(node) : [];
120​
121export function getJSDocInfo(node: Node): JSDocInfo {
122 const docs = getJsDocBlocks(node);
123 if (docs.length === 0) {
124 return { sections: [] };
125 }
126​
127 const clean = cleanDocComment(docs.map((doc) => doc.getText()).join("\n"));
128 const lines = clean.split("\n");
129 const summaryLines: string[] = [];
130 const sections: ExampleSection[] = [];
131​
132 let defaultValue: string | undefined;
133 let sawTag = false;
134 let currentSection: ExampleSection | undefined;
135 let currentExample: ExampleDoc | undefined;
136​
137 const ensureSection = (title: string) => {
138 const section = { title, examples: [] };
139 sections.push(section);
140 currentSection = section;
141 return section;
142 };
143​
144 const flushExample = () => {
145 if (!currentExample) {
146 return;
147 }
148 currentExample.body = currentExample.body.trim();
149 if (!currentSection) {
150 currentSection = ensureSection("Examples");
151 }
152 currentSection.examples.push(currentExample);
153 currentExample = undefined;
154 };
155​
156 for (const line of lines) {
157 const tag = line.trimEnd().match(/^@(\w+)\s*(.*)$/);
158 if (tag) {
159 sawTag = true;
160 const [, name, rest] = tag;
161 const value = rest.trim();
162 switch (name) {
163 case "default":
164 defaultValue = value || undefined;
165 break;
166 case "section":
167 flushExample();
168 ensureSection(value || "Examples");
169 break;
170 case "example":
171 flushExample();
172 currentExample = {
173 title: value || "Example",
174 body: "",
175 };
176 break;
177 }
178 continue;
179 }
180​
181 if (!sawTag) {
182 summaryLines.push(line);
183 continue;
184 }
185​
186 if (currentExample) {
187 currentExample.body += `${line}\n`;
188 }
189 }
190​
191 flushExample();
192​
193 const summary = normalizeWhitespace(
194 summaryLines.join("\n").replace(/```[\s\S]*?```/g, ""),
195 );
196​
197 return {
198 summary: summary || undefined,
199 defaultValue,
200 sections,
201 };
203​
204export function getSummary(node: Node) {
205 return getJSDocInfo(node).summary;
207​
208export function getDefaultValue(node: Node) {
209 return getJSDocInfo(node).defaultValue;
211​
212export function guessExampleValue(property: PropertyDoc) {
213 const type = property.type;
214​
215 const literal = type.match(/"([^"]+)"|'([^']+)'/);
216 if (literal) {
217 return JSON.stringify(literal[1] ?? literal[2]);
218 }
219 if (/ScalarAttributeType/.test(type)) {
220 return `{ pk: "S" }`;
221 }
222 if (/Record</.test(type)) {
223 return "{}";
224 }
225 if (/\[\]$/.test(type) || /Array</.test(type)) {
226 return "[]";
227 }
228 if (/boolean/i.test(type)) {
229 return "true";
230 }
231 if (/number/i.test(type)) {
232 return "1";
233 }
234 if (/string/i.test(type) || /Name|Arn|Id|Url|Key|Path/.test(type)) {
235 return JSON.stringify(property.name);
236 }
237 return "undefined as any";