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

model.ts

814 lines21.9 KB

1import * as path from "node:path";
2​
3import {
4 Node,
5 SyntaxKind,
6 type ClassDeclaration,
7 type InterfaceDeclaration,
8 type ParameterDeclaration,
9 type SourceFile,
10 type Symbol,
11 type TypeAliasDeclaration,
12 type TypeNode,
13} from "ts-morph";
14​
15import {
16 getBindingPolicyClasses,
17 getBindingServiceClasses,
18 getFileKind,
19 getPrimaryNode,
20 getProviderDeclaration,
21 getResourceTypeDetails,
22} from "./discovery.ts";
23import {
24 docsRoot,
25 formatTypeText,
26 getDefaultValue,
27 getJSDocInfo,
28 getSummary,
29 guessExampleValue,
30 labelFromDocRelativePath,
31 lowerCamel,
32 relativeDocLink,
33 relativeSourcePath,
34 srcRoot,
35 titleFromRelativePath,
36 truncateInline,
37} from "./utils.ts";
38import type {
39 BindingClassDoc,
40 DirectoryCatalog,
41 ExportDoc,
42 FileDoc,
43 FileKind,
44 LinkDoc,
45 OperationDoc,
46 PropertyDoc,
47 ResourceDoc,
48 ShapeDoc,
49 SourceEntry,
50} from "./types.ts";
51import { lifecycleOperationOrder } from "./types.ts";
52​
53function propertySignatureToDoc(
54 property: import("ts-morph").PropertySignature,
55): PropertyDoc {
56 return {
57 name: property.getName(),
58 type: formatTypeText(
59 property.getTypeNode()?.getText() ?? property.getType().getText(property),
60 ),
61 optional: property.hasQuestionToken(),
62 readonly: property.isReadonly(),
63 description: getSummary(property),
64 defaultValue: getDefaultValue(property),
65 };
67​
68function getShapeFromMembers(
69 title: string,
70 members: Node[],
71 description?: string,
72): ShapeDoc | undefined {
73 const properties = members
74 .flatMap((member) =>
75 Node.isPropertySignature(member) ? [propertySignatureToDoc(member)] : [],
76 )
77 .sort((left, right) => left.name.localeCompare(right.name));
78​
79 if (properties.length === 0) {
80 return undefined;
81 }
82​
83 return {
84 title,
85 description,
86 properties,
87 };
89​
90function resolveShapeDeclaration(
91 symbol: Symbol | undefined,
92): InterfaceDeclaration | TypeAliasDeclaration | undefined {
93 return symbol
94 ?.getDeclarations()
95 .find(
96 (declaration) =>
97 Node.isInterfaceDeclaration(declaration) ||
98 Node.isTypeAliasDeclaration(declaration),
99 ) as InterfaceDeclaration | TypeAliasDeclaration | undefined;
101​
102function getShapeFromTypeNode(
103 title: string,
104 typeNode: TypeNode,
105 description?: string,
106): ShapeDoc | undefined {
107 if (Node.isTypeLiteral(typeNode)) {
108 return getShapeFromMembers(title, typeNode.getMembers(), description);
109 }
110​
111 if (Node.isTypeReference(typeNode)) {
112 const declaration = resolveShapeDeclaration(
113 typeNode.getTypeName().getSymbol(),
114 );
115 if (declaration) {
116 return getShapeFromDeclaration(title, declaration);
117 }
118 }
119​
120 return {
121 title,
122 description,
123 properties: [],
124 signature: formatTypeText(typeNode.getText()),
125 };
127​
128function getShapeFromDeclaration(
129 title: string,
130 declaration: InterfaceDeclaration | TypeAliasDeclaration,
131): ShapeDoc | undefined {
132 if (Node.isInterfaceDeclaration(declaration)) {
133 return getShapeFromMembers(
134 title,
135 declaration.getMembers(),
136 getSummary(declaration),
137 );
138 }
139​
140 const typeNode = declaration.getTypeNode();
141 if (!typeNode) {
142 return undefined;
143 }
144 return getShapeFromTypeNode(title, typeNode, getSummary(declaration));
146​
147function signatureForDeclaration(declaration: Node) {
148 if (Node.isClassDeclaration(declaration)) {
149 const heritage = declaration
150 .getHeritageClauses()
151 .flatMap((clause) => clause.getTypeNodes())
152 .map((typeNode) => typeNode.getText())
153 .join(", ");
154 return `class ${declaration.getName() ?? "Anonymous"}${heritage ? ` extends ${heritage}` : ""}`;
155 }
156​
157 if (Node.isFunctionDeclaration(declaration)) {
158 const params = declaration
159 .getParameters()
160 .map((param) => param.getText())
161 .join(", ");
162 const returnType = declaration.getReturnTypeNode()?.getText();
163 return `function ${declaration.getName() ?? "anonymous"}(${params})${returnType ? `: ${returnType}` : ""}`;
164 }
165​
166 if (Node.isInterfaceDeclaration(declaration)) {
167 return `interface ${declaration.getName()}`;
168 }
169​
170 if (Node.isTypeAliasDeclaration(declaration)) {
171 return `type ${declaration.getName()} = ${formatTypeText(
172 declaration.getTypeNode()?.getText(),
173 )}`;
174 }
175​
176 if (Node.isVariableDeclaration(declaration)) {
177 const kind =
178 declaration.getVariableStatement()?.getDeclarationKind() ?? "const";
179 const initializer = declaration.getInitializer()?.getText();
180 return `${kind} ${declaration.getName()}${initializer ? ` = ${truncateInline(initializer)}` : ""}`;
181 }
182​
183 if (Node.isModuleDeclaration(declaration)) {
184 return `namespace ${declaration.getName()}`;
185 }
186​
187 if (Node.isEnumDeclaration(declaration)) {
188 return `enum ${declaration.getName()}`;
189 }
190​
191 return truncateInline(declaration.getText());
193​
194function getLocalExports(sourceFile: SourceFile): ExportDoc[] {
195 const exports: ExportDoc[] = [];
196​
197 for (const declaration of sourceFile
198 .getClasses()
199 .filter((item) => item.isExported())) {
200 exports.push({
201 name: declaration.getName() ?? "Anonymous",
202 kind: "class",
203 signature: signatureForDeclaration(declaration),
204 summary: getSummary(declaration),
205 });
206 }
207​
208 for (const declaration of sourceFile
209 .getFunctions()
210 .filter((item) => item.isExported())) {
211 exports.push({
212 name: declaration.getName() ?? "anonymous",
213 kind: "function",
214 signature: signatureForDeclaration(declaration),
215 summary: getSummary(declaration),
216 });
217 }
218​
219 for (const declaration of sourceFile
220 .getInterfaces()
221 .filter((item) => item.isExported())) {
222 exports.push({
223 name: declaration.getName(),
224 kind: "interface",
225 signature: signatureForDeclaration(declaration),
226 summary: getSummary(declaration),
227 shape: getShapeFromDeclaration(declaration.getName(), declaration),
228 });
229 }
230​
231 for (const declaration of sourceFile
232 .getTypeAliases()
233 .filter((item) => item.isExported())) {
234 exports.push({
235 name: declaration.getName(),
236 kind: "type",
237 signature: signatureForDeclaration(declaration),
238 summary: getSummary(declaration),
239 shape: getShapeFromDeclaration(declaration.getName(), declaration),
240 });
241 }
242​
243 for (const declaration of sourceFile
244 .getVariableDeclarations()
245 .filter((item) => item.isExported())) {
246 exports.push({
247 name: declaration.getName(),
248 kind: "const",
249 signature: signatureForDeclaration(declaration),
250 summary: getSummary(declaration.getVariableStatement() ?? declaration),
251 });
252 }
253​
254 for (const declaration of sourceFile
255 .getEnums()
256 .filter((item) => item.isExported())) {
257 exports.push({
258 name: declaration.getName(),
259 kind: "enum",
260 signature: signatureForDeclaration(declaration),
261 summary: getSummary(declaration),
262 });
263 }
264​
265 for (const declaration of sourceFile
266 .getModules()
267 .filter((item) => item.isExported())) {
268 exports.push({
269 name: declaration.getName(),
270 kind: "namespace",
271 signature: signatureForDeclaration(declaration),
272 summary: getSummary(declaration),
273 });
274 }
275​
276 const seen = new Set<string>();
277 return exports
278 .filter((entry) => {
279 const key = `${entry.kind}:${entry.name}`;
280 if (seen.has(key)) {
281 return false;
282 }
283 seen.add(key);
284 return true;
285 })
286 .sort((left, right) => left.name.localeCompare(right.name));
288​
289function getLifecycleOperations(sourceFile: SourceFile, resourceName: string) {
290 const provider = getProviderDeclaration(sourceFile, resourceName);
291 if (!provider) {
292 return [];
293 }
294 const text = provider.getText();
295 return lifecycleOperationOrder.filter((name) =>
296 new RegExp(`\\b${name}\\s*:`).test(text),
297 );
299​
300function getResourceDoc(sourceFile: SourceFile, fileKind: FileKind) {
301 const details = getResourceTypeDetails(
302 sourceFile,
303 fileKind === "host" ? "Host" : "Resource",
304 );
305 if (!details) {
306 return undefined;
307 }
308​
309 const resourceInterface = sourceFile.getInterface(details.name);
310 const props =
311 sourceFile.getInterface(`${details.name}Props`) ??
312 sourceFile.getTypeAlias(`${details.name}Props`);
313​
314 let attributes: ShapeDoc | undefined;
315 let binding: ShapeDoc | undefined;
316​
317 if (resourceInterface) {
318 const resourceHeritage = resourceInterface
319 .getHeritageClauses()
320 .flatMap((clause) => clause.getTypeNodes())
321 .find((typeNode) => typeNode.getExpression().getText() === "Resource");
322​
323 if (resourceHeritage) {
324 const typeArguments = resourceHeritage.getTypeArguments();
325 const attrsNode = typeArguments[2];
326 const bindingNode = typeArguments[3];
327 if (attrsNode) {
328 attributes = getShapeFromTypeNode(
329 `${details.name} Attributes`,
330 attrsNode,
331 );
332 }
333 if (bindingNode) {
334 binding = getShapeFromTypeNode(
335 `${details.name} Binding Contract`,
336 bindingNode,
337 );
338 }
339 }
340 }
341​
342 const resourceDoc: ResourceDoc = {
343 name: details.name,
344 resourceType: details.resourceType,
345 props: props
346 ? getShapeFromDeclaration(`${details.name} Props`, props)
347 : undefined,
348 attributes,
349 binding,
350 lifecycleOperations: getLifecycleOperations(sourceFile, details.name),
351 providerName: getProviderDeclaration(sourceFile, details.name)?.getName(),
352 };
353​
354 return resourceDoc;
356​
357function getBindingIdentifier(declaration: ClassDeclaration) {
358 const text = declaration.getText();
359 return text.match(/\)\("([^"]+)"\)/)?.[1];
361​
362function bindingDocForClass(declaration: ClassDeclaration): BindingClassDoc {
363 return {
364 name: declaration.getName() ?? "Anonymous",
365 identifier: getBindingIdentifier(declaration),
366 signature: signatureForDeclaration(declaration),
367 summary: getSummary(declaration),
368 };
370​
371function getRequestShapes(sourceFile: SourceFile) {
372 return [
373 ...sourceFile
374 .getInterfaces()
375 .filter(
376 (item) =>
377 item.isExported() &&
378 /Request|Props|Options|Input$/.test(item.getName()),
379 ),
380 ...sourceFile
381 .getTypeAliases()
382 .filter(
383 (item) =>
384 item.isExported() &&
385 /Request|Props|Options|Input$/.test(item.getName()),
386 ),
387 ]
388 .map((declaration) =>
389 getShapeFromDeclaration(declaration.getName(), declaration),
390 )
391 .filter((shape): shape is ShapeDoc => shape !== undefined)
392 .sort((left, right) => left.title.localeCompare(right.title));
394​
395function getSupportedHosts(sourceFile: SourceFile) {
396 const hosts = new Set<string>();
397 const text = sourceFile.getText();
398 if (text.includes("isFunction(host)")) {
399 hosts.add("AWS.Lambda.Function");
400 }
401 if (text.includes("isWorker(host)")) {
402 hosts.add("Cloudflare.Workers.Worker");
403 }
404 return [...hosts].sort();
406​
407function parameterToUsage(parameter: ParameterDeclaration) {
408 return {
409 name: parameter.getName(),
410 type: formatTypeText(
411 parameter.getTypeNode()?.getText() ??
412 parameter.getType().getText(parameter),
413 ),
414 optional: parameter.isOptional(),
415 rest: parameter.isRestParameter(),
416 };
418​
419function getOperationUsage(
420 sourceFile: SourceFile,
421 serviceName: string | undefined,
422) {
423 if (!serviceName) {
424 return undefined;
425 }
426​
427 const live = sourceFile.getVariableDeclaration(`${serviceName}Live`);
428 const initializer = live?.getInitializer();
429 if (!initializer) {
430 return undefined;
431 }
432​
433 const effectFns = initializer
434 .getDescendantsOfKind(SyntaxKind.CallExpression)
435 .filter((call) => call.getExpression().getText() === "Effect.fn");
436​
437 const [bindFn, invokeFn] = effectFns.map((call) => {
438 const firstArg = call.getArguments()[0];
439 if (
440 firstArg &&
441 (Node.isFunctionExpression(firstArg) || Node.isArrowFunction(firstArg))
442 ) {
443 return firstArg;
444 }
445 return undefined;
446 });
447​
448 if (!bindFn && !invokeFn) {
449 return undefined;
450 }
451​
452 return {
453 bindParameters: bindFn?.getParameters().map(parameterToUsage) ?? [],
454 invokeParameters: invokeFn?.getParameters().map(parameterToUsage) ?? [],
455 };
457​
458function getOperationDoc(sourceFile: SourceFile): OperationDoc | undefined {
459 const services = getBindingServiceClasses(sourceFile).map(bindingDocForClass);
460 const policies = getBindingPolicyClasses(sourceFile).map(bindingDocForClass);
461 const runtimeLayers = sourceFile
462 .getVariableDeclarations()
463 .filter(
464 (declaration) =>
465 declaration.isExported() &&
466 /Live$/.test(declaration.getName()) &&
467 declaration.getInitializer()?.getText().includes("Layer.") === true,
468 )
469 .map((declaration) => declaration.getName())
470 .sort();
471 const requestShapes = getRequestShapes(sourceFile);
472​
473 if (
474 services.length === 0 &&
475 policies.length === 0 &&
476 runtimeLayers.length === 0 &&
477 requestShapes.length === 0
478 ) {
479 return undefined;
480 }
481​
482 return {
483 services,
484 policies,
485 runtimeLayers,
486 supportedHosts: getSupportedHosts(sourceFile),
487 requestShapes,
488 usage: getOperationUsage(sourceFile, services[0]?.name),
489 };
491​
492function getIndexDoc(sourceFile: SourceFile, outputPath: string) {
493 return {
494 reExports: sourceFile
495 .getExportDeclarations()
496 .flatMap((declaration) => {
497 const moduleSpecifier = declaration.getModuleSpecifierValue();
498 if (!moduleSpecifier) {
499 return [];
500 }
501 const target = declaration.getModuleSpecifierSourceFile();
502 const href = target
503 ? relativeDocLink(
504 outputPath,
505 path.join(
506 docsRoot,
507 path
508 .relative(srcRoot, target.getFilePath())
509 .replace(/\.ts$/, ".md"),
510 ),
511 )
512 : undefined;
513 const namespaceExport = declaration.getNamespaceExport();
514 const exportNames =
515 declaration.getNamedExports().length > 0
516 ? declaration.getNamedExports().map((item) => item.getName())
517 : namespaceExport
518 ? [namespaceExport.getName()]
519 : ["*"];
520​
521 return exportNames.map((exportName) => ({
522 exportName,
523 sourcePath: moduleSpecifier,
524 href,
525 }));
526 })
527 .sort((left, right) =>
528 `${left.exportName}:${left.sourcePath}`.localeCompare(
529 `${right.exportName}:${right.sourcePath}`,
530 ),
531 ),
532 };
534​
535function getProviderDoc(sourceFile: SourceFile) {
536 const exportedFactories = sourceFile
537 .getVariableDeclarations()
538 .filter((declaration) => declaration.isExported())
539 .map((declaration) => declaration.getName())
540 .filter(
541 (name) =>
542 [
543 "providers",
544 "resources",
545 "bindings",
546 "credentials",
547 "stageConfig",
548 ].includes(name) || /Provider/.test(name),
549 )
550 .sort();
551​
552 return exportedFactories.length > 0 ? { exportedFactories } : undefined;
554​
555function buildRelatedLinks(
556 sourceFile: SourceFile,
557 outputPath: string,
558): LinkDoc[] {
559 const links = new Map<string, LinkDoc>();
560​
561 const maybeAdd = (target: SourceFile | undefined, label: string) => {
562 if (!target || !target.getFilePath().startsWith(srcRoot)) {
563 return;
564 }
565 const relativeTargetPath = path.relative(srcRoot, target.getFilePath());
566 const href = relativeDocLink(
567 outputPath,
568 path.join(docsRoot, relativeTargetPath.replace(/\.ts$/, ".md")),
569 );
570 links.set(`${label}:${href}`, {
571 label:
572 path.basename(relativeTargetPath, ".ts") === "index"
573 ? path.basename(path.dirname(relativeTargetPath))
574 : label,
575 href,
576 });
577 };
578​
579 for (const declaration of sourceFile.getImportDeclarations()) {
580 maybeAdd(
581 declaration.getModuleSpecifierSourceFile(),
582 path.basename(declaration.getModuleSpecifierValue(), ".ts"),
583 );
584 }
585​
586 for (const declaration of sourceFile.getExportDeclarations()) {
587 const moduleSpecifier = declaration.getModuleSpecifierValue() ?? "index.ts";
588 maybeAdd(
589 declaration.getModuleSpecifierSourceFile(),
590 path.basename(moduleSpecifier, ".ts"),
591 );
592 }
593​
594 return [...links.values()].sort((left, right) =>
595 left.label.localeCompare(right.label),
596 );
598​
599function buildDirectoryCatalog(
600 entry: SourceEntry,
601 entries: SourceEntry[],
602): DirectoryCatalog {
603 const directory = path.dirname(entry.relativePath);
604 const isIndexPage = path.basename(entry.relativePath) === "index.ts";
605 const parent = !isIndexPage
606 ? {
607 label: directory === "." ? "API Reference" : path.basename(directory),
608 href: relativeDocLink(
609 entry.outputPath,
610 path.join(
611 docsRoot,
612 directory === "." ? "index.md" : directory,
613 "index.md",
614 ),
615 ),
616 }
617 : directory === "."
618 ? undefined
619 : {
620 label:
621 path.dirname(directory) === "."
622 ? "API Reference"
623 : path.basename(path.dirname(directory)),
624 href: relativeDocLink(
625 entry.outputPath,
626 path.join(
627 docsRoot,
628 path.dirname(directory) === "."
629 ? "index.md"
630 : path.dirname(directory),
631 "index.md",
632 ),
633 ),
634 };
635​
636 const siblings = entries
637 .filter(
638 (candidate) =>
639 path.dirname(candidate.relativePath) === directory &&
640 candidate.relativePath !== entry.relativePath,
641 )
642 .map((candidate) => ({
643 label: labelFromDocRelativePath(candidate.relativePath),
644 href: relativeDocLink(entry.outputPath, candidate.outputPath),
645 }))
646 .sort((left, right) => left.label.localeCompare(right.label));
647​
648 return { parent, siblings };
650​
651function buildSummary(sourceFile: SourceFile, fileKind: FileKind) {
652 const primaryNode = getPrimaryNode(sourceFile, fileKind);
653 const summary = primaryNode ? getSummary(primaryNode) : undefined;
654 if (summary) {
655 return summary;
656 }
657 return "";
659​
660function singularize(name: string) {
661 return name.endsWith("ies")
662 ? `${name.slice(0, -3)}y`
663 : name.endsWith("ses")
664 ? name.slice(0, -2)
665 : name.endsWith("s") && name.length > 1
666 ? name.slice(0, -1)
667 : name;
669​
670function guessBindingArgument(name: string, rest: boolean) {
671 const base = rest ? singularize(name) : name;
672 return lowerCamel(base || "resource");
674​
675function buildRequestBlock(shape: ShapeDoc | undefined) {
676 if (!shape) {
677 return "{\n // request fields\n}";
678 }
679​
680 const required = shape.properties.filter((property) => !property.optional);
681 const properties = (required.length > 0 ? required : shape.properties).slice(
682 0,
683 4,
684 );
685​
686 if (properties.length === 0) {
687 return "{}";
688 }
689​
690 return `{\n${properties
691 .map((property) => ` ${property.name}: ${guessExampleValue(property)},`)
692 .join("\n")}\n}`;
694​
695function buildAutoExample(
696 fileKind: FileKind,
697 title: string,
698 resource?: ResourceDoc,
699 operation?: OperationDoc,
700) {
701 if (fileKind === "resource" || fileKind === "host") {
702 const required = (resource?.props?.properties ?? []).filter(
703 (property) => !property.optional,
704 );
705 const propsBlock =
706 required.length === 0
707 ? "{}"
708 : `{\n${required
709 .map(
710 (property) =>
711 ` ${property.name}: ${guessExampleValue(property)},`,
712 )
713 .join("\n")}\n}`;
714 return {
715 title: `Create ${title}`,
716 body: [
717 "```typescript",
718 `const ${lowerCamel(title)} = yield* ${title}("${title}", ${propsBlock});`,
719 "```",
720 ].join("\n"),
721 };
722 }
723​
724 if (fileKind === "operation") {
725 const service = operation?.services[0]?.name ?? title;
726 const bindArguments =
727 operation?.usage?.bindParameters.map((parameter) =>
728 guessBindingArgument(parameter.name, parameter.rest),
729 ) ?? [];
730 const bindCall =
731 bindArguments.length > 0
732 ? `.bind(${bindArguments.join(", ")})`
733 : ".bind()";
734 const invokeParameter = operation?.usage?.invokeParameters[0];
735 const requestShape = operation?.requestShapes[0];
736 const invocation = invokeParameter
737 ? invokeParameter.optional
738 ? `const response = yield* ${lowerCamel(service)}();`
739 : `const response = yield* ${lowerCamel(service)}(${buildRequestBlock(requestShape)});`
740 : `const response = yield* ${lowerCamel(service)}();`;
741​
742 return {
743 title: `Use ${service}`,
744 body: [
745 "```typescript",
746 `const ${lowerCamel(service)} = yield* ${service}${bindCall};`,
747 "",
748 invocation,
749 "```",
750 ].join("\n"),
751 };
752 }
753​
754 if (fileKind === "event-source") {
755 return {
756 title: `Attach ${title}`,
757 body: [
758 "```typescript",
759 `yield* ${title}.bind(resource, {}, (events) =>`,
760 " Effect.log(events),",
761 ");",
762 "```",
763 ].join("\n"),
764 };
765 }
766​
767 return undefined;
769​
770export function buildFileDoc(
771 project: import("ts-morph").Project,
772 entry: SourceEntry,
773 entries: SourceEntry[],
774): FileDoc {
775 const sourceFile = project.getSourceFileOrThrow(entry.sourcePath);
776 const fileKind = getFileKind(sourceFile);
777 const title = titleFromRelativePath(entry.relativePath);
778 const examples = (() => {
779 const primaryNode = getPrimaryNode(sourceFile, fileKind);
780 return primaryNode ? getJSDocInfo(primaryNode).sections : [];
781 })();
782 const resource =
783 fileKind === "resource" || fileKind === "host"
784 ? getResourceDoc(sourceFile, fileKind)
785 : undefined;
786 const operation =
787 fileKind === "operation" || fileKind === "event-source"
788 ? getOperationDoc(sourceFile)
789 : undefined;
790​
791 return {
792 title,
793 fileKind,
794 summary: buildSummary(sourceFile, fileKind),
795 sourcePath: relativeSourcePath(sourceFile.getFilePath()),
796 relativePath: entry.relativePath,
797 outputPath: entry.outputPath,
798 exports: getLocalExports(sourceFile),
799 resource,
800 operation,
801 index:
802 fileKind === "index"
803 ? getIndexDoc(sourceFile, entry.outputPath)
804 : undefined,
805 provider: fileKind === "provider" ? getProviderDoc(sourceFile) : undefined,
806 examples,
807 autoExample:
808 examples.length === 0
809 ? buildAutoExample(fileKind, title, resource, operation)
810 : undefined,
811 relatedLinks: buildRelatedLinks(sourceFile, entry.outputPath),
812 directoryCatalog: buildDirectoryCatalog(entry, entries),
813 };