-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathcustom-frontmatter.mjs
More file actions
1132 lines (1039 loc) · 40.6 KB
/
Copy pathcustom-frontmatter.mjs
File metadata and controls
1132 lines (1039 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { readFileSync } from "node:fs";
import { join } from "node:path";
import {
ReflectionKind,
DeclarationReflection,
ReflectionType,
ReferenceType,
IntrinsicType,
ArrayType,
UnionType,
LiteralType,
IntersectionType,
TupleType,
ReflectionFlag,
UnknownType,
} from "typedoc";
import { MarkdownPageEvent } from "typedoc-plugin-markdown";
import ts from "typescript";
/**
* Determine if a function should be categorized as a component (React components)
*
* @param {string} fileName - The function name
* @param {string} packageName - The package name
* @returns {boolean} True if it should be categorized as a component
*/
function isReactComponent(fileName, packageName) {
// React components typically start with uppercase letter
const isUpperCase = fileName[0] === fileName[0].toUpperCase();
// Known React components
const reactComponents = [
"AlchemyAccountProvider",
"AuthCard",
"Dialog",
"UiConfigProvider",
];
return (
(packageName === "react" || packageName === "react-native") &&
(isUpperCase || reactComponents.includes(fileName))
);
}
/**
* Extract package name from URL path
*
* @param {string} url - The page URL
* @returns {string|null} The package name (e.g., 'react', 'react-native', 'core')
*/
function extractPackageFromUrl(url) {
if (!url) return null;
const match = url.match(/^(?:account-kit|aa-sdk)\/([^/]+)\//);
return match ? match[1] : null;
}
/**
* Custom plugin to generate frontmatter with title, description, and slug
*
* @param {import('typedoc-plugin-markdown').MarkdownApplication} app
*/
/**
* Check if a reflection's source is exclusively from external locations
* (compiled dist/ files or node_modules/), indicating it is either a
* re-export or an inherited member from an external package.
*
* @param {import('typedoc').Reflection} reflection - Reflection to inspect for source file metadata.
* @returns {boolean} True when all reflection sources are generated or external.
*/
function isExternalSource(reflection) {
const sources = reflection.sources;
return (
sources?.length > 0 &&
sources.every(
(s) =>
s.fileName.includes("/dist/") || s.fileName.includes("node_modules/"),
)
);
}
/**
* Convert a TypeScript type from the checker into a TypeDoc Type.
* Handles common patterns and falls back to a string representation.
*
* @param {import('typescript').TypeChecker} checker - TypeScript checker used to inspect type structure.
* @param {import('typescript').Type} tsType - TypeScript type to convert into a TypeDoc type.
* @param {import('typedoc').DeclarationReflection} parent - Parent reflection for nested objects
* @param {import('typedoc').ProjectReflection} project - TypeDoc project that owns generated reflections.
* @param {number} depth - Recursion depth guard
* @returns {import('typedoc').Type} TypeDoc type representation for the TypeScript type.
*/
function tsTypeToTypeDoc(checker, tsType, parent, project, depth = 0) {
if (depth > 4) {
return new UnknownType(checker.typeToString(tsType));
}
const typeStr = checker.typeToString(tsType);
// Intrinsic / primitive types
const intrinsics = [
"string",
"number",
"bigint",
"boolean",
"undefined",
"null",
"void",
"never",
"any",
"unknown",
"symbol",
];
if (intrinsics.includes(typeStr)) {
return new IntrinsicType(typeStr);
}
// String/number/boolean literal types
if (tsType.isStringLiteral()) {
return new LiteralType(tsType.value);
}
if (tsType.isNumberLiteral()) {
return new LiteralType(tsType.value);
}
if (typeStr === "true") return new LiteralType(true);
if (typeStr === "false") return new LiteralType(false);
// Union types
if (tsType.isUnion()) {
const members = tsType.types.map((t) =>
tsTypeToTypeDoc(checker, t, parent, project, depth + 1),
);
return new UnionType(members);
}
// Intersection types
if (tsType.isIntersection()) {
const members = tsType.types.map((t) =>
tsTypeToTypeDoc(checker, t, parent, project, depth + 1),
);
return new IntersectionType(members);
}
// Array types
if (checker.isArrayType(tsType)) {
const typeArgs = checker.getTypeArguments(tsType);
if (typeArgs.length > 0) {
const elementType = tsTypeToTypeDoc(
checker,
typeArgs[0],
parent,
project,
depth + 1,
);
return new ArrayType(elementType);
}
}
// Tuple types
if (checker.isTupleType(tsType)) {
const typeArgs = checker.getTypeArguments(tsType);
const elements = typeArgs.map((t) =>
tsTypeToTypeDoc(checker, t, parent, project, depth + 1),
);
return new TupleType(elements);
}
// Template literal types (e.g., `0x${string}`)
if (tsType.flags & ts.TypeFlags.TemplateLiteral) {
// TypeDoc's TemplateLiteralType expects head + tail pairs
// For simplicity, use the string representation
return new UnknownType(typeStr);
}
// Object types with properties
const props = checker.getPropertiesOfType(tsType);
const callSigs = tsType.getCallSignatures();
if (props.length > 0 && callSigs.length === 0) {
const typeLiteral = new DeclarationReflection(
"__type",
ReflectionKind.TypeLiteral,
parent,
);
for (const prop of props) {
const propDecl = new DeclarationReflection(
prop.name,
ReflectionKind.Property,
typeLiteral,
);
const propType = checker.getTypeOfSymbol(prop);
propDecl.type = tsTypeToTypeDoc(
checker,
propType,
typeLiteral,
project,
depth + 1,
);
// Mark optional properties
if (prop.flags & ts.SymbolFlags.Optional) {
propDecl.flags.setFlag(ReflectionFlag.Optional, true);
}
typeLiteral.children ??= [];
typeLiteral.children.push(propDecl);
}
return new ReflectionType(typeLiteral);
}
// Fallback: use the checker's string representation
return new UnknownType(typeStr);
}
/**
* Check if a TypeDoc type represents an empty/broken object ({} or Object)
*
* @param {import('typedoc').Type | undefined} type - TypeDoc type to inspect.
* @returns {boolean} True when the type is an empty reflected object.
*/
function isEmptyObjectType(type) {
if (!type) return false;
if (type.type === "reflection") {
const decl = type.declaration;
return (
!decl?.children?.length &&
!decl?.signatures?.length &&
!decl?.indexSignatures?.length
);
}
return false;
}
/**
* Resolve schema-derived types that TypeDoc couldn't resolve.
* Fixes type aliases (detail pages) and function signatures.
*
* @param {import('typedoc').Context} context - TypeDoc conversion context used for symbol lookup.
* @param {import('typedoc').ProjectReflection} project - Project reflection whose schema-derived types should be repaired.
* @param {import('typescript').TypeChecker} checker - TypeScript checker used to resolve structural types.
* @returns {{ count: number, codeBlockFixes: Map<string, string> }} Number of fixes and code block replacements.
*/
function resolveSchemaTypes(context, project, checker) {
let fixedCount = 0;
// Map of type alias name → checker type string for code block fixups
const codeBlockFixes = new Map();
const reflections = Object.values(project.reflections);
// Only fix types in the wallet-apis package (schema-derived types)
const isWalletApis = (r) =>
r.sources?.some((s) => s.fileName.includes("wallet-apis/"));
// Build a lookup of type alias reflections by name (wallet-apis only)
const typeAliasMap = new Map();
for (const r of reflections) {
if (
r instanceof DeclarationReflection &&
r.kind === ReflectionKind.TypeAlias &&
isWalletApis(r)
) {
typeAliasMap.set(r.name, r);
}
}
// Step 1: Fix type alias reflections that have empty/broken types
for (const reflection of reflections) {
if (
!(reflection instanceof DeclarationReflection) ||
reflection.kind !== ReflectionKind.TypeAlias ||
!isWalletApis(reflection)
) {
continue;
}
// Check if the current type needs fixing:
// 1. No type at all (null/undefined)
// 2. Empty object type ({}) — TypeDoc couldn't resolve schema types
// 3. Wrapped in Prettify/utility types that collapse inner types to `object`
// 4. Unresolved internal reference — unexported alias TypeDoc can't follow
const currentType = reflection.type;
const needsFix =
// No type at all
!currentType ||
// Entirely collapsed to `object` intrinsic
(currentType?.type === "intrinsic" && currentType.name === "object") ||
// Empty object type ({})
isEmptyObjectType(currentType) ||
(currentType?.type === "reference" &&
currentType.typeArguments?.some(isEmptyObjectType)) ||
// Unresolved internal reference (no package, no type args)
(currentType?.type === "reference" &&
!currentType.reflection &&
!currentType.package &&
!currentType.typeArguments?.length);
if (!needsFix) continue;
const sym = context.getSymbolFromReflection(reflection);
if (!sym) continue;
const tsType = checker.getDeclaredTypeOfSymbol(sym);
let props = checker.getPropertiesOfType(tsType);
// For types wrapped in Prettify or other mapped types, getDeclaredType
// may return the mapped type itself. Try getTypeOfSymbol to get the
// fully resolved structural type instead.
let resolvedType = tsType;
if (props.length === 0) {
resolvedType = checker.getTypeOfSymbol(sym);
props = checker.getPropertiesOfType(resolvedType);
}
if (props.length === 0) continue;
// If the reflection already has children (TypeDoc resolved the properties
// but rendered the code block as `object`), don't replace the type —
// just store a code block fix. Creating a new ReflectionType with children
// would duplicate the property anchors (causing `-1` suffixes).
const hasExistingChildren =
reflection.children?.length > 0 ||
(reflection.type?.type === "reflection" &&
reflection.type.declaration?.children?.length > 0);
if (hasExistingChildren) {
// Prefer the original source text (preserves named type references)
// over the checker's typeToString (which expands everything).
let codeBlockStr;
const cbSym = context.getSymbolFromReflection(reflection);
const cbDecl = cbSym?.getDeclarations()?.[0];
if (cbDecl && ts.isTypeAliasDeclaration(cbDecl) && cbDecl.type) {
codeBlockStr = cbDecl.type.getText();
}
if (!codeBlockStr) {
codeBlockStr = checker.typeToString(
resolvedType,
undefined,
ts.TypeFormatFlags.MultilineObjectLiterals |
ts.TypeFormatFlags.NoTruncation |
ts.TypeFormatFlags.InTypeAlias,
);
}
codeBlockFixes.set(reflection.name, codeBlockStr);
fixedCount++;
} else {
// No existing children — build a proper ReflectionType from the TS checker
const newType = tsTypeToTypeDoc(
checker,
resolvedType,
reflection,
project,
);
if (newType.type !== "unknown") {
reflection.type = newType;
fixedCount++;
if (newType.type === "reflection") {
codeBlockFixes.set(
reflection.name,
checker.typeToString(
resolvedType,
undefined,
ts.TypeFormatFlags.MultilineObjectLiterals |
ts.TypeFormatFlags.NoTruncation |
ts.TypeFormatFlags.InTypeAlias,
),
);
}
}
}
}
// Step 2: Fix function return types — replace empty ReflectionType in
// Promise<{}> with a ReferenceType to the named result type
for (const reflection of reflections) {
if (
!(reflection instanceof DeclarationReflection) ||
reflection.kind !== ReflectionKind.Function ||
!isWalletApis(reflection)
) {
continue;
}
for (const sig of reflection.signatures ?? []) {
// Fix return type: replace inline expansion with named type reference
// Triggers for both empty ({}) and expanded ReflectionTypes
if (
sig.type?.type === "reference" &&
sig.type.name === "Promise" &&
sig.type.typeArguments?.length === 1
) {
const innerArg = sig.type.typeArguments[0];
const isUnresolved =
innerArg.type === "reflection" ||
(innerArg.type === "union" &&
innerArg.types?.some(
(t) => isEmptyObjectType(t) || t.type === "reflection",
)) ||
(innerArg.type === "intrinsic" && innerArg.name === "object");
if (isUnresolved) {
// Use the TS checker to find the actual return type name
const funcSym = context.getSymbolFromReflection(reflection);
if (funcSym) {
const funcType = checker.getTypeOfSymbol(funcSym);
const callSigs = funcType.getCallSignatures();
if (callSigs.length > 0) {
const returnType = checker.getReturnTypeOfSignature(callSigs[0]);
// Check if it's Promise<T>
if (returnType.symbol?.name === "Promise") {
const typeArgs = checker.getTypeArguments(returnType);
if (typeArgs.length > 0) {
const innerType = typeArgs[0];
// Try to find the named type alias
let aliasName = innerType.aliasSymbol?.name;
// If aliasSymbol is lost (e.g., through Prettify), check the
// function's return type annotation for a named reference
if (!aliasName || !typeAliasMap.has(aliasName)) {
const funcDecl = funcSym.getDeclarations()?.[0];
if (funcDecl && funcDecl.type) {
// Return type annotation: Promise<SomeType>
const retNode = funcDecl.type;
if (
ts.isTypeReferenceNode(retNode) &&
retNode.typeArguments?.length === 1
) {
const innerNode = retNode.typeArguments[0];
if (ts.isTypeReferenceNode(innerNode)) {
aliasName = innerNode.typeName.getText();
}
}
}
}
const targetReflection = aliasName
? typeAliasMap.get(aliasName)
: null;
if (targetReflection) {
// Replace with a reference to the named type
sig.type.typeArguments[0] =
ReferenceType.createResolvedReference(
aliasName,
targetReflection,
project,
);
fixedCount++;
} else {
// No named type found — inline the resolved type
const resolved = tsTypeToTypeDoc(
checker,
innerType,
reflection,
project,
);
if (resolved.type !== "unknown") {
sig.type.typeArguments[0] = resolved;
fixedCount++;
}
}
}
}
}
}
}
}
// Fix non-Promise return types that resolved to `any` — happens when
// TypeDoc can't resolve complex generic return types (e.g. viem Client<...>)
// on overloaded functions. Walk the TS AST to find the declared return
// type annotation and replace with a ReferenceType if it's a known alias.
if (
sig.type?.type === "intrinsic" &&
(sig.type.name === "any" || sig.type.name === "object")
) {
const funcSym = context.getSymbolFromReflection(reflection);
if (funcSym) {
const decls = funcSym.getDeclarations() ?? [];
const sigIndex = (reflection.signatures ?? []).indexOf(sig);
// For overloaded functions, match by index against non-implementation declarations
const overloadDecls = decls.filter(
(d) => ts.isFunctionDeclaration(d) && !d.body,
);
const tsDecl = overloadDecls[sigIndex] ?? decls[sigIndex];
if (tsDecl && tsDecl.type && ts.isTypeReferenceNode(tsDecl.type)) {
const aliasName = tsDecl.type.typeName.getText();
const target = typeAliasMap.get(aliasName);
if (target) {
sig.type = ReferenceType.createResolvedReference(
aliasName,
target,
project,
);
fixedCount++;
}
}
}
}
// Fix parameter types: use TS checker to restore named types
// TypeDoc may render params as "Object" when it can't resolve Prettify<T>
// or other mapped types. Check all non-reference params against the checker.
const funcSym2 = context.getSymbolFromReflection(reflection);
if (funcSym2 && sig.parameters?.length) {
const funcType2 = checker.getTypeOfSymbol(funcSym2);
const callSigs2 = funcType2.getCallSignatures();
if (callSigs2.length > 0) {
const tsParams = callSigs2[0].getParameters();
for (let i = 0; i < sig.parameters.length; i++) {
const param = sig.parameters[i];
const tsParam = tsParams[i];
if (!tsParam) continue;
// Skip params that already have a proper reference type
if (param.type?.type === "reference" && param.type.reflection) {
continue;
}
const paramType = checker.getTypeOfSymbol(tsParam);
// Try to get the named type from the parameter's type annotation
// (aliasSymbol is lost when Prettify<T> expands the type)
let aliasName = paramType.aliasSymbol?.name;
if (!aliasName || !typeAliasMap.has(aliasName)) {
const paramDecl = tsParam.getDeclarations()?.[0];
if (paramDecl && ts.isParameter(paramDecl) && paramDecl.type) {
if (ts.isTypeReferenceNode(paramDecl.type)) {
aliasName = paramDecl.type.typeName.getText();
}
}
}
const targetReflection = aliasName
? typeAliasMap.get(aliasName)
: null;
if (targetReflection) {
param.type = ReferenceType.createResolvedReference(
aliasName,
targetReflection,
project,
);
fixedCount++;
} else if (
isEmptyObjectType(param.type) ||
(param.type?.type === "intrinsic" && param.type.name === "Object")
) {
// Inline the resolved type as a fallback
const props = checker.getPropertiesOfType(paramType);
if (props.length > 0) {
const resolved = tsTypeToTypeDoc(
checker,
paramType,
reflection,
project,
);
if (resolved.type !== "unknown") {
param.type = resolved;
fixedCount++;
}
}
}
}
}
}
}
}
// Step 2b: Generate code block fixes for ALL wallet-apis type aliases
// that weren't already fixed. Even when TypeDoc resolves the type alias
// definition, the code block often shows opaque utility-type chains
// (Prettify<WithCapabilities<...>>) instead of the resolved shape.
for (const reflection of reflections) {
if (
!(reflection instanceof DeclarationReflection) ||
reflection.kind !== ReflectionKind.TypeAlias ||
!isWalletApis(reflection)
) {
continue;
}
const sym = context.getSymbolFromReflection(reflection);
if (!sym) continue;
// Skip generic types (have type parameters) — expanding them inlines
// the full resolved type of external packages like viem's Client<...>.
const decl = sym.getDeclarations()?.[0];
if (
decl &&
ts.isTypeAliasDeclaration(decl) &&
decl.typeParameters?.length
) {
continue;
}
// Try multiple resolution strategies — TypeDoc's checker with
// skipErrorChecking may fail on complex conditional/mapped types.
const formatFlags =
ts.TypeFormatFlags.MultilineObjectLiterals |
ts.TypeFormatFlags.NoTruncation |
ts.TypeFormatFlags.InTypeAlias;
let typeStr;
const candidates = [];
// Strategy 1: getTypeAtLocation on the type node
if (decl && ts.isTypeAliasDeclaration(decl) && decl.type) {
candidates.push(checker.getTypeAtLocation(decl.type));
}
// Strategy 2: getTypeOfSymbol (resolves through aliases differently)
candidates.push(checker.getTypeOfSymbol(sym));
// Strategy 3: getDeclaredTypeOfSymbol
candidates.push(checker.getDeclaredTypeOfSymbol(sym));
const trivial = new Set([
reflection.name,
"any",
"unknown",
"object",
"never",
]);
for (const candidate of candidates) {
const str = checker.typeToString(candidate, undefined, formatFlags);
if (!trivial.has(str)) {
typeStr = str;
break;
}
}
if (!typeStr) continue;
// Skip types that reference viem internals — the checker over-expands
// external package types (Client, WalletClient, TypedDataDefinition, etc.)
// producing walls of irrelevant internal fields.
if (
typeStr.includes("Client_Base<") ||
typeStr.includes("ExactPartial<") ||
typeStr.includes("WalletActions<") ||
typeStr.includes("SignTransactionParameters") ||
typeStr.includes("cacheTime?") ||
typeStr.includes("ccipRead?") ||
typeStr.includes("TypedDataParameter")
) {
continue;
}
codeBlockFixes.set(reflection.name, typeStr);
fixedCount++;
}
// Step 3: Fix method signatures inside type alias reflections
// (e.g. SmartWalletActions) — TypeDoc expands schema-derived param/return
// types inline instead of keeping the named type references.
for (const reflection of reflections) {
if (
!(reflection instanceof DeclarationReflection) ||
reflection.kind !== ReflectionKind.TypeAlias ||
!isWalletApis(reflection)
) {
continue;
}
// Step 3 fixes method signatures AND generates source-text code blocks.
// For types with children in a reflection, fix signatures.
// For ANY type alias backed by a type literal in source, use source text.
const decl3 =
reflection.type?.type === "reflection"
? reflection.type.declaration
: null;
// Get the TS AST declaration for this type alias
const sym = context.getSymbolFromReflection(reflection);
if (!sym) continue;
const symDecls = sym.getDeclarations();
if (!symDecls?.length) continue;
const typeAliasDecl = symDecls[0];
if (!ts.isTypeAliasDeclaration(typeAliasDecl)) continue;
const typeLiteral = typeAliasDecl.type;
if (!ts.isTypeLiteralNode(typeLiteral)) continue;
// Map member name → AST PropertySignature
const memberAstMap = new Map();
for (const member of typeLiteral.members) {
if (ts.isPropertySignature(member) && member.name) {
memberAstMap.set(member.name.getText(), member);
}
}
// Fix method signatures if TypeDoc has reflection children
if (decl3?.children?.length) {
for (const child of decl3.children) {
const astMember = memberAstMap.get(child.name);
if (!astMember?.type || !ts.isFunctionTypeNode(astMember.type))
continue;
const funcTypeNode = astMember.type;
for (const sig of child.signatures ?? []) {
// Fix return type: replace expanded type with named reference
if (
sig.type?.type === "reference" &&
sig.type.name === "Promise" &&
sig.type.typeArguments?.length === 1
) {
const innerArg = sig.type.typeArguments[0];
if (
innerArg.type === "reflection" ||
(innerArg.type === "intrinsic" && innerArg.name === "object")
) {
const retNode = funcTypeNode.type;
if (
ts.isTypeReferenceNode(retNode) &&
retNode.typeArguments?.length === 1
) {
const innerNode = retNode.typeArguments[0];
if (ts.isTypeReferenceNode(innerNode)) {
const aliasName = innerNode.typeName.getText();
const target = typeAliasMap.get(aliasName);
if (target) {
sig.type.typeArguments[0] =
ReferenceType.createResolvedReference(
aliasName,
target,
project,
);
fixedCount++;
}
}
}
}
}
// Fix parameter types: replace expanded types with named references
if (sig.parameters?.length) {
for (let i = 0; i < sig.parameters.length; i++) {
const param = sig.parameters[i];
if (param.type?.type === "reference" && param.type.reflection) {
continue;
}
const astParam = funcTypeNode.parameters[i];
if (!astParam?.type) continue;
let typeNode = astParam.type;
if (ts.isUnionTypeNode(typeNode)) {
const nonUndef = typeNode.types.find(
(t) =>
!(
t.kind === ts.SyntaxKind.UndefinedKeyword ||
(ts.isLiteralTypeNode(t) &&
t.literal.kind === ts.SyntaxKind.UndefinedKeyword)
),
);
if (nonUndef) typeNode = nonUndef;
}
if (!ts.isTypeReferenceNode(typeNode)) continue;
const aliasName = typeNode.typeName.getText();
const target = typeAliasMap.get(aliasName);
if (target) {
param.type = ReferenceType.createResolvedReference(
aliasName,
target,
project,
);
fixedCount++;
}
}
}
}
}
}
// Always use source AST text for type literal code blocks — keeps
// named type references instead of checker-expanded inline types.
const sourceText = typeLiteral.getText();
if (sourceText) {
codeBlockFixes.set(reflection.name, sourceText);
}
}
return { count: fixedCount, codeBlockFixes };
}
export function load(app) {
// Remove reflections sourced from external locations (dist/ or node_modules/)
// after conversion so that:
// 1. Re-exports don't get duplicate pages (originals in source packages remain)
// 2. Inherited members from external packages (viem, @types/node) are excluded
app.converter.on("resolveEnd", (context) => {
const project = context.project;
const toRemove = [];
for (const reflection of Object.values(project.reflections)) {
if (
reflection instanceof DeclarationReflection &&
isExternalSource(reflection)
) {
toRemove.push(reflection);
}
}
for (const reflection of toRemove) {
project.removeReflection(reflection);
}
if (toRemove.length > 0) {
console.log(
`Removed ${toRemove.length} reflections sourced from external locations (dist/, node_modules/)`,
);
}
// --- Resolve schema-derived types using the TS checker ---
// TypeDoc can't resolve StaticDecode<T> from schema, so types derived
// via MethodResponse/MethodParams appear as {} or Object. We use the TS
// checker to get the actual resolved properties and build proper TypeDoc
// reflections.
let checker;
try {
checker = context.programs[0].getTypeChecker();
} catch {
// No checker available — skip type resolution
}
if (checker) {
const result = resolveSchemaTypes(context, project, checker);
if (result.count > 0) {
console.log(
`Resolved ${result.count} schema-derived types using TS checker`,
);
}
// Store code block fixes for use during markdown rendering
app._codeBlockFixes = result.codeBlockFixes;
}
});
// Handle frontmatter generation
app.renderer.on(
MarkdownPageEvent.BEGIN,
/** @param {import('typedoc-plugin-markdown').MarkdownPageEvent} page - The markdown page event containing model and URL information */
(page) => {
if (!page.model) return;
let title = page.model.name;
// Extract package name from URL for categorization
const packageName = extractPackageFromUrl(page.url);
const isReadmeFile = page.url && page.url.endsWith("README.mdx");
const isExperimentalPage =
page.url && page.url.includes("/experimental/") && !isReadmeFile;
const isSolanaPage =
page.url && page.url.includes("/solana/") && !isReadmeFile;
if (page.model.kind === ReflectionKind.Class) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.Interface) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.Function) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.Variable) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.TypeAlias) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.Enum) {
title = page.model.name;
} else if (page.model.kind === ReflectionKind.Constructor) {
title = page.model.parent?.name || page.model.name;
} else if (page.model.kind === ReflectionKind.Method) {
title = `${page.model.parent?.name || ""}${page.model.name ? `.${page.model.name}` : ""}`;
} else if (page.model.kind === ReflectionKind.Property) {
title = `${page.model.parent?.name || ""}${page.model.name ? `.${page.model.name}` : ""}`;
}
let description = "";
if (
page.model.comment?.summary &&
page.model.comment.summary.length > 0
) {
description = page.model.comment.summary
.map((part) => part.text || "")
.join("")
.replace(/\n/g, " ")
.trim();
}
if (!description) {
if (page.model.kind === ReflectionKind.Class) {
description = `Overview of the ${page.model.name} class`;
} else if (page.model.kind === ReflectionKind.Interface) {
description = `Overview of the ${page.model.name} interface`;
} else if (page.model.kind === ReflectionKind.Function) {
// Apply same categorization logic as YAML generator
if (isReactComponent(page.model.name, packageName)) {
description = `Overview of the ${page.model.name} component`;
} else if (
page.model.name.startsWith("use") &&
(packageName === "react" || packageName === "react-native")
) {
description = `Overview of the ${page.model.name} hook`;
} else {
description = `Overview of the ${page.model.name} function`;
}
} else if (page.model.kind === ReflectionKind.Constructor) {
description = `Overview of the ${page.model.parent?.name || page.model.name} constructor`;
} else if (page.model.kind === ReflectionKind.Method) {
description = `Overview of the ${page.model.name} method`;
} else if (page.model.kind === ReflectionKind.Property) {
description = `Overview of the ${page.model.name} property`;
} else {
description = `Overview of ${page.model.name}`;
}
}
// For README.mdx files, remove TypeDoc source path segments from title and description.
if (isReadmeFile) {
title = title.replace(/\/src\/exports/g, "").replace(/\/src/g, "");
title = `@alchemy/${title}`;
description = description
.replace(/\/src\/exports/g, "")
.replace(/\/src/g, "");
}
if (isExperimentalPage) {
title = `${title} (experimental)`;
} else if (isSolanaPage) {
title = `${title} (Solana)`;
}
// Generate slug from the URL path
let slug = "";
if (page.url) {
let processedUrl = page.url
.replace(/\.mdx$/, "")
.replace(/\/src/g, "")
.replace(/\/exports/g, "");
if (page.model.kind === ReflectionKind.Function) {
if (isReactComponent(page.model.name, packageName)) {
// Replace /functions/ with /components/ for React components
processedUrl = processedUrl.replace(
/\/functions\//,
"/components/",
);
} else if (
page.model.name.startsWith("use") &&
(packageName === "react" || packageName === "react-native")
) {
// Replace /functions/ with /hooks/ for React hooks
processedUrl = processedUrl.replace(/\/functions\//, "/hooks/");
}
}
slug = `wallets/reference/${processedUrl}`;
if (isReadmeFile) {
slug = slug.replace(/\/README$/, "");
}
}
page.frontmatter = {
title: title,
description: description,
slug: slug,
...page.frontmatter,
};
},
);
// Handle post-processing: auto-generated comment + link fixes
app.renderer.on(
MarkdownPageEvent.END,
/** @param {import('typedoc-plugin-markdown').MarkdownPageEvent} page - The markdown page event containing content to modify */
(page) => {
if (!page.contents) return;
const slug = page.frontmatter?.slug;
const isReadmeFile = page.url && page.url.endsWith("README.mdx");
const isPackageRootReadmeFile =
isReadmeFile &&
page.url &&
/^[^/]+\/src\/(?:exports\/)?README\.mdx$/.test(page.url);
// For package-root README pages, inject the package README.md content
// before link rewrites so that any relative links in the README get
// normalized too. Nested export indexes stay as TypeDoc module indexes
// unless they get their own source README support.
if (isPackageRootReadmeFile && page.url) {
// page.url is e.g. "wallet-apis/src/exports/README.mdx"
// Package dir is the first segment: "wallet-apis"
const segments = page.url.split("/");
if (segments.length >= 1) {
const pkgDir = join("packages", segments[0]);
try {
const raw = readFileSync(join(pkgDir, "README.md"), "utf-8");
// Strip the first markdown heading (# title) since the page already
// has a title via frontmatter, then trim.
const stripped = raw.replace(/^#\s+.+\n+/, "").trim();
if (stripped) {
// Insert after frontmatter, before TypeDoc content
const fmMatch = page.contents.match(/^(---\n[\s\S]*?\n---\n)/);
if (fmMatch) {
const fm = fmMatch[1];
const rest = page.contents.substring(fm.length);
page.contents = fm + "\n" + stripped + "\n\n" + rest;
} else {
page.contents = stripped + "\n\n" + page.contents;