[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: { vite: {
server: { server: {
proxy: { 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']); const api = execa('npm', ['run', 'dev-api']);
api.stdout.pipe(process.stdout); 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 dbJSON = fs.readFileSync(new URL('./db.json', import.meta.url));
const db = JSON.parse(dbJSON); const db = JSON.parse(dbJSON);
const products = db.products; 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 = [ const routes = [
{ {
match: /\/api\/products\/([0-9])+/, match: /\/api\/products\/([0-9])+/,
async handle(_req, res, [,idStr]) { async handle(_req, res, [, idStr]) {
const id = Number(idStr); const id = Number(idStr);
if(productMap.has(id)) { if (productMap.has(id)) {
const product = productMap.get(id); const product = productMap.get(id);
res.writeHead(200, { res.writeHead(200, {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}); });
res.end(JSON.stringify(product)); res.end(JSON.stringify(product));
} else { } else {
res.writeHead(404, { res.writeHead(404, {
'Content-Type': 'text/plain' 'Content-Type': 'text/plain',
}); });
res.end('Not found'); res.end('Not found');
} }
} },
}, },
{ {
match: /\/api\/products/, match: /\/api\/products/,
@ -30,20 +30,19 @@ const routes = [
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}); });
res.end(JSON.stringify(products)); res.end(JSON.stringify(products));
} },
} },
];
]
export async function apiHandler(req, res) { export async function apiHandler(req, res) {
for(const route of routes) { for (const route of routes) {
const match = route.match.exec(req.url); const match = route.match.exec(req.url);
if(match) { if (match) {
return route.handle(req, res, match); return route.handle(req, res, match);
} }
} }
res.writeHead(404, { res.writeHead(404, {
'Content-Type': 'text/plain' 'Content-Type': 'text/plain',
}); });
res.end('Not found'); res.end('Not found');
} }

View file

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

View file

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

View file

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

View file

@ -1,3 +1,3 @@
body { 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 { export function deserializeManifest(serializedManifest: SerializedSSRManifest): SSRManifest {
const routes: RouteInfo[] = []; const routes: RouteInfo[] = [];
for(const serializedRoute of serializedManifest.routes) { for (const serializedRoute of serializedManifest.routes) {
routes.push({ routes.push({
...serializedRoute, ...serializedRoute,
routeData: deserializeRouteData(serializedRoute.routeData) routeData: deserializeRouteData(serializedRoute.routeData),
}); });
const route = serializedRoute as unknown as RouteInfo; const route = serializedRoute as unknown as RouteInfo;
@ -15,6 +15,6 @@ export function deserializeManifest(serializedManifest: SerializedSSRManifest):
return { return {
...serializedManifest, ...serializedManifest,
routes routes,
}; };
} }

View file

@ -1,7 +1,5 @@
import type { ComponentInstance, ManifestData, RouteData, Renderer } from '../../@types/astro'; import type { ComponentInstance, ManifestData, RouteData, Renderer } from '../../@types/astro';
import type { import type { SSRManifest as Manifest, RouteInfo } from './types';
SSRManifest as Manifest, RouteInfo
} from './types';
import { defaultLogOptions } from '../logger.js'; import { defaultLogOptions } from '../logger.js';
import { matchRoute } from '../routing/match.js'; import { matchRoute } from '../routing/match.js';
@ -22,12 +20,10 @@ export class App {
constructor(manifest: Manifest, rootFolder: URL) { constructor(manifest: Manifest, rootFolder: URL) {
this.#manifest = manifest; this.#manifest = manifest;
this.#manifestData = { this.#manifestData = {
routes: manifest.routes.map(route => route.routeData) routes: manifest.routes.map((route) => route.routeData),
}; };
this.#rootFolder = rootFolder; this.#rootFolder = rootFolder;
this.#routeDataToRouteInfo = new Map( this.#routeDataToRouteInfo = new Map(manifest.routes.map((route) => [route.routeData, route]));
manifest.routes.map(route => [route.routeData, route])
);
this.#routeCache = new RouteCache(defaultLogOptions); this.#routeCache = new RouteCache(defaultLogOptions);
this.#renderersPromise = this.#loadRenderers(); this.#renderersPromise = this.#loadRenderers();
} }
@ -35,19 +31,16 @@ export class App {
return matchRoute(pathname, this.#manifestData); return matchRoute(pathname, this.#manifestData);
} }
async render(url: URL, routeData?: RouteData): Promise<string> { async render(url: URL, routeData?: RouteData): Promise<string> {
if(!routeData) { if (!routeData) {
routeData = this.match(url); routeData = this.match(url);
if(!routeData) { if (!routeData) {
return 'Not found'; return 'Not found';
} }
} }
const manifest = this.#manifest; const manifest = this.#manifest;
const info = this.#routeDataToRouteInfo.get(routeData!)!; const info = this.#routeDataToRouteInfo.get(routeData!)!;
const [mod, renderers] = await Promise.all([ const [mod, renderers] = await Promise.all([this.#loadModule(info.file), this.#renderersPromise]);
this.#loadModule(info.file),
this.#renderersPromise
]);
const links = createLinkStylesheetElementSet(info.links, manifest.site); const links = createLinkStylesheetElementSet(info.links, manifest.site);
const scripts = createModuleScriptElementWithSrcSet(info.scripts, manifest.site); const scripts = createModuleScriptElementWithSrcSet(info.scripts, manifest.site);
@ -63,7 +56,7 @@ export class App {
scripts, scripts,
renderers, renderers,
async resolve(specifier: string) { async resolve(specifier: string) {
if(!(specifier in manifest.entryModules)) { if (!(specifier in manifest.entryModules)) {
throw new Error(`Unable to resolve [${specifier}]`); throw new Error(`Unable to resolve [${specifier}]`);
} }
const bundlePath = manifest.entryModules[specifier]; const bundlePath = manifest.entryModules[specifier];
@ -71,21 +64,23 @@ export class App {
}, },
route: routeData, route: routeData,
routeCache: this.#routeCache, routeCache: this.#routeCache,
site: this.#manifest.site site: this.#manifest.site,
}) });
} }
async #loadRenderers(): Promise<Renderer[]> { async #loadRenderers(): Promise<Renderer[]> {
const rendererNames = this.#manifest.renderers; const rendererNames = this.#manifest.renderers;
return await Promise.all(rendererNames.map(async (rendererName) => { return await Promise.all(
rendererNames.map(async (rendererName) => {
return createRenderer(rendererName, { return createRenderer(rendererName, {
renderer(name) { renderer(name) {
return import(name); return import(name);
}, },
server(entry) { server(entry) {
return import(entry); return import(entry);
} },
});
}) })
})); );
} }
async #loadModule(rootRelativePath: string): Promise<ComponentInstance> { async #loadModule(rootRelativePath: string): Promise<ComponentInstance> {
let modUrl = new URL(rootRelativePath, this.#rootFolder).toString(); let modUrl = new URL(rootRelativePath, this.#rootFolder).toString();
@ -93,7 +88,7 @@ export class App {
try { try {
mod = await import(modUrl); mod = await import(modUrl);
return mod; return mod;
} catch(err) { } catch (err) {
throw new Error(`Unable to import ${modUrl}. Does this file exist?`); 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'; import type { RouteData, SerializedRouteData, MarkdownRenderOptions } from '../../@types/astro';
export interface RouteInfo { export interface RouteInfo {
routeData: RouteData routeData: RouteData;
file: string; file: string;
links: string[]; links: string[];
scripts: string[]; scripts: string[];
@ -9,18 +9,18 @@ export interface RouteInfo {
export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & { export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
routeData: SerializedRouteData; routeData: SerializedRouteData;
} };
export interface SSRManifest { export interface SSRManifest {
routes: RouteInfo[]; routes: RouteInfo[];
site?: string; site?: string;
markdown: { markdown: {
render: MarkdownRenderOptions render: MarkdownRenderOptions;
}, };
renderers: string[]; renderers: string[];
entryModules: Record<string, string>; entryModules: Record<string, string>;
} }
export type SerializedSSRManifest = Omit<SSRManifest, 'routes'> & { export type SerializedSSRManifest = Omit<SSRManifest, 'routes'> & {
routes: SerializedRouteInfo[]; 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[]; const [ssrResult] = (await Promise.all([ssrBuild(opts, internals, pageInput), clientBuild(opts, internals, jsInput)])) as RollupOutput[];
// SSG mode, generate pages. // SSG mode, generate pages.
if(staticMode) { if (staticMode) {
// Generate each of the pages. // Generate each of the pages.
await generatePages(ssrResult, opts, internals, facadeIdToPageDataMap); await generatePages(ssrResult, opts, internals, facadeIdToPageDataMap);
await cleanSsrOutput(opts); await cleanSsrOutput(opts);
@ -189,7 +189,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
format: 'esm', format: 'esm',
entryFileNames: '[name].[hash].mjs', entryFileNames: '[name].[hash].mjs',
chunkFileNames: 'chunks/[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 target: 'esnext', // must match an esbuild target
@ -233,8 +233,7 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals,
format: 'esm', format: 'esm',
entryFileNames: '[name].[hash].js', entryFileNames: '[name].[hash].js',
chunkFileNames: 'chunks/[name].[hash].js', chunkFileNames: 'chunks/[name].[hash].js',
assetFileNames: 'assets/[name].[hash][extname]' assetFileNames: 'assets/[name].[hash][extname]',
}, },
preserveEntrySignatures: 'exports-only', preserveEntrySignatures: 'exports-only',
}, },
@ -400,10 +399,10 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
const data: ViteManifest = JSON.parse(inputManifestJSON); const data: ViteManifest = JSON.parse(inputManifestJSON);
const rootRelativeIdToChunkMap = new Map<string, OutputChunk>(); const rootRelativeIdToChunkMap = new Map<string, OutputChunk>();
for(const output of result.output) { for (const output of result.output) {
if(chunkIsPage(astroConfig, output, internals)) { if (chunkIsPage(astroConfig, output, internals)) {
const chunk = output as OutputChunk; const chunk = output as OutputChunk;
if(chunk.facadeModuleId) { if (chunk.facadeModuleId) {
const id = rootRelativeFacadeId(chunk.facadeModuleId, astroConfig); const id = rootRelativeFacadeId(chunk.facadeModuleId, astroConfig);
rootRelativeIdToChunkMap.set(id, chunk); rootRelativeIdToChunkMap.set(id, chunk);
} }
@ -412,11 +411,11 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
const routes: SerializedRouteInfo[] = []; const routes: SerializedRouteInfo[] = [];
for(const routeData of manifest.routes) { for (const routeData of manifest.routes) {
const componentPath = routeData.component; const componentPath = routeData.component;
const entry = data[componentPath]; const entry = data[componentPath];
if(!rootRelativeIdToChunkMap.has(componentPath)) { if (!rootRelativeIdToChunkMap.has(componentPath)) {
throw new Error('Unable to find chunk for ' + componentPath); throw new Error('Unable to find chunk for ' + componentPath);
} }
@ -430,7 +429,7 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
file: entry?.file, file: entry?.file,
links, links,
scripts, scripts,
routeData: serializeRouteData(routeData) routeData: serializeRouteData(routeData),
}); });
} }
@ -438,10 +437,10 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions,
routes, routes,
site: astroConfig.buildOptions.site, site: astroConfig.buildOptions.site,
markdown: { markdown: {
render: astroConfig.markdownOptions.render render: astroConfig.markdownOptions.render,
}, },
renderers: astroConfig.renderers, renderers: astroConfig.renderers,
entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries()) entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries()),
}; };
const outputManifestJSON = JSON.stringify(ssrManifest, null, ' '); const outputManifestJSON = JSON.stringify(ssrManifest, null, ' ');
@ -522,7 +521,7 @@ async function ssrMoveAssets(opts: StaticBuildOptions) {
await emptyDir(fileURLToPath(serverAssets)); await emptyDir(fileURLToPath(serverAssets));
if(fs.existsSync(serverAssets)) { if (fs.existsSync(serverAssets)) {
await fs.promises.rmdir(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.experimentalStaticBuild === 'boolean') astroConfig.buildOptions.experimentalStaticBuild = flags.experimentalStaticBuild;
if (typeof flags.experimentalSsr === 'boolean') { if (typeof flags.experimentalSsr === 'boolean') {
astroConfig.buildOptions.experimentalSsr = flags.experimentalSsr; astroConfig.buildOptions.experimentalSsr = flags.experimentalSsr;
if(flags.experimentalSsr) { if (flags.experimentalSsr) {
astroConfig.buildOptions.experimentalStaticBuild = true; astroConfig.buildOptions.experimentalStaticBuild = true;
} }
} }

View file

@ -49,9 +49,9 @@ async function getParamsAndProps(opts: GetParamsAndPropsOptions): Promise<[Param
interface RenderOptions { interface RenderOptions {
experimentalStaticBuild: boolean; experimentalStaticBuild: boolean;
logging: LogOptions, logging: LogOptions;
links: Set<SSRElement>; links: Set<SSRElement>;
markdownRender: MarkdownRenderOptions, markdownRender: MarkdownRenderOptions;
mod: ComponentInstance; mod: ComponentInstance;
origin: string; origin: string;
pathname: string; pathname: string;
@ -64,21 +64,7 @@ interface RenderOptions {
} }
export async function render(opts: RenderOptions): Promise<string> { export async function render(opts: RenderOptions): Promise<string> {
const { const { experimentalStaticBuild, links, logging, origin, markdownRender, mod, pathname, scripts, renderers, resolve, route, routeCache, site } = opts;
experimentalStaticBuild,
links,
logging,
origin,
markdownRender,
mod,
pathname,
scripts,
renderers,
resolve,
route,
routeCache,
site
} = opts;
const [params, pageProps] = await getParamsAndProps({ const [params, pageProps] = await getParamsAndProps({
logging, 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) 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})`); if (!Component.isAstroComponentFactory) throw new Error(`Unable to SSR non-Astro component (${route?.component})`);
const result = createResult({ const result = createResult({
experimentalStaticBuild, experimentalStaticBuild,
links, links,
@ -105,7 +90,7 @@ export async function render(opts: RenderOptions): Promise<string> {
resolve, resolve,
renderers, renderers,
site, site,
scripts scripts,
}); });
let html = await renderPage(result, Component, pageProps, null); 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; const { astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer } = ssrOpts;
// Add hoisted script tags // Add hoisted script tags
const scripts = createModuleScriptElementWithSrcSet(astroConfig.buildOptions.experimentalStaticBuild ? const scripts = createModuleScriptElementWithSrcSet(astroConfig.buildOptions.experimentalStaticBuild ? Array.from(mod.$$metadata.hoistedScriptPaths()) : []);
Array.from(mod.$$metadata.hoistedScriptPaths()) :
[]
);
// Inject HMR scripts // Inject HMR scripts
if (mode === 'development' && astroConfig.buildOptions.experimentalStaticBuild) { 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 { url } = await viteServer.moduleGraph.ensureEntryFromUrl(entry);
const mod = await viteServer.ssrLoadModule(url); const mod = await viteServer.ssrLoadModule(url);
return mod; return mod;
} },
}); });
return resolvedRenderer; 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. // The other entrypoints need to be loaded through Vite.
const { const {
default: { name, client, polyfills, hydrationPolyfills, server }, 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; resolvedRenderer.name = name;
if (client) resolvedRenderer.source = npath.posix.join(renderer, client); if (client) resolvedRenderer.source = npath.posix.join(renderer, client);

View file

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

View file

@ -4,7 +4,7 @@ import npath from 'path';
import { appendForwardSlash } from '../../core/path.js'; import { appendForwardSlash } from '../../core/path.js';
function getRootPath(site?: string): string { 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 { function joinToRoot(href: string, site?: string): string {
@ -15,14 +15,14 @@ export function createLinkStylesheetElement(href: string, site?: string): SSREle
return { return {
props: { props: {
rel: 'stylesheet', rel: 'stylesheet',
href: joinToRoot(href, site) href: joinToRoot(href, site),
}, },
children: '', children: '',
}; };
} }
export function createLinkStylesheetElementSet(hrefs: string[], site?: string) { 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 { export function createModuleScriptElementWithSrc(src: string, site?: string): SSRElement {
@ -32,9 +32,9 @@ export function createModuleScriptElementWithSrc(src: string, site?: string): SS
src: joinToRoot(src, site), src: joinToRoot(src, site),
}, },
children: '', children: '',
} };
} }
export function createModuleScriptElementWithSrcSet(srces: string[], site?: string): Set<SSRElement> { 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 { createRouteManifest } from './manifest/create.js';
export { export { serializeRouteData, deserializeRouteData } from './manifest/serialization.js';
serializeRouteData,
deserializeRouteData
} from './manifest/serialization.js';
export { matchRoute } from './match.js'; export { matchRoute } from './match.js';
export { getParams } from './params.js'; export { getParams } from './params.js';
export { export { validateGetStaticPathsModule, validateGetStaticPathsResult } from './validation.js';
validateGetStaticPathsModule,
validateGetStaticPathsResult
} from './validation.js';

View file

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

View file

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

View file

@ -1,10 +1,6 @@
import type { import type { ManifestData, RouteData } from '../../@types/astro';
ManifestData,
RouteData
} from '../../@types/astro';
/** Find matching route from pathname */ /** Find matching route from pathname */
export function matchRoute(pathname: string, manifest: ManifestData): RouteData | undefined { export function matchRoute(pathname: string, manifest: ManifestData): RouteData | undefined {
return manifest.routes.find((route) => route.pattern.test(pathname)); 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 * src/routes/[x]/[y]/[z]/svelte, create a function
* that turns a RegExpExecArray into ({ x, y, z }) * that turns a RegExpExecArray into ({ x, y, z })
*/ */
export function getParams(array: string[]) { export function getParams(array: string[]) {
const fn = (match: RegExpExecArray) => { const fn = (match: RegExpExecArray) => {
const params: Params = {}; const params: Params = {};
array.forEach((key, i) => { array.forEach((key, i) => {
@ -20,4 +20,3 @@ import type { Params } from '../../@types/astro';
return fn; return fn;
} }

View file

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