chore(lint): Prettier fix

This commit is contained in:
github-actions[bot] 2021-12-09 17:05:39 +00:00 committed by Matthew Phillips
parent 19e2b5c56c
commit b7ff454453
16 changed files with 120 additions and 105 deletions

View file

@ -2,10 +2,10 @@
export default {
data() {
return {
greeting: 'Hello World!'
}
}
}
greeting: 'Hello World!',
};
},
};
</script>
<template>
@ -17,4 +17,4 @@ export default {
color: red;
font-weight: bold;
}
</style>
</style>

View file

@ -1,3 +1,3 @@
body {
background: lightcoral;
}
}

View file

@ -38,7 +38,7 @@ function resolveArgs(flags: Arguments): CLIState {
port: typeof flags.port === 'number' ? flags.port : undefined,
config: typeof flags.config === 'string' ? flags.config : undefined,
hostname: typeof flags.hostname === 'string' ? flags.hostname : undefined,
experimentalStaticBuild: typeof flags.experimentalStaticBuild === 'boolean' ? flags.experimentalStaticBuild: false,
experimentalStaticBuild: typeof flags.experimentalStaticBuild === 'boolean' ? flags.experimentalStaticBuild : false,
};
if (flags.version) {

View file

@ -1,4 +1,4 @@
import type { AstroConfig, ManifestData, RouteCache } from '../../@types/astro';
import type { AstroConfig, ManifestData, RouteCache } from '../../@types/astro';
import type { LogOptions } from '../logger';
import type { PageBuildData } from './types';
@ -78,7 +78,7 @@ class AstroBuilder {
manifest: this.manifest,
origin,
routeCache: this.routeCache,
viteServer: this.viteServer
viteServer: this.viteServer,
});
debug(logging, 'build', timerMessage('All pages loaded', timer.loadStart));
@ -90,14 +90,14 @@ class AstroBuilder {
timer.buildStart = performance.now();
// Use the new faster static based build.
if(this.config.buildOptions.experimentalStaticBuild) {
if (this.config.buildOptions.experimentalStaticBuild) {
await staticBuild({
allPages,
astroConfig: this.config,
logging: this.logging,
origin: this.origin,
routeCache: this.routeCache,
viteConfig: this.viteConfig
viteConfig: this.viteConfig,
});
} else {
await scanBasedBuild({

View file

@ -21,7 +21,7 @@ export interface BuildInternals {
* @returns {BuildInternals}
*/
export function createBuildInternals(): BuildInternals {
// Pure CSS chunks are chunks that only contain CSS.
// Pure CSS chunks are chunks that only contain CSS.
// This is all of them, and chunkToReferenceIdMap maps them to a hash id used to find the final file.
const pureCSSChunks = new Set<RenderedChunk>();
const chunkToReferenceIdMap = new Map<string, string>();
@ -42,4 +42,4 @@ export function createBuildInternals(): BuildInternals {
astroPageStyleMap,
facadeIdToAssetsMap,
};
}
}

View file

@ -119,4 +119,4 @@ async function getStaticPathsForRoute(opts: CollectPagesDataOptions, route: Rout
paths: staticPaths.map((staticPath) => staticPath.params && route.generate(staticPath.params)).filter(Boolean),
rss: rss.rss,
};
}
}

View file

@ -32,14 +32,14 @@ export async function build(opts: ScanBasedBuildOptions) {
mode: 'production',
build: {
emptyOutDir: true,
minify: false,// 'esbuild', // significantly faster than "terser" but may produce slightly-bigger bundles
minify: false, // 'esbuild', // significantly faster than "terser" but may produce slightly-bigger bundles
outDir: fileURLToPath(astroConfig.dist),
ssr: true,
rollupOptions: {
// The `input` will be populated in the build rollup plugin.
input: [],
output: {
format: 'esm'
format: 'esm',
},
},
target: 'es2020', // must match an esbuild target
@ -56,7 +56,7 @@ export async function build(opts: ScanBasedBuildOptions) {
viteServer,
}),
rollupPluginAstroBuildCSS({
internals
internals,
}),
...(viteConfig.plugins || []),
],
@ -66,4 +66,4 @@ export async function build(opts: ScanBasedBuildOptions) {
server: viteConfig.server,
base: astroConfig.buildOptions.site ? new URL(astroConfig.buildOptions.site).pathname : '/',
});
}
}

View file

@ -53,7 +53,7 @@ export async function staticBuild(opts: StaticBuildOptions) {
const internals = createBuildInternals();
// Perform the SSR build
const result = (await ssrBuild(opts, internals, jsInput) as RollupOutput);
const result = (await ssrBuild(opts, internals, jsInput)) as RollupOutput;
// Generate each of the pages.
await generatePages(result, opts, internals, facadeIdToPageDataMap);
@ -61,19 +61,19 @@ export async function staticBuild(opts: StaticBuildOptions) {
async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, input: Set<string>) {
const { astroConfig, viteConfig } = opts;
return await vite.build({
logLevel: 'error',
mode: 'production',
build: {
emptyOutDir: true,
minify: false,// 'esbuild', // significantly faster than "terser" but may produce slightly-bigger bundles
minify: false, // 'esbuild', // significantly faster than "terser" but may produce slightly-bigger bundles
outDir: fileURLToPath(astroConfig.dist),
ssr: true,
rollupOptions: {
input: Array.from(input),
output: {
format: 'esm'
format: 'esm',
},
},
target: 'es2020', // must match an esbuild target
@ -81,7 +81,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
plugins: [
vitePluginNewBuild(),
rollupPluginAstroBuildCSS({
internals
internals,
}),
...(viteConfig.plugins || []),
],
@ -96,17 +96,14 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
async function generatePages(result: RollupOutput, opts: StaticBuildOptions, internals: BuildInternals, facadeIdToPageDataMap: Map<string, PageBuildData>) {
console.log('End build step, now generating');
const generationPromises = [];
for(let output of result.output) {
if(output.type === 'chunk' && output.facadeModuleId) {
generationPromises.push(
generatePage(output, opts, internals, facadeIdToPageDataMap)
);
for (let output of result.output) {
if (output.type === 'chunk' && output.facadeModuleId) {
generationPromises.push(generatePage(output, opts, internals, facadeIdToPageDataMap));
}
}
await Promise.all(generationPromises);
}
async function generatePage(output: OutputChunk, opts: StaticBuildOptions, internals: BuildInternals, facadeIdToPageDataMap: Map<string, PageBuildData>) {
const { astroConfig } = opts;
@ -120,11 +117,11 @@ async function generatePage(output: OutputChunk, opts: StaticBuildOptions, inter
const generationOptions: Readonly<GeneratePathOptions> = {
pageData,
linkIds,
Component
Component,
};
const renderPromises = pageData.paths.map(path => {
return generatePath(path, opts, generationOptions)
const renderPromises = pageData.paths.map((path) => {
return generatePath(path, opts, generationOptions);
});
return await Promise.all(renderPromises);
}
@ -147,7 +144,7 @@ async function generatePath(path: string, opts: StaticBuildOptions, gopts: Gener
routeCache,
logging,
pathname: path,
mod
mod,
});
info(logging, 'generate', `Generating: ${path}`);
@ -157,14 +154,11 @@ async function generatePath(path: string, opts: StaticBuildOptions, gopts: Gener
const outFile = new URL('./index.html', outFolder);
await fs.promises.mkdir(outFolder, { recursive: true });
await fs.promises.writeFile(outFile, html, 'utf-8');
} catch(err) {
} catch (err) {
console.error(`Error rendering:`, err);
}
}
export function vitePluginNewBuild(): VitePlugin {
return {
name: '@astro/rollup-plugin-new-build',
@ -173,7 +167,7 @@ export function vitePluginNewBuild(): VitePlugin {
// Delete this hook because it causes assets not to be built
const plugins = resolvedConfig.plugins as VitePlugin[];
const viteAsset = plugins.find((p) => p.name === 'vite:asset');
if(viteAsset) {
if (viteAsset) {
delete viteAsset.generateBundle;
}
},
@ -185,9 +179,9 @@ export function vitePluginNewBuild(): VitePlugin {
},
chunkFileNames(_chunk: PreRenderedChunk) {
return 'assets/[name].[hash].mjs';
}
},
});
return outputOptions;
},
}
}
};
}

View file

@ -58,7 +58,7 @@ export const AstroConfigSchema = z.object({
.union([z.literal('file'), z.literal('directory')])
.optional()
.default('directory'),
experimentalStaticBuild: z.boolean().optional().default(false)
experimentalStaticBuild: z.boolean().optional().default(false),
})
.optional()
.default({}),

View file

@ -139,14 +139,25 @@ export async function preload({ astroConfig, filePath, viteServer }: SSROptions)
return [renderers, mod];
}
export async function renderComponent(renderers: Renderer[], Component: AstroComponentFactory, astroConfig: AstroConfig, pathname: string, origin: string, params: Params, pageProps: Props, links: string[] = []): Promise<string> {
const _links = new Set<SSRElement>(links.map(href => ({
props: {
rel: 'stylesheet',
href
},
children: ''
})));
export async function renderComponent(
renderers: Renderer[],
Component: AstroComponentFactory,
astroConfig: AstroConfig,
pathname: string,
origin: string,
params: Params,
pageProps: Props,
links: string[] = []
): Promise<string> {
const _links = new Set<SSRElement>(
links.map((href) => ({
props: {
rel: 'stylesheet',
href,
},
children: '',
}))
);
const result: SSRResult = {
styles: new Set<SSRElement>(),
scripts: new Set<SSRElement>(),
@ -188,7 +199,7 @@ export async function renderComponent(renderers: Renderer[], Component: AstroCom
_metadata: {
renderers,
pathname,
experimentalStaticBuild: astroConfig.buildOptions.experimentalStaticBuild
experimentalStaticBuild: astroConfig.buildOptions.experimentalStaticBuild,
},
};
@ -197,7 +208,19 @@ export async function renderComponent(renderers: Renderer[], Component: AstroCom
return html;
}
export async function getParamsAndProps({route, routeCache, logging, pathname, mod}: {route: RouteData | undefined, routeCache: RouteCache, pathname: string, mod: ComponentInstance, logging: LogOptions}): Promise<[Params, Props]> {
export async function getParamsAndProps({
route,
routeCache,
logging,
pathname,
mod,
}: {
route: RouteData | undefined;
routeCache: RouteCache;
pathname: string;
mod: ComponentInstance;
logging: LogOptions;
}): Promise<[Params, Props]> {
// Handle dynamic routes
let params: Params = {};
let pageProps: Props = {};
@ -318,7 +341,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
_metadata: {
renderers,
pathname,
experimentalStaticBuild: astroConfig.buildOptions.experimentalStaticBuild
experimentalStaticBuild: astroConfig.buildOptions.experimentalStaticBuild,
},
};

View file

@ -372,15 +372,16 @@ const uniqueElements = (item: any, index: number, all: any[]) => {
// styles and scripts into the head.
export async function renderPage(result: SSRResult, Component: AstroComponentFactory, props: any, children: any) {
const template = await renderToString(result, Component, props, children);
const styles = result._metadata.experimentalStaticBuild ? [] :
Array.from(result.styles)
.filter(uniqueElements)
.map((style) =>
renderElement('style', {
...style,
props: { ...style.props, 'astro-style': true },
})
);
const styles = result._metadata.experimentalStaticBuild
? []
: Array.from(result.styles)
.filter(uniqueElements)
.map((style) =>
renderElement('style', {
...style,
props: { ...style.props, 'astro-style': true },
})
);
let needsHydrationStyles = false;
const scripts = Array.from(result.scripts)
.filter(uniqueElements)
@ -399,7 +400,7 @@ export async function renderPage(result: SSRResult, Component: AstroComponentFac
const links = Array.from(result.links)
.filter(uniqueElements)
.map(link => renderElement('link', link))
.map((link) => renderElement('link', link));
// inject styles & scripts at end of <head>
let headPos = template.indexOf('</head>');

View file

@ -30,8 +30,7 @@ async function compile(config: AstroConfig, filename: string, source: string, vi
// pages and layouts should be transformed as full documents (implicit <head> <body> etc)
// everything else is treated as a fragment
const normalizedID = fileURLToPath(new URL(`file://${filename}`));
const isPage = normalizedID.startsWith(fileURLToPath(config.pages)) ||
normalizedID.startsWith(fileURLToPath(config.layouts));
const isPage = normalizedID.startsWith(fileURLToPath(config.pages)) || normalizedID.startsWith(fileURLToPath(config.layouts));
//let source = await fs.promises.readFile(id, 'utf8');
let cssTransformError: Error | undefined;
@ -51,10 +50,11 @@ async function compile(config: AstroConfig, filename: string, source: string, vi
const lang = `.${attrs?.lang || 'css'}`.toLowerCase();
try {
const result = await transformWithVite({
value, lang,
value,
lang,
id: filename,
transformHook: viteTransform,
ssr: isSSR(opts)
ssr: isSSR(opts),
});
let map: SourceMapInput | undefined;
@ -82,7 +82,7 @@ async function compile(config: AstroConfig, filename: string, source: string, vi
}
export function invalidateCompilation(config: AstroConfig, filename: string) {
if(configCache.has(config)) {
if (configCache.has(config)) {
const cache = configCache.get(config)!;
cache.delete(filename);
}
@ -90,19 +90,19 @@ export function invalidateCompilation(config: AstroConfig, filename: string) {
export async function cachedCompilation(config: AstroConfig, filename: string, source: string | null, viteTransform: TransformHook, opts: boolean | undefined) {
let cache: CompilationCache;
if(!configCache.has(config)) {
if (!configCache.has(config)) {
cache = new Map();
configCache.set(config, cache);
} else {
cache = configCache.get(config)!;
}
if(cache.has(filename)) {
if (cache.has(filename)) {
return cache.get(filename)!;
}
if(source === null) {
if (source === null) {
throw new Error(`Oh no, this should have been cached.`);
}
const transformResult = await compile(config, filename, source, viteTransform, opts);
cache.set(filename, transformResult);
return transformResult;
}
}

View file

@ -32,15 +32,14 @@ export default function astro({ config }: AstroPluginOptions): vite.Plugin {
},
async load(id, opts) {
let { filename, query } = parseAstroRequest(id);
if(query.astro) {
if(query.type === 'style') {
if(filename.startsWith('/') && !filename.startsWith(config.projectRoot.pathname)) {
if (query.astro) {
if (query.type === 'style') {
if (filename.startsWith('/') && !filename.startsWith(config.projectRoot.pathname)) {
filename = new URL('.' + filename, config.projectRoot).pathname;
}
const transformResult = await cachedCompilation(config, filename, null,
viteTransform, opts);
const transformResult = await cachedCompilation(config, filename, null, viteTransform, opts);
if(typeof query.index === 'undefined') {
if (typeof query.index === 'undefined') {
throw new Error(`Requests for Astro CSS must include an index.`);
}
@ -48,7 +47,7 @@ export default function astro({ config }: AstroPluginOptions): vite.Plugin {
const code = csses[query.index];
return {
code
code,
};
}
}
@ -61,15 +60,14 @@ export default function astro({ config }: AstroPluginOptions): vite.Plugin {
}
try {
const transformResult = await cachedCompilation(config, id, source,
viteTransform, opts);
const transformResult = await cachedCompilation(config, id, source, viteTransform, opts);
// Compile all TypeScript to JavaScript.
// Also, catches invalid JS/TS in the compiled output before returning.
const { code, map } = await esbuild.transform(transformResult.code, {
loader: 'ts',
sourcemap: 'external',
sourcefile: id
sourcefile: id,
});
return {
@ -123,14 +121,13 @@ export default function astro({ config }: AstroPluginOptions): vite.Plugin {
// TODO: remove stack replacement when compiler throws better errors
err.stack = ` at ${id}`;
}
throw err;
}
},
async handleHotUpdate(context) {
// Invalidate the compilation cache so it recompiles
invalidateCompilation(config, context.file);
}
},
};
}

View file

@ -1,35 +1,35 @@
export interface AstroQuery {
astro?: boolean
src?: boolean
type?: 'script' | 'template' | 'style' | 'custom'
index?: number
lang?: string
raw?: boolean
astro?: boolean;
src?: boolean;
type?: 'script' | 'template' | 'style' | 'custom';
index?: number;
lang?: string;
raw?: boolean;
}
// Parses an id to check if its an Astro request.
// CSS is imported like `import '/src/pages/index.astro?astro&type=style&index=0&lang.css';
// This parses those ids and returns an object representing what it found.
export function parseAstroRequest(id: string): {
filename: string
query: AstroQuery
filename: string;
query: AstroQuery;
} {
const [filename, rawQuery] = id.split(`?`, 2);
const query = Object.fromEntries(new URLSearchParams(rawQuery).entries()) as AstroQuery;
if (query.astro != null) {
query.astro = true
query.astro = true;
}
if (query.src != null) {
query.src = true
query.src = true;
}
if (query.index != null) {
query.index = Number(query.index)
query.index = Number(query.index);
}
if (query.raw != null) {
query.raw = true
query.raw = true;
}
return {
filename,
query
}
}
query,
};
}

View file

@ -137,11 +137,11 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin {
type: 'asset',
source: minifiedCSS,
});
internals.chunkToReferenceIdMap.set(chunk.fileName, referenceId);
if(chunk.type === 'chunk') {
if (chunk.type === 'chunk') {
const facadeId = chunk.facadeModuleId!;
if(!internals.facadeIdToAssetsMap.has(facadeId)) {
if (!internals.facadeIdToAssetsMap.has(facadeId)) {
internals.facadeIdToAssetsMap.set(facadeId, []);
}
internals.facadeIdToAssetsMap.get(facadeId)!.push(this.getFileName(referenceId));

View file

@ -234,7 +234,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
return `assets/${pageName}.[hash].js`;
}
return 'assets/[name].[hash].js';
}
},
});
return outputOptions;
},