Skip to content

Commit

Permalink
Clean up block comments
Browse files Browse the repository at this point in the history
  • Loading branch information
drwpow committed Oct 20, 2021
1 parent 2359f5d commit 3d9eb75
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 61 deletions.
4 changes: 2 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ module.exports = {
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-var-requires': 'off',
'multiline-comment-style': ['warn', 'starred-block'],
'no-console': 'warn',
'no-shadow': 'error',
'prefer-const': 'off',
'prefer-rest-params': 'off',
'require-jsdoc': 'off',
// 'require-jsdoc': 'error', // re-enable this to enforce JSDoc for all functions
},
};
21 changes: 12 additions & 9 deletions packages/astro/src/@types/astro-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ export interface AstroUserConfig {
buildOptions?: {
/** Your public domain, e.g.: https://my-site.dev/. Used to generate sitemaps and canonical URLs. */
site?: string;
/** Generate an automatically-generated sitemap for your build.
/**
* Generate an automatically-generated sitemap for your build.
* Default: true
*/
sitemap?: boolean;
Expand Down Expand Up @@ -95,14 +96,16 @@ export interface AstroUserConfig {
vite?: vite.InlineConfig;
}

// NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that
// we can add JSDoc-style documentation and link to the definition file in our repo.
// However, Zod comes with the ability to auto-generate AstroConfig from the schema
// above. If we ever get to the point where we no longer need the dedicated
// @types/config.ts file, consider replacing it with the following lines:
//
// export interface AstroUserConfig extends z.input<typeof AstroConfigSchema> {
// }
/*
* NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that
* we can add JSDoc-style documentation and link to the definition file in our repo.
* However, Zod comes with the ability to auto-generate AstroConfig from the schema
* above. If we ever get to the point where we no longer need the dedicated
* @types/config.ts file, consider replacing it with the following lines:
*
* export interface AstroUserConfig extends z.input<typeof AstroConfigSchema> {
* }
*/
export type AstroConfig = z.output<typeof AstroConfigSchema>;

export type AsyncRendererComponentFn<U> = (Component: any, props: any, children: string | undefined, metadata?: AstroComponentMetadata) => Promise<U>;
Expand Down
6 changes: 4 additions & 2 deletions packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ export const AstroConfigSchema = z.object({
/** Turn raw config values into normalized values */
export async function validateConfig(userConfig: any, root: string): Promise<AstroConfig> {
const fileProtocolRoot = pathToFileURL(root + path.sep);
// We need to extend the global schema to add transforms that are relative to root.
// This is type checked against the global schema to make sure we still match.
/*
* We need to extend the global schema to add transforms that are relative to root.
* This is type checked against the global schema to make sure we still match.
*/
const AstroConfigRelativeSchema = AstroConfigSchema.extend({
projectRoot: z
.string()
Expand Down
8 changes: 5 additions & 3 deletions packages/astro/src/core/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,11 @@ export class AstroDevServer {
this.manifest = createRouteManifest({ config: this.config });
});
viteServer.watcher.on('change', () => {
// No need to rebuild routes on file content changes.
// However, we DO want to clear the cache in case
// the change caused a getStaticPaths() return to change.
/*
* No need to rebuild routes on file content changes.
* However, we DO want to clear the cache in case
* the change caused a getStaticPaths() return to change.
*/
this.routeCache = {};
});

Expand Down
6 changes: 4 additions & 2 deletions packages/astro/src/core/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ function getLoggerLocale(): string {
const defaultLocale = 'en-US';
if (process.env.LANG) {
const extractedLocale = process.env.LANG.split('.')[0].replace(/_/g, '-');
// Check if language code is atleast two characters long (ie. en, es).
// NOTE: if "c" locale is encountered, the default locale will be returned.
/*
* Check if language code is at least two characters long (ie. en, es).
* NOTE: if "c" locale is encountered, the default locale will be returned.
*/
if (extractedLocale.length < 2) return defaultLocale;
else return extractedLocale;
} else return defaultLocale;
Expand Down
8 changes: 5 additions & 3 deletions packages/astro/src/core/ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ const cache = new Map<string, Promise<Renderer>>();
// TODO: improve validation and error handling here.
async function resolveRenderer(viteServer: ViteDevServer, renderer: string) {
const resolvedRenderer: any = {};
// We can dynamically import the renderer by itself because it shouldn't have
// any non-standard imports, the index is just meta info.
// The other entrypoints need to be loaded through Vite.
/*
* We can dynamically import the renderer by itself because it shouldn't have
* any non-standard imports, the index is just meta info.
* The other entrypoints need to be loaded through Vite.
*/
const {
default: { name, client, polyfills, hydrationPolyfills, server },
} = await import(renderer);
Expand Down
10 changes: 0 additions & 10 deletions packages/astro/src/core/ssr/paginate.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
import { GetStaticPathsResult, PaginatedCollectionProp, PaginateFunction, Params, Props, RouteData } from '../../@types/astro-core';

// return filters.map((filter) => {
// const filteredRecipes = allRecipes.filter((recipe) =>
// filterKeys.some((key) => recipe[key] === filter)
// );
// return paginate(filteredRecipes, {
// params: { slug: slugify(filter) },
// props: { filter },
// });
// });

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;
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/core/ssr/sitemap.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** Construct sitemap.xml given a set of URLs */
export function generateSitemap(pages: string[]): string {
// TODO: find way to respect <link rel="canonical"> URLs here

// TODO: find way to exclude pages from sitemap

const urls = [...pages]; // copy just in case original copy is needed
Expand Down
22 changes: 14 additions & 8 deletions packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ export { createMetadata } from './metadata.js';

const { generate, GENERATOR } = astring;

// A more robust version alternative to `JSON.stringify` that can handle most values
// see https://github.com/remcohaszing/estree-util-value-to-estree#readme
/*
* A more robust version alternative to `JSON.stringify` that can handle most values
* See https://github.com/remcohaszing/estree-util-value-to-estree#readme
*/
const customGenerator: astring.Generator = {
...GENERATOR,
Literal(node, state) {
if (node.raw != null) {
// escape closing script tags in strings so browsers wouldn't interpret them as
// closing the actual end tag in HTML
/*
* escape closing script tags in strings so browsers wouldn't interpret them as
* closing the actual end tag in HTML
*/
state.write(node.raw.replace('</script>', '<\\/script>'));
} else {
GENERATOR.Literal(node, state);
Expand All @@ -35,9 +39,11 @@ async function _render(child: any): Promise<any> {
if (Array.isArray(child)) {
return (await Promise.all(child.map((value) => _render(value)))).join('\n');
} else if (typeof child === 'function') {
// Special: If a child is a function, call it automatically.
// This lets you do {() => ...} without the extra boilerplate
// of wrapping it in a function and calling it.
/*
* Special: If a child is a function, call it automatically.
* This lets you do {() => ...} without the extra boilerplate
* of wrapping it in a function and calling it.
*/
return _render(child());
} else if (typeof child === 'string') {
return child;
Expand Down Expand Up @@ -261,7 +267,7 @@ function createFetchContentFn(url: URL) {
...mod.frontmatter,
content: mod.metadata,
file: new URL(spec, url),
url: urlSpec.includes('/pages/') && urlSpec.replace(/^.*\/pages\//, '/').replace(/\.md$/, '')
url: urlSpec.includes('/pages/') && urlSpec.replace(/^.*\/pages\//, '/').replace(/\.md$/, ''),
};
})
.filter(Boolean);
Expand Down
8 changes: 5 additions & 3 deletions packages/astro/src/vite-plugin-astro-postprocess/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ interface AstroPluginOptions {
devServer?: AstroDevServer;
}

// esbuild transforms the component-scoped Astro into Astro2, so need to check both.
// esbuild transforms the component-scoped Astro into Astro2, so need to check both.
const validAstroGlobalNames = new Set(['Astro', 'Astro2']);

export default function astro({ config, devServer }: AstroPluginOptions): Plugin {
Expand All @@ -23,8 +23,10 @@ export default function astro({ config, devServer }: AstroPluginOptions): Plugin
return null;
}

// Optimization: only run on a probably match
// Open this up if need for post-pass extends past fetchContent
/*
* Optimization: only run on a probably match
* Open this up if need for post-pass extends past fetchContent
*/
if (!code.includes('fetchContent')) {
return null;
}
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export default function astro({ config, devServer }: AstroPluginOptions): Plugin

try {
// `.astro` -> `.ts`
// use `sourcemap: "inline"` so that the sourcemap is included in the "code" result that we pass to esbuild.
tsResult = await transform(source, {
site: config.buildOptions.site,
sourcefile: id,
Expand Down
28 changes: 15 additions & 13 deletions packages/astro/src/vite-plugin-fetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ import MagicString from 'magic-string';
// https://github.com/vitejs/vite/discussions/5109#discussioncomment-1450726
function isSSR(options: undefined | boolean | { ssr: boolean }): boolean {
if (options === undefined) {
return false
return false;
}
if (typeof options === 'boolean') {
return options
return options;
}
if (typeof options == 'object') {
return !!options.ssr
return !!options.ssr;
}
return false
return false;
}

// This matches any JS-like file (that we know of)
// See https://regex101.com/r/Cgofir/1
/*
* This matches any JS-like file (that we know of)
* See https://regex101.com/r/Cgofir/1
*/
const SUPPORTED_FILES = /\.(astro|svelte|vue|[cm]?js|jsx|[cm]?ts|tsx)$/;
const DEFINE_FETCH = `import fetch from 'node-fetch';\n`;

Expand All @@ -26,33 +28,33 @@ export default function pluginFetch(): Plugin {
enforce: 'post',
async transform(code, id, opts) {
const ssr = isSSR(opts);

// If this isn't an SSR pass, `fetch` will already be available!
if (!ssr) {
return null;
}

// Only transform JS-like files
if (!id.match(SUPPORTED_FILES)) {
return null;
}

// Optimization: only run on probable matches
if (!code.includes('fetch')) {
return null;
}

const s = new MagicString(code);
s.prepend(DEFINE_FETCH);

const result = s.toString();

const map = s.generateMap({
source: id,
includeContent: true
includeContent: true,
});
return { code: result, map }

return { code: result, map };
},
};
}
21 changes: 16 additions & 5 deletions packages/astro/src/vite-plugin-jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ const IMPORT_STATEMENTS: Record<string, string> = {
preact: "import { h } from 'preact'",
'solid-js': "import 'solid-js/web'",
};
// The `tsx` loader in esbuild will remove unused imports, so we need to
// be careful about esbuild not treating h, React, Fragment, etc. as unused.
/*
* The `tsx` loader in esbuild will remove unused imports, so we need to
* be careful about esbuild not treating h, React, Fragment, etc. as unused.
*/
const PREVENT_UNUSED_IMPORTS = ';;(React,Fragment,h);';

interface AstroPluginJSXOptions {
Expand Down Expand Up @@ -53,14 +55,23 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
}
}

// attempt 0: if we only have one renderer, we can skip a bunch of work!
/*
* Single JSX renderer
* If we only have one renderer, we can skip a bunch of work!
*/
if (JSX_RENDERERS.size === 1) {
return transformJSX({ code, id, renderer: [...JSX_RENDERERS.values()][0], ssr: ssr || false });
}

// attempt 1: try and guess framework from imports (file can’t import React and Preact)
/*
* Multiple JSX renderers
* Determine for each .jsx or .tsx file what it wants to use to Render
*/

// we need valid JS here, so we can use `h` and `Fragment` as placeholders

// try and guess renderer from imports (file can’t import React and Preact)

// NOTE(fks, matthewp): Make sure that you're transforming the original contents here.
const { code: codeToScan } = await esbuild.transform(code + PREVENT_UNUSED_IMPORTS, {
loader: getLoader(path.extname(id)),
Expand All @@ -85,7 +96,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
}
}

// attempt 2: look for @jsxImportSource comment
// if no imports were found, look for @jsxImportSource comment
if (!importSource) {
const multiline = code.match(/\/\*\*[\S\s]*\*\//gm) || [];
for (const comment of multiline) {
Expand Down

0 comments on commit 3d9eb75

Please sign in to comment.