[ci] yarn format

This commit is contained in:
natemoo-re 2021-05-26 18:31:27 +00:00 committed by GitHub Actions
parent 643c880f28
commit 5fa7e354b3
26 changed files with 159 additions and 192 deletions

View file

@ -9,10 +9,11 @@ Updated the rendering pipeline for `astro` to truly support any framework.
For the vast majority of use cases, `astro` should _just work_ out of the box. Astro now depends on `@astro-renderer/preact`, `@astro-renderer/react`, `@astro-renderer/svelte`, and `@astro-renderer/vue`, rather than these being built into the core library. This opens the door for anyone to contribute additional renderers for Astro to support their favorite framework, as well as the ability for users to control which renderers should be used.
**Features**
- Expose a pluggable interface for controlling server-side rendering and client-side hydration
- Allows components from different frameworks to be nested within each other.
- Allows components from different frameworks to be nested within each other.
> Note: `svelte` currently does support non-destructive hydration, so components from other frameworks cannot currently be nested inside of a Svelte component. See https://github.com/sveltejs/svelte/issues/4308.
**Breaking Changes**
- To improve compiler performance, improve framework support, and minimize JS payloads, any children passed to hydrated components are automatically wrapped with an `<astro-fragment>` element.
- To improve compiler performance, improve framework support, and minimize JS payloads, any children passed to hydrated components are automatically wrapped with an `<astro-fragment>` element.

View file

@ -3,38 +3,7 @@
import entities from './entities.js';
const windows_1252 = [
8364,
129,
8218,
402,
8222,
8230,
8224,
8225,
710,
8240,
352,
8249,
338,
141,
381,
143,
144,
8216,
8217,
8220,
8221,
8226,
8211,
8212,
732,
8482,
353,
8250,
339,
157,
382,
376,
8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376,
];
const entity_pattern = new RegExp(`&(#?(?:x[\\w\\d]+|\\d+|${Object.keys(entities).join('|')}))(?:;|\\b)`, 'g');

View file

@ -125,9 +125,7 @@ export interface CollectionRSS<T = any> {
/** Specify custom data in opening of file */
customData?: string;
/** Return data about each item */
item: (
item: T
) => {
item: (item: T) => {
/** (required) Title of item */
title: string;
/** (required) Link to item */

View file

@ -1 +1 @@
export type GetHydrateCallback = () => Promise<(element: Element, innerHTML: string|null) => void>;
export type GetHydrateCallback = () => Promise<(element: Element, innerHTML: string | null) => void>;

View file

@ -103,6 +103,6 @@ export async function buildStaticPage({ astroConfig, buildState, filepath, runti
contentType: 'text/html',
encoding: 'utf8',
};
})
}),
]);
}

View file

@ -146,7 +146,8 @@ function getComponentWrapper(_name: string, { url, importSpecifier }: ComponentI
};
const getComponentExport = () => {
switch (importSpecifier.type) {
case 'ImportDefaultSpecifier': return { value: 'default' };
case 'ImportDefaultSpecifier':
return { value: 'default' };
case 'ImportSpecifier': {
if (importSpecifier.imported.type === 'Identifier') {
return { value: importSpecifier.imported.name };
@ -158,13 +159,13 @@ function getComponentWrapper(_name: string, { url, importSpecifier }: ComponentI
return { value };
}
}
}
};
const importInfo = kind ? { componentUrl: getComponentUrl(), componentExport: getComponentExport() } : {};
return {
wrapper: `__astro_component(${name}, ${JSON.stringify({ hydrate: kind, displayName: name, ...importInfo })})`,
wrapperImport: `import {__astro_component} from '${internalImport('__astro_component.js')}';`,
}
};
}
/** Evaluate expression (safely) */

View file

@ -16,7 +16,7 @@ export default function (): Transformer {
if (kind && !hasComponents) {
hasComponents = true;
}
}
},
},
Element: {
enter(node) {
@ -30,10 +30,11 @@ export default function (): Transformer {
body = node;
return;
}
default: return;
default:
return;
}
}
}
},
},
},
},
async finalize() {
@ -42,9 +43,7 @@ export default function (): Transformer {
const style: TemplateNode = {
type: 'Element',
name: 'style',
attributes: [
{ name: 'type', type: 'Attribute', value: [{ type: 'Text', raw: 'text/css', data: 'text/css' }] },
],
attributes: [{ name: 'type', type: 'Attribute', value: [{ type: 'Text', raw: 'text/css', data: 'text/css' }] }],
start: 0,
end: 0,
children: [
@ -53,9 +52,9 @@ export default function (): Transformer {
end: 0,
type: 'Text',
data: 'astro-root, astro-fragment { display: contents; }',
raw: 'astro-root, astro-fragment { display: contents; }'
}
]
raw: 'astro-root, astro-fragment { display: contents; }',
},
],
};
head.children = [...(head.children ?? []), style];
},

View file

@ -7,17 +7,17 @@ import * as astro from './renderer-astro';
// see https://github.com/remcohaszing/estree-util-value-to-estree#readme
const serialize = (value: Value) => generate(valueToEstree(value));
/**
* These values are dynamically injected by Snowpack.
* See comment in `snowpack-plugin.cjs`!
*
* In a world where Snowpack supports virtual files, this won't be necessary.
* It would ideally look something like:
*
* ```ts
* import { __rendererSources, __renderers } from "virtual:astro/runtime"
* ```
*/
/**
* These values are dynamically injected by Snowpack.
* See comment in `snowpack-plugin.cjs`!
*
* In a world where Snowpack supports virtual files, this won't be necessary.
* It would ideally look something like:
*
* ```ts
* import { __rendererSources, __renderers } from "virtual:astro/runtime"
* ```
*/
declare let __rendererSources: string[];
declare let __renderers: any[];
@ -33,7 +33,7 @@ function resolveRenderer(Component: any, props: any = {}) {
}
for (const __renderer of __renderers) {
const shouldUse = __renderer.check(Component, props)
const shouldUse = __renderer.check(Component, props);
if (shouldUse) {
rendererCache.set(Component, __renderer);
return __renderer;
@ -43,15 +43,14 @@ function resolveRenderer(Component: any, props: any = {}) {
interface AstroComponentProps {
displayName: string;
hydrate?: 'load'|'idle'|'visible';
componentUrl?: string;
componentExport?: { value: string, namespace?: boolean };
hydrate?: 'load' | 'idle' | 'visible';
componentUrl?: string;
componentExport?: { value: string; namespace?: boolean };
}
/** For hydrated components, generate a <script type="module"> to load the component */
async function generateHydrateScript({ renderer, astroId, props }: any, { hydrate, componentUrl, componentExport }: Required<AstroComponentProps>) {
const rendererSource = __rendererSources[__renderers.findIndex(r => r === renderer)];
const rendererSource = __rendererSources[__renderers.findIndex((r) => r === renderer)];
const script = `<script type="module">
import setup from '/_astro_internal/hydrate/${hydrate}.js';
@ -64,8 +63,7 @@ setup("${astroId}", async () => {
return script;
}
export const __astro_component = (Component: any, componentProps: AstroComponentProps = {} as any) => {
export const __astro_component = (Component: any, componentProps: AstroComponentProps = {} as any) => {
if (Component == null) {
throw new Error(`Unable to render <${componentProps.displayName}> because it is ${Component}!\nDid you forget to import the component or is it possible there is a typo?`);
}
@ -73,28 +71,28 @@ export const __astro_component = (Component: any, componentProps: AstroComponent
let renderer = resolveRenderer(Component);
return async (props: any, ..._children: string[]) => {
if (!renderer) {
// Second attempt at resolving a renderer (this time we have props!)
renderer = resolveRenderer(Component, props);
if (!renderer) {
// Second attempt at resolving a renderer (this time we have props!)
renderer = resolveRenderer(Component, props);
// Okay now we definitely can't resolve a renderer, so let's throw
if (!renderer) {
const name = typeof Component === 'function' ? (Component.displayName ?? Component.name) : `{ ${Object.keys(Component).join(', ')} }`;
throw new Error(`No renderer found for ${name}! Did you forget to add a renderer to your Astro config?`);
}
// Okay now we definitely can't resolve a renderer, so let's throw
if (!renderer) {
const name = typeof Component === 'function' ? Component.displayName ?? Component.name : `{ ${Object.keys(Component).join(', ')} }`;
throw new Error(`No renderer found for ${name}! Did you forget to add a renderer to your Astro config?`);
}
const children = _children.join('\n');
const { html } = await renderer.renderToStaticMarkup(Component, props, children);
// If we're NOT hydrating this component, just return the HTML
if (!componentProps.hydrate) {
// It's safe to remove <astro-fragment>, static content doesn't need the wrapper
return html.replace(/\<\/?astro-fragment\>/g, '');
};
// If we ARE hydrating this component, let's generate the hydration script
const astroId = hash.unique(html);
const script = await generateHydrateScript({ renderer, astroId, props }, componentProps as Required<AstroComponentProps>)
const astroRoot = `<astro-root uid="${astroId}">${html}</astro-root>`;
return [astroRoot, script].join('\n');
}
}
}
const children = _children.join('\n');
const { html } = await renderer.renderToStaticMarkup(Component, props, children);
// If we're NOT hydrating this component, just return the HTML
if (!componentProps.hydrate) {
// It's safe to remove <astro-fragment>, static content doesn't need the wrapper
return html.replace(/\<\/?astro-fragment\>/g, '');
}
// If we ARE hydrating this component, let's generate the hydration script
const astroId = hash.unique(html);
const script = await generateHydrateScript({ renderer, astroId, props }, componentProps as Required<AstroComponentProps>);
const astroRoot = `<astro-root uid="${astroId}">${html}</astro-root>`;
return [astroRoot, script].join('\n');
};
};

View file

@ -4,5 +4,5 @@ export function check(Component: any) {
export async function renderToStaticMarkup(Component: any, props: any, children: string) {
const html = await Component.__render(props, children);
return { html }
};
return { html };
}

View file

@ -266,12 +266,7 @@ interface CreateSnowpackOptions {
resolvePackageUrl?: (pkgName: string) => Promise<string>;
}
const defaultRenderers = [
'@astro-renderer/vue',
'@astro-renderer/svelte',
'@astro-renderer/react',
'@astro-renderer/preact'
];
const defaultRenderers = ['@astro-renderer/vue', '@astro-renderer/svelte', '@astro-renderer/react', '@astro-renderer/preact'];
/** Create a new Snowpack instance to power Astro */
async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackOptions) {
@ -284,7 +279,7 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO
let snowpack: SnowpackDevServer;
let astroPluginOptions: {
resolvePackageUrl?: (s: string) => Promise<string>;
renderers?: { name: string, client: string, server: string }[];
renderers?: { name: string; client: string; server: string }[];
astroConfig: AstroConfig;
} = {
astroConfig,
@ -305,42 +300,41 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO
(process.env as any).TAILWIND_DISABLE_TOUCH = true;
}
const rendererInstances = (await Promise.all(renderers.map(renderer => import(pathToFileURL(resolveDependency(renderer)).toString()))))
.map(({ default: raw }, i) => {
const { name = renderers[i], client, server, snowpackPlugin: snowpackPluginName, snowpackPluginOptions } = raw;
const rendererInstances = (await Promise.all(renderers.map((renderer) => import(pathToFileURL(resolveDependency(renderer)).toString())))).map(({ default: raw }, i) => {
const { name = renderers[i], client, server, snowpackPlugin: snowpackPluginName, snowpackPluginOptions } = raw;
if (typeof client !== 'string') {
throw new Error(`Expected "client" from ${name} to be a relative path to the client-side renderer!`);
}
if (typeof client !== 'string') {
throw new Error(`Expected "client" from ${name} to be a relative path to the client-side renderer!`);
}
if (typeof server !== 'string') {
throw new Error(`Expected "server" from ${name} to be a relative path to the server-side renderer!`);
}
let snowpackPlugin: string|[string, any]|undefined;
if (typeof snowpackPluginName === 'string') {
if (snowpackPluginOptions) {
snowpackPlugin = [resolveDependency(snowpackPluginName), snowpackPluginOptions]
} else {
snowpackPlugin = resolveDependency(snowpackPluginName);
}
} else if (snowpackPluginName) {
throw new Error(`Expected the snowpackPlugin from ${name} to be a "string" but encountered "${typeof snowpackPluginName}"!`);
}
if (typeof server !== 'string') {
throw new Error(`Expected "server" from ${name} to be a relative path to the server-side renderer!`);
}
return {
name,
snowpackPlugin,
client: path.join(name, raw.client),
server: path.join(name, raw.server),
let snowpackPlugin: string | [string, any] | undefined;
if (typeof snowpackPluginName === 'string') {
if (snowpackPluginOptions) {
snowpackPlugin = [resolveDependency(snowpackPluginName), snowpackPluginOptions];
} else {
snowpackPlugin = resolveDependency(snowpackPluginName);
}
})
} else if (snowpackPluginName) {
throw new Error(`Expected the snowpackPlugin from ${name} to be a "string" but encountered "${typeof snowpackPluginName}"!`);
}
return {
name,
snowpackPlugin,
client: path.join(name, raw.client),
server: path.join(name, raw.server),
};
});
astroPluginOptions.renderers = rendererInstances;
// Make sure that Snowpack builds our renderer plugins
const knownEntrypoints = [].concat(...rendererInstances.map(renderer => [renderer.server, renderer.client]) as any) as string[];
const rendererSnowpackPlugins = rendererInstances.filter(renderer => renderer.snowpackPlugin).map(renderer => renderer.snowpackPlugin) as string|[string, any];
const knownEntrypoints = [].concat(...(rendererInstances.map((renderer) => [renderer.server, renderer.client]) as any)) as string[];
const rendererSnowpackPlugins = rendererInstances.filter((renderer) => renderer.snowpackPlugin).map((renderer) => renderer.snowpackPlugin) as string | [string, any];
const snowpackConfig = await loadConfiguration({
root: fileURLToPath(projectRoot),
@ -395,7 +389,11 @@ export async function createRuntime(astroConfig: AstroConfig, { mode, logging }:
const resolvePackageUrl = async (pkgName: string) => frontendSnowpack.getUrlForPackage(pkgName);
timer.backend = performance.now();
const { snowpack: backendSnowpack, snowpackRuntime: backendSnowpackRuntime, snowpackConfig: backendSnowpackConfig } = await createSnowpack(astroConfig, {
const {
snowpack: backendSnowpack,
snowpackRuntime: backendSnowpackRuntime,
snowpackConfig: backendSnowpackConfig,
} = await createSnowpack(astroConfig, {
env: {
astro: true,
},
@ -405,7 +403,11 @@ export async function createRuntime(astroConfig: AstroConfig, { mode, logging }:
debug(logging, 'core', `backend snowpack created [${stopTimer(timer.backend)}]`);
timer.frontend = performance.now();
const { snowpack: frontendSnowpack, snowpackRuntime: frontendSnowpackRuntime, snowpackConfig: frontendSnowpackConfig } = await createSnowpack(astroConfig, {
const {
snowpack: frontendSnowpack,
snowpackRuntime: frontendSnowpackRuntime,
snowpackConfig: frontendSnowpackConfig,
} = await createSnowpack(astroConfig, {
env: {
astro: false,
},

View file

@ -2,4 +2,4 @@ export default {
name: '@astro-renderer/preact',
client: './client',
server: './server',
}
};

View file

@ -7,14 +7,14 @@ function check(Component, props) {
return Boolean(renderToString(h(Component, props)));
} catch (e) {}
return false;
};
}
function renderToStaticMarkup(Component, props, children) {
const html = renderToString(h(Component, props, h(StaticHtml, { value: children })))
const html = renderToString(h(Component, props, h(StaticHtml, { value: children })));
return { html };
}
export default {
check,
renderToStaticMarkup
}
export default {
check,
renderToStaticMarkup,
};

View file

@ -9,16 +9,16 @@ import { h } from 'preact';
*/
const StaticHtml = ({ value }) => {
if (!value) return null;
return h('astro-fragment', { dangerouslySetInnerHTML: { __html: value }});
}
return h('astro-fragment', { dangerouslySetInnerHTML: { __html: value } });
};
/**
* This tells Preact to opt-out of re-rendering this subtree,
* In addition to being a performance optimization,
* this also allows other frameworks to attach to `children`.
*
* See https://preactjs.com/guide/v8/external-dom-mutations
*/
* This tells Preact to opt-out of re-rendering this subtree,
* In addition to being a performance optimization,
* this also allows other frameworks to attach to `children`.
*
* See https://preactjs.com/guide/v8/external-dom-mutations
*/
StaticHtml.shouldComponentUpdate = () => false;
export default StaticHtml;

View file

@ -2,4 +2,5 @@ import { createElement } from 'react';
import { hydrate } from 'react-dom';
import StaticHtml from './static-html.js';
export default (element) => (Component, props, children) => hydrate(createElement(Component, { ...props, suppressHydrationWarning: true }, createElement(StaticHtml, { value: children, suppressHydrationWarning: true })), element);
export default (element) => (Component, props, children) =>
hydrate(createElement(Component, { ...props, suppressHydrationWarning: true }, createElement(StaticHtml, { value: children, suppressHydrationWarning: true })), element);

View file

@ -2,4 +2,4 @@ export default {
name: '@astro-renderer/react',
client: './client',
server: './server',
}
};

View file

@ -7,14 +7,14 @@ function check(Component, props) {
return Boolean(renderToString(h(Component, props)));
} catch (e) {}
return false;
};
}
function renderToStaticMarkup(Component, props, children) {
const html = renderToString(h(Component, props, h(StaticHtml, { value: children })))
const html = renderToString(h(Component, props, h(StaticHtml, { value: children })));
return { html };
}
export default {
check,
renderToStaticMarkup
export default {
check,
renderToStaticMarkup,
};

View file

@ -9,16 +9,16 @@ import { createElement as h } from 'react';
*/
const StaticHtml = ({ value }) => {
if (!value) return null;
return h('astro-fragment', { suppressHydrationWarning: true, dangerouslySetInnerHTML: { __html: value }});
}
return h('astro-fragment', { suppressHydrationWarning: true, dangerouslySetInnerHTML: { __html: value } });
};
/**
* This tells React to opt-out of re-rendering this subtree,
* In addition to being a performance optimization,
* this also allows other frameworks to attach to `children`.
*
* See https://preactjs.com/guide/v8/external-dom-mutations
*/
* This tells React to opt-out of re-rendering this subtree,
* In addition to being a performance optimization,
* this also allows other frameworks to attach to `children`.
*
* See https://preactjs.com/guide/v8/external-dom-mutations
*/
StaticHtml.shouldComponentUpdate = () => false;
export default StaticHtml;

View file

@ -7,7 +7,7 @@ export default (target) => {
target,
props: { __astro_component: component, __astro_children: children, ...props },
hydrate: true,
});
});
} catch (e) {}
}
}
};
};

View file

@ -3,5 +3,5 @@ export default {
snowpackPlugin: '@snowpack/plugin-svelte',
snowpackPluginOptions: { compilerOptions: { hydratable: true } },
client: './client',
server: './server'
server: './server',
};

View file

@ -1,15 +1,15 @@
import SvelteWrapper from './Wrapper.svelte';
function check(Component) {
function check(Component) {
return Component['render'] && Component['$$render'];
}
async function renderToStaticMarkup (Component, props, children) {
async function renderToStaticMarkup(Component, props, children) {
const { html } = SvelteWrapper.render({ __astro_component: Component, __astro_children: children, ...props });
return { html };
}
export default {
check,
renderToStaticMarkup
renderToStaticMarkup,
};

View file

@ -2,6 +2,6 @@ import { h, createSSRApp } from 'vue';
import StaticHtml from './static-html.js';
export default (element) => (Component, props, children) => {
const app = createSSRApp({ render: () => h(Component, props, { default: () => h(StaticHtml, { value: children }) })});
app.mount(element, true);
const app = createSSRApp({ render: () => h(Component, props, { default: () => h(StaticHtml, { value: children }) }) });
app.mount(element, true);
};

View file

@ -2,5 +2,5 @@ export default {
name: '@astro-renderer/vue',
snowpackPlugin: '@snowpack/plugin-vue',
client: './client',
server: './server'
server: './server',
};

View file

@ -7,12 +7,12 @@ function check(Component) {
}
async function renderToStaticMarkup(Component, props, children) {
const app = createSSRApp({ render: () => h(Component, props, { default: () => h(StaticHtml, { value: children }) })});
const app = createSSRApp({ render: () => h(Component, props, { default: () => h(StaticHtml, { value: children }) }) });
const html = await renderToString(app);
return { html };
}
export default {
check,
renderToStaticMarkup
}
renderToStaticMarkup,
};

View file

@ -8,20 +8,20 @@ import { h, defineComponent } from 'vue';
*/
const StaticHtml = defineComponent({
props: {
value: String
value: String,
},
setup({ value }) {
if (!value) return () => null;
return () => h('astro-fragment', { innerHTML: value })
}
})
return () => h('astro-fragment', { innerHTML: value });
},
});
/**
* Other frameworks have `shouldComponentUpdate` in order to signal
* that this subtree is entirely static and will not be updated
*
* Fortunately, Vue is smart enough to figure that out without any
* help from us, so this just works out of the box!
*/
/**
* Other frameworks have `shouldComponentUpdate` in order to signal
* that this subtree is entirely static and will not be updated
*
* Fortunately, Vue is smart enough to figure that out without any
* help from us, so this just works out of the box!
*/
export default StaticHtml;

View file

@ -211,7 +211,7 @@ export class TypeScriptDocumentSnapshot implements DocumentSnapshot {
}
async getFragment(): Promise<DocumentFragmentSnapshot> {
return (this as unknown) as any;
return this as unknown as any;
}
destroyFragment() {

View file

@ -61,9 +61,7 @@ export class LanguageServiceManager {
return tsService.updateDocument(pathOrDoc);
}
async getTypeScriptDoc(
document: Document
): Promise<{
async getTypeScriptDoc(document: Document): Promise<{
tsDoc: DocumentSnapshot;
lang: ts.LanguageService;
}> {