Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tag JSX exports with astro:renderer #3926

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 47 additions & 23 deletions packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ const svgEnumAttributes = /^(autoReverse|externalResourcesRequired|focusable|pre
// Or maybe type UserValue = any; ?
async function* _render(child: any): AsyncIterable<any> {
child = await child;
if (child instanceof HTMLString) {
if (child instanceof Error) {
throw child;
} else if (child instanceof HTMLString) {
yield child;
} else if (Array.isArray(child)) {
for (const value of child) {
Expand Down Expand Up @@ -181,6 +183,17 @@ function formatList(values: string[]): string {

const rendererAliases = new Map([['solid', 'solid-js']]);

/** @internal */
export function __astro_tag_component__(Component: unknown, rendererName: string) {
if (!Component) return;
if (typeof Component !== 'function') return;
Object.defineProperty(Component, 'astro:renderer', {
value: rendererName,
writable: false,
enumerable: false
})
}

export async function renderComponent(
result: SSRResult,
displayName: string,
Expand Down Expand Up @@ -269,20 +282,27 @@ Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`')
// Call the renderers `check` hook to see if any claim this component.
let renderer: SSRLoadedRenderer | undefined;
if (metadata.hydrate !== 'only') {
let error;
for (const r of renderers) {
try {
if (await r.ssr.check.call({ result }, Component, props, children)) {
renderer = r;
break;
if (Component && (Component as any)['astro:renderer']) {
const rendererName = (Component as any)['astro:renderer'];
renderer = renderers.find(({ name }) => name === rendererName);
}

if (!renderer) {
let error;
for (const r of renderers) {
try {
if (await r.ssr.check.call({ result }, Component, props, children)) {
renderer = r;
break;
}
} catch (e) {
error ??= e;
}
} catch (e) {
error ??= e;
}
}

if (error) {
throw error;
if (error) {
throw error;
}
}

if (!renderer && typeof HTMLElement === 'function' && componentIsHTMLElement(Component)) {
Expand All @@ -297,9 +317,9 @@ Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`')
const rendererName = rendererAliases.has(passedName)
? rendererAliases.get(passedName)
: passedName;
renderer = renderers.filter(
renderer = renderers.find(
({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
)[0];
);
}
// Attempt: user only has a single renderer, default to that
if (!renderer && renderers.length === 1) {
Expand Down Expand Up @@ -765,17 +785,21 @@ export async function renderPage(
start(controller) {
async function read() {
let i = 0;
for await (const chunk of iterable) {
let html = chunk.toString();
if (i === 0) {
if (!/<!doctype html/i.test(html)) {
controller.enqueue(encoder.encode('<!DOCTYPE html>\n'));
try {
for await (const chunk of iterable) {
let html = chunk.toString();
if (i === 0) {
if (!/<!doctype html/i.test(html)) {
controller.enqueue(encoder.encode('<!DOCTYPE html>\n'));
}
}
controller.enqueue(encoder.encode(html));
i++;
}
controller.enqueue(encoder.encode(html));
i++;
controller.close();
} catch (e) {
controller.error(e)
}
controller.close();
}
read();
},
Expand Down Expand Up @@ -850,7 +874,7 @@ export async function* renderAstroComponent(
if (value || value === 0) {
for await (const chunk of _render(value)) {
yield markHTMLString(chunk);
}
}
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/src/vite-plugin-jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { AstroConfig, AstroRenderer } from '../@types/astro';
import type { LogOptions } from '../core/logger/core.js';

import babel from '@babel/core';
import tagExportsPlugin from './tag.js';
import * as eslexer from 'es-module-lexer';
import esbuild from 'esbuild';
import * as colors from 'kleur/colors';
Expand Down Expand Up @@ -54,7 +55,7 @@ async function transformJSX({
}: TransformJSXOptions): Promise<TransformResult> {
const { jsxTransformOptions } = renderer;
const options = await jsxTransformOptions!({ mode, ssr });
const plugins = [...(options.plugins || [])];
const plugins = [...(options.plugins || []), tagExportsPlugin({ rendererName: renderer.name })];
const result = await babel.transformAsync(code, {
presets: options.presets,
plugins,
Expand Down
54 changes: 54 additions & 0 deletions packages/astro/src/vite-plugin-jsx/tag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { PluginObj } from '@babel/core';
import * as t from '@babel/types';

export default function astroJSX({ rendererName }: { rendererName: string }): PluginObj {
return {
visitor: {
Program: {
enter(path) {
path.node.body.splice(
0,
0,
t.importDeclaration(
[t.importSpecifier(t.identifier('__astro_tag_component__'), t.identifier('__astro_tag_component__'))],
t.stringLiteral('astro/server/index.js')
)
);
},
exit(path, state) {
const exportedIds = state.get('astro:tags')
if (exportedIds) {
for (const id of exportedIds) {
path.node.body.push(
t.expressionStatement(t.callExpression(t.identifier('__astro_tag_component__'), [t.identifier(id), t.stringLiteral(rendererName)]))
)
}
}
}
},
ExportDeclaration(path, state) {
const node = path.node;
if (node.exportKind === 'type') return;
if (node.type === 'ExportAllDeclaration') return;

if (node.type === 'ExportNamedDeclaration') {
if (t.isFunctionDeclaration(node.declaration)) {
if (node.declaration.id?.name) {
const id = node.declaration.id.name;
const tags = state.get('astro:tags') ?? []
state.set('astro:tags', [...tags, id])
}
}
} else if (node.type === 'ExportDefaultDeclaration') {
if (t.isFunctionDeclaration(node.declaration)) {
if (node.declaration.id?.name) {
const id = node.declaration.id.name;
const tags = state.get('astro:tags') ?? []
state.set('astro:tags', [...tags, id])
}
}
}
},
}
};
}