[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

@ -2,7 +2,7 @@ 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 = [
{
@ -12,16 +12,16 @@ const routes = [
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,10 +30,9 @@ const routes = [
'Content-Type': 'application/json',
});
res.end(JSON.stringify(products));
}
}
]
},
},
];
export async function apiHandler(req, res) {
for (const route of routes) {
@ -43,7 +42,7 @@ export async function apiHandler(req, res) {
}
}
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);
@ -18,9 +18,9 @@ async function handle(req, res) {
const html = await app.render(req, route);
res.writeHead(200, {
'Content-Type': 'text/html'
'Content-Type': 'text/html',
});
res.end(html)
res.end(html);
} else if (/^\/api\//.test(req.url)) {
return apiHandler(req, res);
} else {
@ -28,7 +28,7 @@ async function handle(req, res) {
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,9 +7,7 @@ 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}`);
@ -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

@ -6,7 +6,7 @@ export function deserializeManifest(serializedManifest: SerializedSSRManifest):
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();
}
@ -44,10 +40,7 @@ export class App {
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);
@ -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();

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

@ -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',
},
@ -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, ' ');

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

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

@ -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';