0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00

[ci] format

This commit is contained in:
natemoo-re 2022-06-30 18:11:12 +00:00 committed by fredkbot
parent 032ad1c047
commit af23bdd515
14 changed files with 95 additions and 99 deletions

View file

@ -4,8 +4,5 @@ import preact from '@astrojs/preact';
// https://astro.build/config // https://astro.build/config
export default defineConfig({ export default defineConfig({
integrations: [ integrations: [mdx(), preact()],
mdx(),
preact()
]
}); });

View file

@ -1,19 +1,17 @@
import Counter from '../components/Counter.jsx' import Counter from '../components/Counter.jsx';
import Title from '../components/Title.astro' import Title from '../components/Title.astro';
export const components = { h1: Title } export const components = { h1: Title };
# Hello world! # Hello world!
export const authors = [ export const authors = [
{name: 'Jane', email: 'hi@jane.com'}, { name: 'Jane', email: 'hi@jane.com' },
{name: 'John', twitter: '@john2002'} { name: 'John', twitter: '@john2002' },
] ];
export const published = new Date('2022-02-01') export const published = new Date('2022-02-01');
Written by: {new Intl.ListFormat('en').format(authors.map(d => d.name))}. Written by: {new Intl.ListFormat('en').format(authors.map(d => d.name))}.
Published on: {new Intl.DateTimeFormat('en', {dateStyle: 'long'}).format(published)}. Published on: {new Intl.DateTimeFormat('en', {dateStyle: 'long'}).format(published)}.
<Counter client:idle> <Counter client:idle>## Counter</Counter>
## Counter
</Counter>

View file

@ -939,9 +939,10 @@ export interface SSRLoadedRenderer extends AstroRenderer {
}; };
} }
export type HookParameters<Hook extends keyof AstroIntegration['hooks'], Fn = AstroIntegration['hooks'][Hook]> = Fn extends (...args: any) => any export type HookParameters<
? Parameters<Fn>[0] Hook extends keyof AstroIntegration['hooks'],
: never; Fn = AstroIntegration['hooks'][Hook]
> = Fn extends (...args: any) => any ? Parameters<Fn>[0] : never;
export interface AstroIntegration { export interface AstroIntegration {
/** The name of the integration. */ /** The name of the integration. */

View file

@ -346,9 +346,7 @@ export async function validateConfig(
adapter: undefined, adapter: undefined,
}, },
}; };
if ( if (result.integrations.find((integration) => integration.name === '@astrojs/mdx')) {
result.integrations.find((integration) => integration.name === '@astrojs/mdx')
) {
// Enable default JSX integration. It needs to come first, so unshift rather than push! // Enable default JSX integration. It needs to come first, so unshift rather than push!
const { default: jsxRenderer } = await import('../jsx/renderer.js'); const { default: jsxRenderer } = await import('../jsx/renderer.js');
(result._ctx.renderers as any[]).unshift(jsxRenderer); (result._ctx.renderers as any[]).unshift(jsxRenderer);

View file

@ -140,9 +140,11 @@ function getPluginName(plugin: vite.PluginOption) {
function sortPlugins(result: ViteConfigWithSSR) { function sortPlugins(result: ViteConfigWithSSR) {
// HACK: move mdxPlugin to top because it needs to run before internal JSX plugin // HACK: move mdxPlugin to top because it needs to run before internal JSX plugin
const mdxPluginIndex = result.plugins?.findIndex(plugin => getPluginName(plugin) === '@mdx-js/rollup') ?? -1; const mdxPluginIndex =
result.plugins?.findIndex((plugin) => getPluginName(plugin) === '@mdx-js/rollup') ?? -1;
if (mdxPluginIndex === -1) return; if (mdxPluginIndex === -1) return;
const jsxPluginIndex = result.plugins?.findIndex(plugin => getPluginName(plugin) === 'astro:jsx') ?? -1; const jsxPluginIndex =
result.plugins?.findIndex((plugin) => getPluginName(plugin) === 'astro:jsx') ?? -1;
const mdxPlugin = result.plugins?.[mdxPluginIndex]; const mdxPlugin = result.plugins?.[mdxPluginIndex];
result.plugins?.splice(mdxPluginIndex, 1); result.plugins?.splice(mdxPluginIndex, 1);
result.plugins?.splice(jsxPluginIndex, 0, mdxPlugin); result.plugins?.splice(jsxPluginIndex, 0, mdxPlugin);

View file

@ -9,7 +9,7 @@ import type {
} from '../../@types/astro'; } from '../../@types/astro';
import type { LogOptions } from '../logger/core.js'; import type { LogOptions } from '../logger/core.js';
import { renderComponent, renderPage } from '../../runtime/server/index.js'; import { renderPage } from '../../runtime/server/index.js';
import { getParams } from '../routing/params.js'; import { getParams } from '../routing/params.js';
import { createResult } from './result.js'; import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js'; import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';

View file

@ -2,9 +2,9 @@ import type { AddressInfo } from 'net';
import type { ViteDevServer } from 'vite'; import type { ViteDevServer } from 'vite';
import { import {
AstroConfig, AstroConfig,
HookParameters,
AstroRenderer, AstroRenderer,
BuildConfig, BuildConfig,
HookParameters,
RouteData, RouteData,
} from '../@types/astro.js'; } from '../@types/astro.js';
import ssgAdapter from '../adapter-ssg/index.js'; import ssgAdapter from '../adapter-ssg/index.js';
@ -58,9 +58,7 @@ export async function runHookConfigSetup({
}; };
// Semi-private `addPageExtension` hook // Semi-private `addPageExtension` hook
function addPageExtension(...input: (string | string[])[]) { function addPageExtension(...input: (string | string[])[]) {
const exts = (input.flat(Infinity) as string[]).map( const exts = (input.flat(Infinity) as string[]).map((ext) => `.${ext.replace(/^\./, '')}`);
(ext) => `.${ext.replace(/^\./, '')}`
);
updatedConfig._ctx.pageExtensions.push(...exts); updatedConfig._ctx.pageExtensions.push(...exts);
} }
Object.defineProperty(hooks, 'addPageExtension', { Object.defineProperty(hooks, 'addPageExtension', {

View file

@ -166,9 +166,7 @@ function formatList(values: string[]): string {
return `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`; return `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
} }
const rendererAliases = new Map([ const rendererAliases = new Map([['solid', 'solid-js']]);
['solid', 'solid-js']
])
export async function renderComponent( export async function renderComponent(
result: SSRResult, result: SSRResult,
@ -283,7 +281,9 @@ Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`')
// Attempt: use explicitly passed renderer name // Attempt: use explicitly passed renderer name
if (metadata.hydrateArgs) { if (metadata.hydrateArgs) {
const passedName = metadata.hydrateArgs; const passedName = metadata.hydrateArgs;
const rendererName = rendererAliases.has(passedName) ? rendererAliases.get(passedName) : passedName; const rendererName = rendererAliases.has(passedName)
? rendererAliases.get(passedName)
: passedName;
renderer = renderers.filter( renderer = renderers.filter(
({ name }) => name === `@astrojs/${rendererName}` || name === rendererName ({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
)[0]; )[0];
@ -709,16 +709,22 @@ export async function renderPage(
let iterable: AsyncIterable<any>; let iterable: AsyncIterable<any>;
if (!componentFactory.isAstroComponentFactory) { if (!componentFactory.isAstroComponentFactory) {
const pageProps: Record<string, any> = { ...(props ?? {}), 'server:root': true }; const pageProps: Record<string, any> = { ...(props ?? {}), 'server:root': true };
const output = await renderComponent(result, componentFactory.name, componentFactory, pageProps, null); const output = await renderComponent(
let html = output.toString() result,
componentFactory.name,
componentFactory,
pageProps,
null
);
let html = output.toString();
if (!/<!doctype html/i.test(html)) { if (!/<!doctype html/i.test(html)) {
html = `<!DOCTYPE html>\n${await maybeRenderHead(result)}${html}`; html = `<!DOCTYPE html>\n${await maybeRenderHead(result)}${html}`;
} }
return new Response(html, { return new Response(html, {
headers: new Headers([ headers: new Headers([
['Content-Type', 'text/html; charset=utf-8'], ['Content-Type', 'text/html; charset=utf-8'],
['Content-Length', `${Buffer.byteLength(html, 'utf-8')}`] ['Content-Length', `${Buffer.byteLength(html, 'utf-8')}`],
]) ]),
}); });
} }
const factoryReturnValue = await componentFactory(result, props, children); const factoryReturnValue = await componentFactory(result, props, children);

View file

@ -28,13 +28,16 @@ export async function renderJSX(result: any, vnode: any): Promise<any> {
let props: Record<string, any> = {}; let props: Record<string, any> = {};
let slots: Record<string, any> = {}; let slots: Record<string, any> = {};
for (const [key, value] of Object.entries(vnode.props ?? {})) { for (const [key, value] of Object.entries(vnode.props ?? {})) {
if (key === 'children' || value && typeof value === 'object' && (value as any)['$$slot']) { if (
key === 'children' ||
(value && typeof value === 'object' && (value as any)['$$slot'])
) {
slots[key === 'children' ? 'default' : key] = () => renderJSX(result, value); slots[key === 'children' ? 'default' : key] = () => renderJSX(result, value);
} else { } else {
props[key] = value; props[key] = value;
} }
} }
return await renderToString(result, vnode.type, props, slots) return await renderToString(result, vnode.type, props, slots);
} }
} }
if (vnode[AstroJSX]) { if (vnode[AstroJSX]) {

View file

@ -165,7 +165,6 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
} }
} }
// if no imports were found, look for @jsxImportSource comment // if no imports were found, look for @jsxImportSource comment
if (!importSource) { if (!importSource) {
const multiline = code.match(/\/\*\*?[\S\s]*\*\//gm) || []; const multiline = code.match(/\/\*\*?[\S\s]*\*\//gm) || [];

View file

@ -71,7 +71,7 @@ export async function loadFixture(inlineConfig) {
cwd = new URL(cwd.replace(/\/?$/, '/'), import.meta.url); cwd = new URL(cwd.replace(/\/?$/, '/'), import.meta.url);
} }
} }
// Load the config. // Load the config.
let config = await loadConfig({ cwd: fileURLToPath(cwd) }); let config = await loadConfig({ cwd: fileURLToPath(cwd) });
config = merge(config, { ...inlineConfig, root: cwd }); config = merge(config, { ...inlineConfig, root: cwd });
@ -83,7 +83,7 @@ export async function loadFixture(inlineConfig) {
if (inlineConfig.base && !inlineConfig.base.endsWith('/')) { if (inlineConfig.base && !inlineConfig.base.endsWith('/')) {
config.base = inlineConfig.base + '/'; config.base = inlineConfig.base + '/';
} }
if (config.integrations.find(integration => integration.name === '@astrojs/mdx')) { if (config.integrations.find((integration) => integration.name === '@astrojs/mdx')) {
// Enable default JSX integration. It needs to come first, so unshift rather than push! // Enable default JSX integration. It needs to come first, so unshift rather than push!
const { default: jsxRenderer } = await import('astro/jsx/renderer.js'); const { default: jsxRenderer } = await import('astro/jsx/renderer.js');
config._ctx.renderers.unshift(jsxRenderer); config._ctx.renderers.unshift(jsxRenderer);

View file

@ -1,39 +1,39 @@
import type { AstroIntegration } from 'astro';
import mdxPlugin from '@mdx-js/rollup'; import mdxPlugin from '@mdx-js/rollup';
import type { AstroIntegration } from 'astro';
export default function mdx(): AstroIntegration { export default function mdx(): AstroIntegration {
return { return {
name: '@astrojs/mdx', name: '@astrojs/mdx',
hooks: { hooks: {
'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => { 'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => {
addPageExtension('.mdx'); addPageExtension('.mdx');
updateConfig({ updateConfig({
vite: { vite: {
plugins: [ plugins: [
{ {
enforce: 'pre', enforce: 'pre',
...mdxPlugin({ ...mdxPlugin({
jsx: true, jsx: true,
jsxImportSource: 'astro', jsxImportSource: 'astro',
// Note: disable `.md` support // Note: disable `.md` support
format: 'mdx', format: 'mdx',
mdExtensions: [] mdExtensions: [],
}) }),
}, },
command === 'dev' && { command === 'dev' && {
name: '@astrojs/mdx', name: '@astrojs/mdx',
transform(code: string, id: string) { transform(code: string, id: string) {
if (!id.endsWith('.mdx')) return; if (!id.endsWith('.mdx')) return;
// TODO: decline HMR updates until we have a stable approach // TODO: decline HMR updates until we have a stable approach
return `${code}\nif (import.meta.hot) { return `${code}\nif (import.meta.hot) {
import.meta.hot.decline(); import.meta.hot.decline();
}` }`;
} },
} },
] ],
} },
}) });
} },
} },
} };
} }

View file

@ -1,18 +1,16 @@
import mdx from '@astrojs/mdx'; import mdx from '@astrojs/mdx';
import { expect } from 'chai'; import { expect } from 'chai';
import { parseHTML } from 'linkedom' import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js'; import { loadFixture } from '../../../astro/test/test-utils.js';
describe('MDX Component', () => { describe('MDX Component', () => {
let fixture; let fixture;
before(async () => { before(async () => {
fixture = await loadFixture({ fixture = await loadFixture({
root: new URL('./fixtures/mdx-component/', import.meta.url), root: new URL('./fixtures/mdx-component/', import.meta.url),
integrations: [ integrations: [mdx()],
mdx()
]
}); });
}); });
@ -21,22 +19,21 @@ describe('MDX Component', () => {
await fixture.build(); await fixture.build();
}); });
it('works', async () => { it('works', async () => {
const html = await fixture.readFile('/index.html'); const html = await fixture.readFile('/index.html');
const { document } = parseHTML(html); const { document } = parseHTML(html);
const h1 = document.querySelector('h1'); const h1 = document.querySelector('h1');
const foo = document.querySelector('#foo'); const foo = document.querySelector('#foo');
expect(h1.textContent).to.equal('Hello component!'); expect(h1.textContent).to.equal('Hello component!');
expect(foo.textContent).to.equal('bar'); expect(foo.textContent).to.equal('bar');
}); });
}) });
describe('dev', () => { describe('dev', () => {
let devServer; let devServer;
before(async () => { before(async () => {
devServer = await fixture.startDevServer(); devServer = await fixture.startDevServer();
}); });
@ -52,12 +49,12 @@ describe('MDX Component', () => {
const html = await res.text(); const html = await res.text();
const { document } = parseHTML(html); const { document } = parseHTML(html);
const h1 = document.querySelector('h1'); const h1 = document.querySelector('h1');
const foo = document.querySelector('#foo'); const foo = document.querySelector('#foo');
expect(h1.textContent).to.equal('Hello component!'); expect(h1.textContent).to.equal('Hello component!');
expect(foo.textContent).to.equal('bar'); expect(foo.textContent).to.equal('bar');
}); });
}) });
}) });

View file

@ -1,18 +1,16 @@
import mdx from '@astrojs/mdx'; import mdx from '@astrojs/mdx';
import { expect } from 'chai'; import { expect } from 'chai';
import { parseHTML } from 'linkedom' import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js'; import { loadFixture } from '../../../astro/test/test-utils.js';
describe('MDX Page', () => { describe('MDX Page', () => {
let fixture; let fixture;
before(async () => { before(async () => {
fixture = await loadFixture({ fixture = await loadFixture({
root: new URL('./fixtures/mdx-page/', import.meta.url), root: new URL('./fixtures/mdx-page/', import.meta.url),
integrations: [ integrations: [mdx()],
mdx()
]
}); });
}); });
@ -21,20 +19,19 @@ describe('MDX Page', () => {
await fixture.build(); await fixture.build();
}); });
it('works', async () => { it('works', async () => {
const html = await fixture.readFile('/index.html'); const html = await fixture.readFile('/index.html');
const { document } = parseHTML(html); const { document } = parseHTML(html);
const h1 = document.querySelector('h1'); const h1 = document.querySelector('h1');
expect(h1.textContent).to.equal('Hello page!'); expect(h1.textContent).to.equal('Hello page!');
}); });
}) });
describe('dev', () => { describe('dev', () => {
let devServer; let devServer;
before(async () => { before(async () => {
devServer = await fixture.startDevServer(); devServer = await fixture.startDevServer();
}); });
@ -45,15 +42,15 @@ describe('MDX Page', () => {
it('works', async () => { it('works', async () => {
const res = await fixture.fetch('/'); const res = await fixture.fetch('/');
expect(res.status).to.equal(200); expect(res.status).to.equal(200);
const html = await res.text(); const html = await res.text();
const { document } = parseHTML(html); const { document } = parseHTML(html);
const h1 = document.querySelector('h1'); const h1 = document.querySelector('h1');
expect(h1.textContent).to.equal('Hello page!'); expect(h1.textContent).to.equal('Hello page!');
}); });
}) });
}) });