Skip to content

Commit

Permalink
chore: better Typescript types (#9480)
Browse files Browse the repository at this point in the history
* fix doc type

* improve frontmatter types

* add types to files.ts

* get rid of `any`s from docPage

* add types to JsBundleListClient

* add TS types to utils.ts

* fix dynamicNav types

* let the inferred type shine

* add proper types to CodeKeywords

* add TS to apiExamples

* add TS type to sidebar

* add TS types to serverSidebar

* add TS types to expandable

* add TS types to PlatformContent component

* add TS types to cliChecksumTableClient

* add proper TS types to changelog/list

* add proper doc TS type to Include component

* improte TS types for Alert component

* imropve resolveOpenAPI types

* fix type import 🙊

* add missing sidebar_title front matter property

* fix TS errors on [[...path]]/page.tsx

* fix TS errors in *sidebar.tsx

* fix TS errors on apiPage

* fix TS errors on docTree

* narrow down some anys on docTree

* move remark-component-spacing plugin to TS

* move remark-toc-headings plugin to TS

* move remark-extract-frontmatter plugin to TS
  • Loading branch information
a-hariti authored Mar 22, 2024
1 parent c77bf5d commit 81d291c
Show file tree
Hide file tree
Showing 27 changed files with 256 additions and 117 deletions.
6 changes: 3 additions & 3 deletions app/[[...path]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {capitilize} from 'sentry-docs/utils';

export async function generateStaticParams() {
const docs = await getDocsFrontMatter();
const paths = docs.map(doc => {
const paths: {path: string[] | undefined}[] = docs.map(doc => {
const path = doc.slug.split('/');
return {path};
});
Expand Down Expand Up @@ -83,7 +83,7 @@ export default async function Page({params}) {
}

// get the MDX for the current doc and render it
let doc: any = null;
let doc: Awaited<ReturnType<typeof getFileBySlug>> | null = null;
try {
doc = await getFileBySlug(`docs/${pageNode.path}`);
} catch (e) {
Expand Down Expand Up @@ -128,7 +128,7 @@ export async function generateMetadata({params}: MetadataProps): Promise<Metadat
title =
pageNode.frontmatter.title +
(guideOrPlatform ? ` | Sentry for ${capitilize(guideOrPlatform.name)}` : '');
description = pageNode.frontmatter.description;
description = pageNode.frontmatter.description ?? '';
}
}

Expand Down
24 changes: 21 additions & 3 deletions src/build/resolveOpenAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,32 @@ export type APIParameter = {
};
};

type APIExample = {
summary: string;
value: any;
};

type APIResponse = {
description: string;
status_code: string;
content?: {
content_type: string;
schema: any;
example?: APIExample;
examples?: {[key: string]: APIExample};
};
};

type APIData = DeRefedOpenAPI['paths'][string][string];

export type API = {
apiPath: string;
bodyParameters: APIParameter[];
method: string;
name: string;
pathParameters: APIParameter[];
queryParameters: APIParameter[];
responses: any;
responses: APIResponse[];
slug: string;
bodyContentType?: string;
descriptionMarkdown?: string;
Expand Down Expand Up @@ -154,7 +172,7 @@ async function apiCategoriesUncached(): Promise<APICategory[]> {
return categories;
}

function getBodyParameters(apiData): APIParameter[] {
function getBodyParameters(apiData: APIData): APIParameter[] {
const content = apiData.requestBody?.content;
const contentType = content && Object.values(content)[0];
const properties = contentType?.schema?.properties;
Expand All @@ -176,7 +194,7 @@ function getBodyParameters(apiData): APIParameter[] {
}));
}

function getBodyContentType(apiData): string | undefined {
function getBodyContentType(apiData: APIData): string | undefined {
const content = apiData.requestBody?.content;
const types = content && Object.keys(content);
if (!types?.length) {
Expand Down
6 changes: 4 additions & 2 deletions src/components/alert.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
'use client';

import {ReactNode} from 'react';

type Props = {
children?: any;
children?: ReactNode;
level?: 'info' | 'warning' | 'danger' | 'success' | '';
title?: string;
};
Expand All @@ -11,7 +13,7 @@ export function Alert({title, children, level}: Props) {
if (level) {
className += ` alert-${level}`;
}
if (children.props && typeof children.props.children === 'string') {
if (children && typeof children === 'string') {
className += ' markdown-text-only';
}
return (
Expand Down
22 changes: 12 additions & 10 deletions src/components/apiExamples.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,18 @@ import {Fragment, useState} from 'react';

import {type API} from 'sentry-docs/build/resolveOpenAPI';

function Example(props) {
const selectedTabView: number = props.selectedTabView;
const api: API = props.api;
const selectedResponse: number = props.selectedResponse;
type ExampleProps = {
api: API;
selectedResponse: number;
selectedTabView: number;
};

let exampleJson;
function Example({api, selectedTabView, selectedResponse}: ExampleProps) {
let exampleJson: any;
if (api.responses[selectedResponse].content?.examples) {
exampleJson = Object.values(api.responses[selectedResponse].content?.examples).map(
(e: any) => e.value
)[0];
exampleJson = Object.values(
api.responses[selectedResponse].content?.examples ?? {}
).map(e => e.value)[0];
} else if (api.responses[selectedResponse].content?.example) {
exampleJson = api.responses[selectedResponse].content?.example;
}
Expand All @@ -43,7 +45,7 @@ function Example(props) {
<code
dangerouslySetInnerHTML={{
__html: Prism.highlight(
JSON.stringify(api.responses[selectedResponse].content.schema, null, 2),
JSON.stringify(api.responses[selectedResponse].content?.schema, null, 2),
Prism.languages.json,
'json'
),
Expand All @@ -54,7 +56,7 @@ function Example(props) {
);
}

const strFormat = str => {
const strFormat = (str: string) => {
const s = str.trim();
if (s.endsWith('.')) {
return s;
Expand Down
7 changes: 4 additions & 3 deletions src/components/changelog/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,16 @@ export default function Changelogs({
});

// iterate over all posts and create a list of months & years
const months = changelogs.reduce((allMonths: any, post: any) => {
const date = new Date(post.publishedAt) as Date;
const months = changelogs.reduce((allMonths, post) => {
// if no date is set, use the epoch (simulate behavior before this refactor)
const date = post.publishedAt ?? new Date(0);
const year = date.getFullYear();
const month = date.toLocaleString('default', {
month: 'long',
});
const dateMonthYear = `${month} ${year}`;
return [...new Set([...allMonths, dateMonthYear])];
}, []);
}, [] as string[]);

const monthsCopy = [...months];

Expand Down
12 changes: 10 additions & 2 deletions src/components/cliChecksumTableClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@ const ChecksumValue = styled.code`
white-space: nowrap;
`;

export type Files = {
checksums: {
name: string;
value: string;
}[];
name: string;
};

type Props = {
files: any[];
files: Files[];
version: string;
};

Expand Down Expand Up @@ -37,7 +45,7 @@ export function CliChecksumTableClient({version, files}: Props) {
</td>
<td style={{verticalAlign: 'middle', width: '100%'}}>
<ChecksumValue>
{`sha384-${file.checksums.find(c => c.name === 'sha256-hex').value}`}
{`sha384-${file.checksums.find(c => c.name === 'sha256-hex')?.value}`}
</ChecksumValue>
</td>
</tr>
Expand Down
4 changes: 2 additions & 2 deletions src/components/codeKeywords.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ function runRegex(
arr: ChildrenItem[],
str: string,
regex: RegExp,
cb: (lastIndex: number, match: any[]) => React.ReactNode
cb: (lastIndex: number, match: RegExpExecArray) => React.ReactNode
): void {
regex.lastIndex = 0;

let match;
let match: RegExpExecArray | null;
let lastIndex = 0;
// eslint-disable-next-line no-cond-assign
while ((match = regex.exec(str)) !== null) {
Expand Down
5 changes: 3 additions & 2 deletions src/components/docPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {ReactNode} from 'react';

import {getCurrentPlatformOrGuide} from 'sentry-docs/docTree';
import {serverContext} from 'sentry-docs/serverContext';
import {FrontMatter} from 'sentry-docs/types';

import {Breadcrumbs} from './breadcrumbs';
import {CodeContextProvider} from './codeContext';
Expand All @@ -15,8 +16,8 @@ import {ServerSidebar} from './serverSidebar';
import {TableOfContents} from './tableOfContents';

type Props = {
children: any;
frontMatter: any;
children: ReactNode;
frontMatter: Omit<FrontMatter, 'slug'>;
notoc?: boolean;
sidebar?: ReactNode;
};
Expand Down
14 changes: 9 additions & 5 deletions src/components/dynamicNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ type Node = {
[key: string]: any;
context: {
[key: string]: any;
sidebar_order?: number | null;
sidebar_title?: string | null;
title?: string | null;
sidebar_order?: number;
sidebar_title?: string;
title?: string;
};
path: string;
};
Expand Down Expand Up @@ -64,13 +64,17 @@ export const renderChildren = (
({name, node}) =>
node && !!node.context.title && name !== '' && exclude.indexOf(node.path) === -1
),
({node}) => node
({node}) => node!
).map(({node, children: nodeChildren}) => {
// will not be null because of the filter above
if (!node) {
return null;
}
return (
<SidebarLink
to={node.path}
key={node.path}
title={node.context.sidebar_title || node.context.title}
title={node.context.sidebar_title || node.context.title!}
collapsed={depth >= showDepth}
path={path}
>
Expand Down
4 changes: 2 additions & 2 deletions src/components/expandable.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use client';

import {useState} from 'react';
import {ReactNode, useState} from 'react';
import {ArrowDown} from 'react-feather';
import styled from '@emotion/styled';

type Props = {
children: any;
children: ReactNode;
title: string;
};

Expand Down
2 changes: 1 addition & 1 deletion src/components/include.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Props = {
};

export async function Include({name}: Props) {
let doc: any = null;
let doc: Awaited<ReturnType<typeof getFileBySlug>> | null = null;
if (name.endsWith('.mdx')) {
name = name.slice(0, name.length - '.mdx'.length);
}
Expand Down
16 changes: 14 additions & 2 deletions src/components/jsBundleListClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,19 @@ const ChecksumValue = styled.code`
white-space: nowrap;
`;

export function JsBundleListClient({files}: {files: any[]}) {
type File = {
checksums: {
name: string;
value: string;
}[];
name: string;
};

type Props = {
files: File[];
};

export function JsBundleListClient({files}: Props) {
return (
<table style={{display: 'block', overflow: 'scroll'}}>
<thead>
Expand All @@ -32,7 +44,7 @@ export function JsBundleListClient({files}: {files: any[]}) {
</td>
<td style={{verticalAlign: 'middle', width: '100%'}}>
<ChecksumValue>
{`sha384-${file.checksums.find(c => c.name === 'sha384-base64').value}`}
{`sha384-${file.checksums.find(c => c.name === 'sha384-base64')?.value}`}
</ChecksumValue>
</td>
</tr>
Expand Down
2 changes: 1 addition & 1 deletion src/components/platformContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function PlatformContent({includePath, platform, noGuides}: Props)
guide = `${platform}.${path[3]}`;
}

let doc: any = null;
let doc: Awaited<ReturnType<typeof getFileBySlug>> | null = null;
if (guide) {
try {
doc = await getFileBySlug(`platform-includes/${includePath}/${guide}`);
Expand Down
2 changes: 1 addition & 1 deletion src/components/platformSdkPackageName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function PlatformSdkPackageName({fallback}: PlatformSdkPackageNameP
const packageRegistry = await getPackageRegistry();
const allSdks = packageRegistry.data;
const entries = Object.entries(allSdks || {});
const pair: any = entries.find(([sdkName]) => sdkName === platformOrGuide.sdk);
const pair = entries.find(([sdkName]) => sdkName === platformOrGuide.sdk);
if (!pair) {
return <code>{fallbackName} </code>;
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/productSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import {SidebarLink} from './sidebarLink';
export type NavNode = {
context: {
draft: boolean;
sidebar_order: number;
title: string;
sidebar_order?: number;
sidebar_title?: string;
};
path: string;
Expand Down
6 changes: 3 additions & 3 deletions src/components/serverSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function productSidebar(rootNode: DocNode) {
const nodes: NavNode[] = [
{
context: {
draft: productNode.frontmatter.draft,
draft: Boolean(productNode.frontmatter.draft),
title: productNode.frontmatter.title,
sidebar_order: productNode.frontmatter.sidebar_order,
sidebar_title: productNode.frontmatter.sidebar_title,
Expand All @@ -27,7 +27,7 @@ export function productSidebar(rootNode: DocNode) {
docNodes.forEach(n => {
nodes.push({
context: {
draft: n.frontmatter.draft,
draft: Boolean(n.frontmatter.draft),
title: n.frontmatter.title,
sidebar_order: n.frontmatter.sidebar_order,
sidebar_title: n.frontmatter.sidebar_title,
Expand Down Expand Up @@ -142,7 +142,7 @@ export function ServerSidebar() {
const nodeToSidebarNode = (n: DocNode): SidebarNode => {
return {
path: n.path,
frontmatter: n.frontmatter as {[key: string]: any},
frontmatter: n.frontmatter,
children: n.children.map(nodeToSidebarNode),
};
};
Expand Down
6 changes: 4 additions & 2 deletions src/components/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import {Fragment} from 'react';
import styled from '@emotion/styled';
import Link from 'next/link';

import {FrontMatter} from 'sentry-docs/types';

export type SidebarNode = {
children: SidebarNode[];
frontmatter: {[key: string]: any};
frontmatter: FrontMatter;
path: string;
};

Expand All @@ -21,7 +23,7 @@ export function Sidebar({node, path}: Props) {
return `${baseClassName} ${className}`;
};

const renderChildren = children =>
const renderChildren = (children: SidebarNode[]) =>
children && (
<ul className="list-unstyled" data-sidebar-tree>
{children.map(n => (
Expand Down
Loading

0 comments on commit 81d291c

Please sign in to comment.