Clean up, simplify types (#1816)

Also add JSDoc to external types
This commit is contained in:
Drew Powers 2021-11-16 14:00:08 -07:00 committed by GitHub
parent 3cd1458aa7
commit c8544a2651
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 166 additions and 186 deletions

View file

@ -4,7 +4,7 @@
"author": "Skypack",
"license": "MIT",
"type": "module",
"types": "./dist/types/@types/astro-core.d.ts",
"types": "./dist/types/@types/astro.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/snowpackjs/astro.git",

View file

@ -1,64 +0,0 @@
import type { Renderer } from './astro-core';
export interface AstroBuiltinProps {
'client:load'?: boolean;
'client:idle'?: boolean;
'client:media'?: string;
'client:visible'?: boolean;
}
export interface AstroGlobal extends TopLevelAstro {
props: Record<string, number | string | any>;
request: AstroPageRequest;
slots: Record<string, true | undefined>;
}
interface AstroPageRequest {
url: URL;
canonicalURL: URL;
params: Params;
}
type AstroRenderedHTML = string;
export type FetchContentResultBase = {
astro: {
headers: string[];
source: string;
html: AstroRenderedHTML;
};
url: URL;
};
export type FetchContentResult<T> = FetchContentResultBase & T;
export interface HydrateOptions {
value?: string;
}
export type GetHydrateCallback = () => Promise<(element: Element, innerHTML: string | null) => void>;
export type Params = Record<string, string | undefined>;
export interface TopLevelAstro {
fetchContent<T = any>(globStr: string): Promise<FetchContentResult<T>[]>;
resolve: (path: string) => string;
site: URL;
}
export interface SSRMetadata {
renderers: Renderer[];
pathname: string;
}
export interface SSRResult {
styles: Set<SSRElement>;
scripts: Set<SSRElement>;
createAstro(Astro: TopLevelAstro, props: Record<string, any>, slots: Record<string, any> | null): AstroGlobal;
_metadata: SSRMetadata;
}
export interface SSRElement {
props: Record<string, any>;
children: string;
}

View file

@ -2,7 +2,14 @@ import type babel from '@babel/core';
import type { z } from 'zod';
import type { AstroConfigSchema } from '../core/config';
import type { AstroComponentFactory, Metadata } from '../runtime/server';
import type vite from '../../vendor/vite';
import type vite from '../core/vite';
export interface AstroBuiltinProps {
'client:load'?: boolean;
'client:idle'?: boolean;
'client:media'?: string;
'client:visible'?: boolean;
}
export interface AstroComponentMetadata {
displayName: string;
@ -13,8 +20,34 @@ export interface AstroComponentMetadata {
}
/**
* The Astro User Config Format:
* This is the type interface for your astro.config.mjs default export.
* Astro.* available in all components
* Docs: https://docs.astro.build/reference/api-reference/#astro-global
*/
export interface AstroGlobal extends AstroGlobalPartial {
/** set props for this astro component (along with default values) */
props: Record<string, number | string | any>;
/** get information about this page */
request: {
/** get the current page URL */
url: URL;
/** get the current canonical URL */
canonicalURL: URL;
/** get page params (dynamic pages only) */
params: Params;
};
/** see if slots are used */
slots: Record<string, true | undefined>;
}
export interface AstroGlobalPartial {
fetchContent<T = any>(globStr: string): Promise<FetchContentResult<T>[]>;
resolve: (path: string) => string;
site: URL;
}
/**
* Astro User Config
* Docs: https://docs.astro.build/reference/configuration-reference/
*/
export interface AstroUserConfig {
/**
@ -103,40 +136,14 @@ export interface AstroUserConfig {
// export interface AstroUserConfig extends z.input<typeof AstroConfigSchema> {
// }
/**
* Resolved Astro Config
* Config with user settings along with all defaults filled in.
*/
export type AstroConfig = z.output<typeof AstroConfigSchema>;
export type AsyncRendererComponentFn<U> = (Component: any, props: any, children: string | undefined, metadata?: AstroComponentMetadata) => Promise<U>;
export interface CollectionRSS {
/** (required) Title of the RSS Feed */
title: string;
/** (required) Description of the RSS Feed */
description: string;
/** Specify arbitrary metadata on opening <xml> tag */
xmlns?: Record<string, string>;
/** Specify custom data in opening of file */
customData?: string;
/**
* Specify where the RSS xml file should be written.
* Relative to final build directory. Example: '/foo/bar.xml'
* Defaults to '/rss.xml'.
*/
dest?: string;
/** Return data about each item */
items: {
/** (required) Title of item */
title: string;
/** (required) Link to item */
link: string;
/** Publication date of item */
pubDate?: Date;
/** Item description */
description?: string;
/** Append some other XML-valid data to this item */
customData?: string;
}[];
}
/** Generic interface for a component (Astro, Svelte, React, etc.) */
export interface ComponentInstance {
$$metadata: Metadata;
@ -145,14 +152,36 @@ export interface ComponentInstance {
getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult;
}
export type GetStaticPathsArgs = { paginate: PaginateFunction; rss: RSSFunction };
/**
* Astro.fetchContent() result
* Docs: https://docs.astro.build/reference/api-reference/#astrofetchcontent
*/
export type FetchContentResult<T> = FetchContentResultBase & T;
export interface GetStaticPathsOptions {
export type FetchContentResultBase = {
astro: {
headers: string[];
source: string;
html: string;
};
url: URL;
};
export type GetHydrateCallback = () => Promise<(element: Element, innerHTML: string | null) => void>;
/**
* getStaticPaths() options
* Docs: https://docs.astro.build/reference/api-reference/#getstaticpaths
*/ export interface GetStaticPathsOptions {
paginate?: PaginateFunction;
rss?: (...args: any[]) => any;
}
export type GetStaticPathsResult = { params: Params; props?: Props }[] | { params: Params; props?: Props }[];
export type GetStaticPathsResult = { params: Params; props?: Props }[];
export interface HydrateOptions {
value?: string;
}
export interface JSXTransformConfig {
/** Babel presets */
@ -167,7 +196,24 @@ export interface ManifestData {
routes: RouteData[];
}
export interface PaginatedCollectionProp<T = any> {
/**
* paginate() Options
* Docs: https://docs.astro.build/guides/pagination/#calling-the-paginate-function
*/
export interface PaginateOptions {
/** the number of items per-page (default: `10`) */
pageSize?: number;
/** key: value object of page params (ex: `{ tag: 'javascript' }`) */
params?: Params;
/** object of props to forward to `page` result */
props?: Props;
}
/**
* Page Prop
* Docs: https://docs.astro.build/guides/pagination/#using-the-page-prop
*/
export interface Page<T = any> {
/** result */
data: T[];
/** metadata */
@ -193,33 +239,7 @@ export interface PaginatedCollectionProp<T = any> {
};
}
export interface PaginatedCollectionResult<T = any> {
/** result */
data: T[];
/** metadata */
/** the count of the first item on the page, starting from 0 */
start: number;
/** the count of the last item on the page, starting from 0 */
end: number;
/** total number of results */
total: number;
/** the current page number, starting from 1 */
currentPage: number;
/** number of items per page (default: 25) */
size: number;
/** number of last page */
lastPage: number;
url: {
/** url of the current page */
current: string;
/** url of the previous page (if there is one) */
prev: string | undefined;
/** url of the next page (if there is one) */
next: string | undefined;
};
}
export type PaginateFunction = (data: [], args?: { pageSize?: number; params?: Params; props?: Props }) => GetStaticPathsResult;
export type PaginateFunction = (data: [], args?: PaginateOptions) => GetStaticPathsResult;
export type Params = Record<string, string | undefined>;
@ -236,6 +256,10 @@ export interface RenderPageOptions {
css?: string[];
}
/**
* Astro Renderer
* Docs: https://docs.astro.build/reference/renderer-reference/
*/
export interface Renderer {
/** Name of the renderer (required) */
name: string;
@ -264,9 +288,6 @@ export interface Renderer {
knownEntrypoints?: string[];
}
/** <link> tags with attributes represented by an object */
export type Resource = Record<string, string>;
export interface RouteData {
component: string;
generate: (data?: any) => string;
@ -280,9 +301,11 @@ export type RouteCache = Record<string, GetStaticPathsResult>;
export type RuntimeMode = 'development' | 'production';
export type RSSFunction = (args: RSSFunctionArgs) => void;
export interface RSSFunctionArgs {
/**
* RSS
* Docs: https://docs.astro.build/reference/api-reference/#rss
*/
export interface RSS {
/** (required) Title of the RSS Feed */
title: string;
/** (required) Description of the RSS Feed */
@ -312,16 +335,25 @@ export interface RSSFunctionArgs {
}[];
}
export type RSSResult = { url: string; xml?: string };
export type RSSFunction = (args: RSS) => void;
export type ScriptInfo = ScriptInfoInline | ScriptInfoExternal;
export type RSSResult = { url: string; xml?: string };
export type SSRError = Error & vite.ErrorPayload['err'];
export interface ScriptInfoInline {
content: string;
export interface SSRElement {
props: Record<string, any>;
children: string;
}
export interface ScriptInfoExternal {
src: string;
export interface SSRMetadata {
renderers: Renderer[];
pathname: string;
}
export interface SSRResult {
styles: Set<SSRElement>;
scripts: Set<SSRElement>;
createAstro(Astro: AstroGlobalPartial, props: Record<string, any>, slots: Record<string, any> | null): AstroGlobal;
_metadata: SSRMetadata;
}

View file

@ -1,6 +1,6 @@
/* eslint-disable no-console */
import { AstroCheck, DiagnosticSeverity } from '@astrojs/language-server';
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import { bold, black, bgWhite, red, cyan, yellow } from 'kleur/colors';
import glob from 'fast-glob';

View file

@ -1,7 +1,7 @@
/* eslint-disable no-console */
import type { AstroConfig } from '../@types/astro-core';
import { LogOptions } from '../core/logger.js';
import type { AstroConfig } from '../@types/astro';
import type { LogOptions } from '../core/logger';
import * as colors from 'kleur/colors';
import fs from 'fs';

View file

@ -1,4 +1,4 @@
import type { AstroConfig, ComponentInstance, GetStaticPathsResult, ManifestData, RouteCache, RouteData, RSSResult } from '../../@types/astro-core';
import type { AstroConfig, ComponentInstance, GetStaticPathsResult, ManifestData, RouteCache, RouteData, RSSResult } from '../../@types/astro';
import type { LogOptions } from '../logger';
import type { AllPagesData } from './types';
import type { RenderedChunk } from 'rollup';

View file

@ -1,5 +1,5 @@
import type { ComponentPreload } from '../ssr/index';
import type { RouteData } from '../../@types/astro-core';
import type { RouteData } from '../../@types/astro';
export interface PageBuildData {
paths: string[];

View file

@ -1,6 +1,5 @@
import type { AstroConfig, AstroUserConfig } from '../@types/astro-core';
import type { AstroConfig, AstroUserConfig } from '../@types/astro';
import { existsSync } from 'fs';
import * as colors from 'kleur/colors';
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';

View file

@ -1,4 +1,4 @@
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import type { AstroDevServer } from './dev';
import type { LogOptions } from './logger';

View file

@ -1,6 +1,6 @@
import type { NextFunction } from 'connect';
import type http from 'http';
import type { AstroConfig, ManifestData, RouteCache, RouteData } from '../../@types/astro-core';
import type { AstroConfig, ManifestData, RouteCache, RouteData } from '../../@types/astro';
import type { LogOptions } from '../logger';
import type { HmrContext, ModuleNode } from '../vite';

View file

@ -1,4 +1,4 @@
import type { AstroConfig } from '../../@types/astro-core';
import type { AstroConfig } from '../../@types/astro';
import type { LogOptions } from '../logger';
import http from 'http';

View file

@ -1,4 +1,4 @@
import type vite from '../../../vendor/vite';
import type vite from '../vite';
import { fileURLToPath } from 'url';
import path from 'path';

View file

@ -1,7 +1,21 @@
import type { BuildResult } from 'esbuild';
import type vite from '../vite';
import type { AstroConfig, ComponentInstance, GetStaticPathsResult, Params, Props, Renderer, RouteCache, RouteData, RuntimeMode, SSRError } from '../../@types/astro-core';
import type { AstroGlobal, TopLevelAstro, SSRResult, SSRElement } from '../../@types/astro-runtime';
import type {
AstroConfig,
AstroGlobal,
AstroGlobalPartial,
ComponentInstance,
GetStaticPathsResult,
Params,
Props,
Renderer,
RouteCache,
RouteData,
RuntimeMode,
SSRElement,
SSRError,
SSRResult,
} from '../../@types/astro';
import type { LogOptions } from '../logger';
import fs from 'fs';
@ -157,7 +171,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
styles: new Set<SSRElement>(),
scripts: new Set<SSRElement>(),
/** This function returns the `Astro` faux-global */
createAstro(astroGlobal: TopLevelAstro, props: Record<string, any>, slots: Record<string, any> | null) {
createAstro(astroGlobal: AstroGlobalPartial, props: Record<string, any>, slots: Record<string, any> | null) {
const site = new URL(origin);
const url = new URL('.' + pathname, site);
const canonicalURL = getCanonicalURL('.' + pathname, astroConfig.buildOptions.site || origin);

View file

@ -1,12 +1,12 @@
import { GetStaticPathsResult, PaginatedCollectionProp, PaginateFunction, Params, Props, RouteData } from '../../@types/astro-core';
import { GetStaticPathsResult, Page, PaginateFunction, Params, Props, RouteData } from '../../@types/astro';
export function generatePaginateFunction(routeMatch: RouteData): PaginateFunction {
return function paginateUtility(data: any[], args: { pageSize?: number; params?: Params; props?: Props } = {}) {
let { pageSize: _pageSize, params: _params, props: _props } = args;
const pageSize = _pageSize || 10;
const paramName = 'page';
const additoonalParams = _params || {};
const additoonalProps = _props || {};
const additionalParams = _params || {};
const additionalProps = _props || {};
let includesFirstPageNumber: boolean;
if (routeMatch.params.includes(`...${paramName}`)) {
includesFirstPageNumber = false;
@ -24,13 +24,13 @@ export function generatePaginateFunction(routeMatch: RouteData): PaginateFunctio
const start = pageSize === Infinity ? 0 : (pageNum - 1) * pageSize; // currentPage is 1-indexed
const end = Math.min(start + pageSize, data.length);
const params = {
...additoonalParams,
...additionalParams,
[paramName]: includesFirstPageNumber || pageNum > 1 ? String(pageNum) : undefined,
};
return {
params,
props: {
...additoonalProps,
...additionalProps,
page: {
data: data.slice(start, end),
start,
@ -44,7 +44,7 @@ export function generatePaginateFunction(routeMatch: RouteData): PaginateFunctio
next: pageNum === lastPage ? undefined : routeMatch.generate({ ...params, page: String(pageNum + 1) }),
prev: pageNum === 1 ? undefined : routeMatch.generate({ ...params, page: !includesFirstPageNumber && pageNum - 1 === 1 ? undefined : String(pageNum - 1) }),
},
} as PaginatedCollectionProp,
} as Page,
},
};
});

View file

@ -1,4 +1,4 @@
import type { AstroConfig, ComponentInstance, GetStaticPathsResult, ManifestData, Params, RouteData } from '../../@types/astro-core';
import type { AstroConfig, ComponentInstance, GetStaticPathsResult, ManifestData, Params, RouteData } from '../../@types/astro';
import type { LogOptions } from '../logger';
import fs from 'fs';

View file

@ -1,4 +1,4 @@
import type { RSSFunction, RSSFunctionArgs, RSSResult, RouteData } from '../../@types/astro-core';
import type { RSSFunction, RSS, RSSResult, RouteData } from '../../@types/astro';
import parser from 'fast-xml-parser';
import { canonicalURL } from '../util.js';
@ -12,7 +12,7 @@ export function validateRSS(args: GenerateRSSArgs): void {
if (!Array.isArray(rssData.items)) throw new Error(`[${srcFile}] rss.items should be an array of items`);
}
type GenerateRSSArgs = { site: string; rssData: RSSFunctionArgs; srcFile: string; feedURL: string };
type GenerateRSSArgs = { site: string; rssData: RSS; srcFile: string; feedURL: string };
/** Generate RSS 2.0 feed */
export function generateRSS(args: GenerateRSSArgs): string {

View file

@ -1,4 +1,4 @@
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import type { ErrorPayload } from 'vite';
import eol from 'eol';
import path from 'path';

View file

@ -1,4 +1,4 @@
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro-runtime';
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro';
/**
* Hydrate this component as soon as the main thread is free

View file

@ -1,4 +1,4 @@
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro-runtime';
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro';
/**
* Hydrate this component immediately

View file

@ -1,4 +1,4 @@
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro-runtime';
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro';
/**
* Hydrate this component when a matching media query is found

View file

@ -1,4 +1,4 @@
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro-runtime';
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro';
/**
* Hydrate this component immediately

View file

@ -1,4 +1,4 @@
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro-runtime';
import type { GetHydrateCallback, HydrateOptions } from '../../@types/astro';
/**
* Hydrate this component when one of it's children becomes visible.

View file

@ -1,5 +1,5 @@
import type { AstroComponentMetadata } from '../../@types/astro-core';
import type { SSRElement } from '../../@types/astro-runtime';
import type { AstroComponentMetadata } from '../../@types/astro';
import type { SSRElement } from '../../@types/astro';
import { valueToEstree } from 'estree-util-value-to-estree';
import * as astring from 'astring';
import { serializeListValue } from './util.js';

View file

@ -1,6 +1,5 @@
import type { AstroComponentMetadata, Renderer } from '../../@types/astro-core';
import type { SSRResult, SSRElement } from '../../@types/astro-runtime';
import type { TopLevelAstro } from '../../@types/astro-runtime';
import type { AstroComponentMetadata, Renderer } from '../../@types/astro';
import type { AstroGlobalPartial, SSRResult, SSRElement } from '../../@types/astro';
import shorthash from 'shorthash';
import { extractDirectives, generateHydrateScript } from './hydration.js';
@ -269,12 +268,12 @@ function createFetchContentFn(url: URL) {
// This has to be cast because the type of fetchContent is the type of the function
// that receives the import.meta.glob result, but the user is using it as
// another type.
return fetchContent as unknown as TopLevelAstro['fetchContent'];
return fetchContent as unknown as AstroGlobalPartial['fetchContent'];
}
// This is used to create the top-level Astro global; the one that you can use
// Inside of getStaticPaths.
export function createAstro(fileURLStr: string, site: string): TopLevelAstro {
export function createAstro(fileURLStr: string, site: string): AstroGlobalPartial {
const url = new URL(fileURLStr);
const fetchContent = createFetchContentFn(url);
return {

View file

@ -1,6 +1,6 @@
import type * as t from '@babel/types';
import type { Plugin } from '../core/vite';
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import type { AstroDevServer } from '../core/dev/index';
import * as babelTraverse from '@babel/traverse';

View file

@ -1,7 +1,7 @@
import type { TransformResult } from '@astrojs/compiler';
import type { SourceMapInput } from 'rollup';
import type vite from '../core/vite';
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import esbuild from 'esbuild';
import fs from 'fs';

View file

@ -1,5 +1,5 @@
import type { RenderedChunk } from 'rollup';
import type { Plugin as VitePlugin } from 'vite';
import type { Plugin as VitePlugin } from '../core/vite';
import { STYLE_EXTENSIONS } from '../core/ssr/css.js';
import { getViteTransform, TransformHook } from '../vite-plugin-astro/styles.js';

View file

@ -1,5 +1,5 @@
import type { ResolveIdHook, LoadHook } from 'rollup';
import type { ResolvedConfig, Plugin as VitePlugin } from 'vite';
import type { ResolvedConfig, Plugin as VitePlugin } from '../core/vite';
export function getVitePluginByName(viteConfig: ResolvedConfig, pluginName: string): VitePlugin {
const plugin = viteConfig.plugins.find(({ name }) => name === pluginName);

View file

@ -1,6 +1,6 @@
import type { AstroConfig, RouteCache } from '../@types/astro-core';
import type { AstroConfig, RouteCache } from '../@types/astro';
import type { LogOptions } from '../core/logger';
import type { ViteDevServer, Plugin as VitePlugin } from 'vite';
import type { ViteDevServer, Plugin as VitePlugin } from '../core/vite';
import type { OutputChunk, PreRenderedChunk, RenderedChunk } from 'rollup';
import type { AllPagesData } from '../core/build/types';
import parse5 from 'parse5';

View file

@ -2,7 +2,7 @@ import * as tsr from 'tsconfig-resolver';
import * as path from 'path';
import * as url from 'url';
import type * as vite from 'vite';
import type * as vite from '../core/vite';
/** Result of successfully parsed tsconfig.json or jsconfig.json. */
export declare interface Alias {

View file

@ -1,6 +1,6 @@
import type { TransformResult } from 'rollup';
import type { Plugin, ResolvedConfig } from '../core/vite';
import type { AstroConfig, Renderer } from '../@types/astro-core';
import type { AstroConfig, Renderer } from '../@types/astro';
import type { LogOptions } from '../core/logger';
import babel from '@babel/core';

View file

@ -1,5 +1,5 @@
import type { Plugin } from '../core/vite';
import type { AstroConfig } from '../@types/astro-core';
import type { AstroConfig } from '../@types/astro';
import esbuild from 'esbuild';
import fs from 'fs';