[ci] yarn format

This commit is contained in:
matthewp 2022-02-14 17:50:16 +00:00 committed by GitHub Actions
parent ba5e2b5e6c
commit f84848226d
24 changed files with 99 additions and 157 deletions

View file

@ -5,8 +5,8 @@ export default /** @type {import('astro').AstroUserConfig} */ ({
vite: {
server: {
proxy: {
'/api': 'http://localhost:8085'
}
}
}
'/api': 'http://localhost:8085',
},
},
},
});

View file

@ -1,4 +1,4 @@
import {execa} from 'execa';
import { execa } from 'execa';
const api = execa('npm', ['run', 'dev-api']);
api.stdout.pipe(process.stdout);

View file

@ -2,26 +2,26 @@ import fs from 'fs';
const dbJSON = fs.readFileSync(new URL('./db.json', import.meta.url));
const db = JSON.parse(dbJSON);
const products = db.products;
const productMap = new Map(products.map(product => [product.id, product]));
const productMap = new Map(products.map((product) => [product.id, product]));
const routes = [
{
match: /\/api\/products\/([0-9])+/,
async handle(_req, res, [,idStr]) {
async handle(_req, res, [, idStr]) {
const id = Number(idStr);
if(productMap.has(id)) {
if (productMap.has(id)) {
const product = productMap.get(id);
res.writeHead(200, {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
});
res.end(JSON.stringify(product));
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
'Content-Type': 'text/plain',
});
res.end('Not found');
}
}
},
},
{
match: /\/api\/products/,
@ -30,20 +30,19 @@ const routes = [
'Content-Type': 'application/json',
});
res.end(JSON.stringify(products));
}
}
]
},
},
];
export async function apiHandler(req, res) {
for(const route of routes) {
for (const route of routes) {
const match = route.match.exec(req.url);
if(match) {
if (match) {
return route.handle(req, res, match);
}
}
res.writeHead(404, {
'Content-Type': 'text/plain'
'Content-Type': 'text/plain',
});
res.end('Not found');
}

View file

@ -4,13 +4,13 @@ import { apiHandler } from './api.mjs';
const PORT = process.env.PORT || 8085;
const server = createServer((req, res) => {
apiHandler(req, res).catch(err => {
apiHandler(req, res).catch((err) => {
console.error(err);
res.writeHead(500, {
'Content-Type': 'text/plain'
'Content-Type': 'text/plain',
});
res.end(err.toString());
})
});
});
server.listen(PORT);

View file

@ -2,7 +2,7 @@ import { createServer } from 'http';
import fs from 'fs';
import mime from 'mime';
import { loadApp } from 'astro/app/node';
import { polyfill } from '@astropub/webapi'
import { polyfill } from '@astropub/webapi';
import { apiHandler } from './api.mjs';
polyfill(globalThis);
@ -14,21 +14,21 @@ const app = await loadApp(serverRoot);
async function handle(req, res) {
const route = app.match(req);
if(route) {
if (route) {
const html = await app.render(req, route);
res.writeHead(200, {
'Content-Type': 'text/html'
'Content-Type': 'text/html',
});
res.end(html)
} else if(/^\/api\//.test(req.url)) {
res.end(html);
} else if (/^\/api\//.test(req.url)) {
return apiHandler(req, res);
} else {
let local = new URL('.' + req.url, clientRoot);
try {
const data = await fs.promises.readFile(local);
res.writeHead(200, {
'Content-Type': mime.getType(req.url)
'Content-Type': mime.getType(req.url),
});
res.end(data);
} catch {
@ -39,13 +39,13 @@ async function handle(req, res) {
}
const server = createServer((req, res) => {
handle(req, res).catch(err => {
handle(req, res).catch((err) => {
console.error(err);
res.writeHead(500, {
'Content-Type': 'text/plain'
'Content-Type': 'text/plain',
});
res.end(err.toString());
})
});
});
server.listen(8085);

View file

@ -7,13 +7,11 @@ interface Product {
//let origin: string;
const { mode } = import.meta.env;
const origin = mode === 'develeopment' ?
`http://localhost:3000` :
`http://localhost:8085`;
const origin = mode === 'develeopment' ? `http://localhost:3000` : `http://localhost:8085`;
async function get<T>(endpoint: string, cb: (response: Response) => Promise<T>): Promise<T> {
const response = await fetch(`${origin}${endpoint}`);
if(!response.ok) {
if (!response.ok) {
// TODO make this better...
return null;
}
@ -21,14 +19,14 @@ async function get<T>(endpoint: string, cb: (response: Response) => Promise<T>):
}
export async function getProducts(): Promise<Product[]> {
return get<Product[]>('/api/products', async response => {
return get<Product[]>('/api/products', async (response) => {
const products: Product[] = await response.json();
return products;
});
}
export async function getProduct(id: number): Promise<Product> {
return get<Product>(`/api/products/${id}`, async response => {
return get<Product>(`/api/products/${id}`, async (response) => {
const product: Product = await response.json();
return product;
});

View file

@ -1,3 +1,3 @@
body {
font-family: "GT America Standard", "Helvetica Neue", Helvetica,Arial,sans-serif;
font-family: 'GT America Standard', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

View file

@ -3,10 +3,10 @@ import { deserializeRouteData } from '../routing/manifest/serialization.js';
export function deserializeManifest(serializedManifest: SerializedSSRManifest): SSRManifest {
const routes: RouteInfo[] = [];
for(const serializedRoute of serializedManifest.routes) {
for (const serializedRoute of serializedManifest.routes) {
routes.push({
...serializedRoute,
routeData: deserializeRouteData(serializedRoute.routeData)
routeData: deserializeRouteData(serializedRoute.routeData),
});
const route = serializedRoute as unknown as RouteInfo;
@ -15,6 +15,6 @@ export function deserializeManifest(serializedManifest: SerializedSSRManifest):
return {
...serializedManifest,
routes
routes,
};
}

View file

@ -1,7 +1,5 @@
import type { ComponentInstance, ManifestData, RouteData, Renderer } from '../../@types/astro';
import type {
SSRManifest as Manifest, RouteInfo
} from './types';
import type { SSRManifest as Manifest, RouteInfo } from './types';
import { defaultLogOptions } from '../logger.js';
import { matchRoute } from '../routing/match.js';
@ -22,12 +20,10 @@ export class App {
constructor(manifest: Manifest, rootFolder: URL) {
this.#manifest = manifest;
this.#manifestData = {
routes: manifest.routes.map(route => route.routeData)
routes: manifest.routes.map((route) => route.routeData),
};
this.#rootFolder = rootFolder;
this.#routeDataToRouteInfo = new Map(
manifest.routes.map(route => [route.routeData, route])
);
this.#routeDataToRouteInfo = new Map(manifest.routes.map((route) => [route.routeData, route]));
this.#routeCache = new RouteCache(defaultLogOptions);
this.#renderersPromise = this.#loadRenderers();
}
@ -35,19 +31,16 @@ export class App {
return matchRoute(pathname, this.#manifestData);
}
async render(url: URL, routeData?: RouteData): Promise<string> {
if(!routeData) {
if (!routeData) {
routeData = this.match(url);
if(!routeData) {
if (!routeData) {
return 'Not found';
}
}
const manifest = this.#manifest;
const info = this.#routeDataToRouteInfo.get(routeData!)!;
const [mod, renderers] = await Promise.all([
this.#loadModule(info.file),
this.#renderersPromise
]);
const [mod, renderers] = await Promise.all([this.#loadModule(info.file), this.#renderersPromise]);
const links = createLinkStylesheetElementSet(info.links, manifest.site);
const scripts = createModuleScriptElementWithSrcSet(info.scripts, manifest.site);
@ -63,7 +56,7 @@ export class App {
scripts,
renderers,
async resolve(specifier: string) {
if(!(specifier in manifest.entryModules)) {
if (!(specifier in manifest.entryModules)) {
throw new Error(`Unable to resolve [${specifier}]`);
}
const bundlePath = manifest.entryModules[specifier];
@ -71,21 +64,23 @@ export class App {
},
route: routeData,
routeCache: this.#routeCache,
site: this.#manifest.site
})
site: this.#manifest.site,
});
}
async #loadRenderers(): Promise<Renderer[]> {
const rendererNames = this.#manifest.renderers;
return await Promise.all(rendererNames.map(async (rendererName) => {
return await Promise.all(
rendererNames.map(async (rendererName) => {
return createRenderer(rendererName, {
renderer(name) {
return import(name);
},
server(entry) {
return import(entry);
}
},
});
})
}));
);
}
async #loadModule(rootRelativePath: string): Promise<ComponentInstance> {
let modUrl = new URL(rootRelativePath, this.#rootFolder).toString();
@ -93,7 +88,7 @@ export class App {
try {
mod = await import(modUrl);
return mod;
} catch(err) {
} catch (err) {
throw new Error(`Unable to import ${modUrl}. Does this file exist?`);
}
}

View file

@ -1,7 +1,7 @@
import type { RouteData, SerializedRouteData, MarkdownRenderOptions } from '../../@types/astro';
export interface RouteInfo {
routeData: RouteData
routeData: RouteData;
file: string;
links: string[];
scripts: string[];
@ -9,18 +9,18 @@ export interface RouteInfo {
export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
routeData: SerializedRouteData;
}
};
export interface SSRManifest {
routes: RouteInfo[];
site?: string;
markdown: {
render: MarkdownRenderOptions
},
render: MarkdownRenderOptions;
};
renderers: string[];
entryModules: Record<string, string>;
}
export type SerializedSSRManifest = Omit<SSRManifest, 'routes'> & {
routes: SerializedRouteInfo[];
}
};

View file

@ -159,7 +159,7 @@ export async function staticBuild(opts: StaticBuildOptions) {
const [ssrResult] = (await Promise.all([ssrBuild(opts, internals, pageInput), clientBuild(opts, internals, jsInput)])) as RollupOutput[];
// SSG mode, generate pages.
if(staticMode) {
if (staticMode) {
// Generate each of the pages.
await generatePages(ssrResult, opts, internals, facadeIdToPageDataMap);
await cleanSsrOutput(opts);
@ -189,7 +189,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
format: 'esm',
entryFileNames: '[name].[hash].mjs',
chunkFileNames: 'chunks/[name].[hash].mjs',
assetFileNames: 'assets/[name].[hash][extname]'
assetFileNames: 'assets/[name].[hash][extname]',
},
},
target: 'esnext', // must match an esbuild target
@ -233,8 +233,7 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals,
format: 'esm',
entryFileNames: '[name].[hash].js',
chunkFileNames: 'chunks/[name].[hash].js',
assetFileNames: 'assets/[name].[hash][extname]'
assetFileNames: 'assets/[name].[hash][extname]',
},
preserveEntrySignatures: 'exports-only',
},
@ -400,10 +399,10 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
const data: ViteManifest = JSON.parse(inputManifestJSON);
const rootRelativeIdToChunkMap = new Map<string, OutputChunk>();
for(const output of result.output) {
if(chunkIsPage(astroConfig, output, internals)) {
for (const output of result.output) {
if (chunkIsPage(astroConfig, output, internals)) {
const chunk = output as OutputChunk;
if(chunk.facadeModuleId) {
if (chunk.facadeModuleId) {
const id = rootRelativeFacadeId(chunk.facadeModuleId, astroConfig);
rootRelativeIdToChunkMap.set(id, chunk);
}
@ -412,11 +411,11 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
const routes: SerializedRouteInfo[] = [];
for(const routeData of manifest.routes) {
for (const routeData of manifest.routes) {
const componentPath = routeData.component;
const entry = data[componentPath];
if(!rootRelativeIdToChunkMap.has(componentPath)) {
if (!rootRelativeIdToChunkMap.has(componentPath)) {
throw new Error('Unable to find chunk for ' + componentPath);
}
@ -430,7 +429,7 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
file: entry?.file,
links,
scripts,
routeData: serializeRouteData(routeData)
routeData: serializeRouteData(routeData),
});
}
@ -438,10 +437,10 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
routes,
site: astroConfig.buildOptions.site,
markdown: {
render: astroConfig.markdownOptions.render
render: astroConfig.markdownOptions.render,
},
renderers: astroConfig.renderers,
entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries())
entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries()),
};
const outputManifestJSON = JSON.stringify(ssrManifest, null, ' ');
@ -522,7 +521,7 @@ async function ssrMoveAssets(opts: StaticBuildOptions) {
await emptyDir(fileURLToPath(serverAssets));
if(fs.existsSync(serverAssets)) {
if (fs.existsSync(serverAssets)) {
await fs.promises.rmdir(serverAssets);
}
}

View file

@ -147,7 +147,7 @@ function mergeCLIFlags(astroConfig: AstroUserConfig, flags: CLIFlags) {
if (typeof flags.experimentalStaticBuild === 'boolean') astroConfig.buildOptions.experimentalStaticBuild = flags.experimentalStaticBuild;
if (typeof flags.experimentalSsr === 'boolean') {
astroConfig.buildOptions.experimentalSsr = flags.experimentalSsr;
if(flags.experimentalSsr) {
if (flags.experimentalSsr) {
astroConfig.buildOptions.experimentalStaticBuild = true;
}
}

View file

@ -49,9 +49,9 @@ async function getParamsAndProps(opts: GetParamsAndPropsOptions): Promise<[Param
interface RenderOptions {
experimentalStaticBuild: boolean;
logging: LogOptions,
logging: LogOptions;
links: Set<SSRElement>;
markdownRender: MarkdownRenderOptions,
markdownRender: MarkdownRenderOptions;
mod: ComponentInstance;
origin: string;
pathname: string;
@ -64,21 +64,7 @@ interface RenderOptions {
}
export async function render(opts: RenderOptions): Promise<string> {
const {
experimentalStaticBuild,
links,
logging,
origin,
markdownRender,
mod,
pathname,
scripts,
renderers,
resolve,
route,
routeCache,
site
} = opts;
const { experimentalStaticBuild, links, logging, origin, markdownRender, mod, pathname, scripts, renderers, resolve, route, routeCache, site } = opts;
const [params, pageProps] = await getParamsAndProps({
logging,
@ -93,7 +79,6 @@ export async function render(opts: RenderOptions): Promise<string> {
if (!Component) throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);
if (!Component.isAstroComponentFactory) throw new Error(`Unable to SSR non-Astro component (${route?.component})`);
const result = createResult({
experimentalStaticBuild,
links,
@ -105,7 +90,7 @@ export async function render(opts: RenderOptions): Promise<string> {
resolve,
renderers,
site,
scripts
scripts,
});
let html = await renderPage(result, Component, pageProps, null);

View file

@ -50,10 +50,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
const { astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer } = ssrOpts;
// Add hoisted script tags
const scripts = createModuleScriptElementWithSrcSet(astroConfig.buildOptions.experimentalStaticBuild ?
Array.from(mod.$$metadata.hoistedScriptPaths()) :
[]
);
const scripts = createModuleScriptElementWithSrcSet(astroConfig.buildOptions.experimentalStaticBuild ? Array.from(mod.$$metadata.hoistedScriptPaths()) : []);
// Inject HMR scripts
if (mode === 'development' && astroConfig.buildOptions.experimentalStaticBuild) {

View file

@ -15,7 +15,7 @@ async function resolveRenderer(viteServer: vite.ViteDevServer, renderer: string,
const { url } = await viteServer.moduleGraph.ensureEntryFromUrl(entry);
const mod = await viteServer.ssrLoadModule(url);
return mod;
}
},
});
return resolvedRenderer;

View file

@ -14,7 +14,7 @@ export async function createRenderer(renderer: string, impl: RendererResolverImp
// The other entrypoints need to be loaded through Vite.
const {
default: { name, client, polyfills, hydrationPolyfills, server },
} = await impl.renderer(renderer) //await import(resolveDependency(renderer, astroConfig));
} = await impl.renderer(renderer); //await import(resolveDependency(renderer, astroConfig));
resolvedRenderer.name = name;
if (client) resolvedRenderer.source = npath.posix.join(renderer, client);

View file

@ -22,16 +22,7 @@ export interface CreateResultArgs {
}
export function createResult(args: CreateResultArgs): SSRResult {
const {
experimentalStaticBuild,
origin,
markdownRender,
params,
pathname,
renderers,
resolve,
site: buildOptionsSite
} = args;
const { experimentalStaticBuild, origin, markdownRender, params, pathname, renderers, resolve, site: buildOptionsSite } = args;
// Create the result object that will be passed into the render function.
// This object starts here as an empty shell (not yet the result) but then
@ -111,7 +102,7 @@ ${extra}`
else if (mdRender instanceof Promise) {
const mod: { default: MarkdownParser } = await mdRender;
parser = mod.default;
} else if(typeof mdRender === 'function') {
} else if (typeof mdRender === 'function') {
parser = mdRender;
} else {
throw new Error('No Markdown parser found.');

View file

@ -4,7 +4,7 @@ import npath from 'path';
import { appendForwardSlash } from '../../core/path.js';
function getRootPath(site?: string): string {
return appendForwardSlash(new URL(site || 'http://localhost/').pathname)
return appendForwardSlash(new URL(site || 'http://localhost/').pathname);
}
function joinToRoot(href: string, site?: string): string {
@ -15,14 +15,14 @@ export function createLinkStylesheetElement(href: string, site?: string): SSREle
return {
props: {
rel: 'stylesheet',
href: joinToRoot(href, site)
href: joinToRoot(href, site),
},
children: '',
};
}
export function createLinkStylesheetElementSet(hrefs: string[], site?: string) {
return new Set<SSRElement>(hrefs.map(href => createLinkStylesheetElement(href, site)));
return new Set<SSRElement>(hrefs.map((href) => createLinkStylesheetElement(href, site)));
}
export function createModuleScriptElementWithSrc(src: string, site?: string): SSRElement {
@ -32,9 +32,9 @@ export function createModuleScriptElementWithSrc(src: string, site?: string): SS
src: joinToRoot(src, site),
},
children: '',
}
};
}
export function createModuleScriptElementWithSrcSet(srces: string[], site?: string): Set<SSRElement> {
return new Set<SSRElement>(srces.map(src => createModuleScriptElementWithSrc(src, site)));
return new Set<SSRElement>(srces.map((src) => createModuleScriptElementWithSrc(src, site)));
}

View file

@ -1,11 +1,5 @@
export { createRouteManifest } from './manifest/create.js';
export {
serializeRouteData,
deserializeRouteData
} from './manifest/serialization.js';
export { serializeRouteData, deserializeRouteData } from './manifest/serialization.js';
export { matchRoute } from './match.js';
export { getParams } from './params.js';
export {
validateGetStaticPathsModule,
validateGetStaticPathsResult
} from './validation.js';
export { validateGetStaticPathsModule, validateGetStaticPathsResult } from './validation.js';

View file

@ -1,8 +1,4 @@
import type {
AstroConfig,
ManifestData,
RouteData
} from '../../../@types/astro';
import type { AstroConfig, ManifestData, RouteData } from '../../../@types/astro';
import type { LogOptions } from '../../logger';
import fs from 'fs';
@ -86,7 +82,6 @@ function getPattern(segments: Part[][], addTrailingSlash: AstroConfig['devOption
return new RegExp(`^${pathname || '\\/'}${trailing}`);
}
function getTrailingSlashPattern(addTrailingSlash: AstroConfig['devOptions']['trailingSlash']): string {
if (addTrailingSlash === 'always') {
return '\\/$';

View file

@ -1,7 +1,4 @@
import type {
RouteData,
SerializedRouteData
} from '../../../@types/astro';
import type { RouteData, SerializedRouteData } from '../../../@types/astro';
function createRouteData(pattern: RegExp, params: string[], component: string, pathname: string | undefined): RouteData {
return {
@ -12,7 +9,7 @@ function createRouteData(pattern: RegExp, params: string[], component: string, p
// TODO bring back
generate: () => '',
pathname: pathname || undefined,
}
};
}
export function serializeRouteData(routeData: RouteData): SerializedRouteData {

View file

@ -1,10 +1,6 @@
import type {
ManifestData,
RouteData
} from '../../@types/astro';
import type { ManifestData, RouteData } from '../../@types/astro';
/** Find matching route from pathname */
export function matchRoute(pathname: string, manifest: ManifestData): RouteData | undefined {
return manifest.routes.find((route) => route.pattern.test(pathname));
}

View file

@ -5,7 +5,7 @@ import type { Params } from '../../@types/astro';
* src/routes/[x]/[y]/[z]/svelte, create a function
* that turns a RegExpExecArray into ({ x, y, z })
*/
export function getParams(array: string[]) {
export function getParams(array: string[]) {
const fn = (match: RegExpExecArray) => {
const params: Params = {};
array.forEach((key, i) => {
@ -20,4 +20,3 @@ import type { Params } from '../../@types/astro';
return fn;
}

View file

@ -1,7 +1,4 @@
import type {
ComponentInstance,
GetStaticPathsResult
} from '../../@types/astro';
import type { ComponentInstance, GetStaticPathsResult } from '../../@types/astro';
import type { LogOptions } from '../logger';
import { warn } from '../logger.js';