[ci] yarn format

This commit is contained in:
natemoo-re 2021-10-29 19:47:01 +00:00 committed by GitHub Actions
parent 34e03cf912
commit a5c6f922fa
26 changed files with 101 additions and 104 deletions

View file

@ -13,4 +13,4 @@ description: Just a Hello World Post!
This is so cool! This is so cool!
Do variables work {frontmatter.value * 2}? Do variables work {frontmatter.value \* 2}?

View file

@ -1,6 +1,6 @@
import { KNOWN_LANGUAGES } from './config'; import { KNOWN_LANGUAGES } from './config';
export { KNOWN_LANGUAGES } export { KNOWN_LANGUAGES };
export const KNOWN_LANGUAGE_CODES = Object.values(KNOWN_LANGUAGES); export const KNOWN_LANGUAGE_CODES = Object.values(KNOWN_LANGUAGES);
export const langPathRegex = /\/([a-z]{2}-?[A-Z]{0,2})\//; export const langPathRegex = /\/([a-z]{2}-?[A-Z]{0,2})\//;

View file

@ -11,13 +11,16 @@ import astroRemark from '@astrojs/markdown-remark';
export default /** @type {import('astro').AstroUserConfig} */ ({ export default /** @type {import('astro').AstroUserConfig} */ ({
// Enable Custom Markdown options, plugins, etc. // Enable Custom Markdown options, plugins, etc.
markdownOptions: { markdownOptions: {
render: [astroRemark, { render: [
remarkPlugins: ['remark-code-titles', 'remark-slug'], astroRemark,
rehypePlugins: [ {
['rehype-autolink-headings', { behavior: 'prepend' }], remarkPlugins: ['remark-code-titles', 'remark-slug'],
['rehype-toc', { headings: ['h2', 'h3'] }], rehypePlugins: [
['rehype-add-classes', { 'h1,h2,h3': 'title' }], ['rehype-autolink-headings', { behavior: 'prepend' }],
] ['rehype-toc', { headings: ['h2', 'h3'] }],
}] ['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
},
],
}, },
}); });

View file

@ -1 +1 @@
export function addAstro(Prism: any): void; export function addAstro(Prism: any): void;

View file

@ -66,7 +66,7 @@ export function codeFrame(src: string, loc: ErrorPayload['err']['loc']): string
export function resolveDependency(dep: string, astroConfig: AstroConfig) { export function resolveDependency(dep: string, astroConfig: AstroConfig) {
const resolved = resolve.sync(dep, { const resolved = resolve.sync(dep, {
basedir: fileURLToPath(astroConfig.projectRoot) basedir: fileURLToPath(astroConfig.projectRoot),
}); });
// For Windows compat, we need a fully resolved `file://` URL string // For Windows compat, we need a fully resolved `file://` URL string
return pathToFileURL(resolved).toString(); return pathToFileURL(resolved).toString();

View file

@ -1,2 +1,2 @@
export * from '../../vendor/vite/dist/node/index.js'; export * from '../../vendor/vite/dist/node/index.js';
export { default } from '../../vendor/vite/dist/node/index.js'; export { default } from '../../vendor/vite/dist/node/index.js';

View file

@ -365,13 +365,17 @@ export async function renderToString(result: SSRResult, componentFactory: AstroC
const uniqueElements = (item: any, index: number, all: any[]) => { const uniqueElements = (item: any, index: number, all: any[]) => {
const props = JSON.stringify(item.props); const props = JSON.stringify(item.props);
const children = item.children; const children = item.children;
return index === all.findIndex(i => JSON.stringify(i.props) === props && i.children == children) return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
} };
export async function renderPage(result: SSRResult, Component: AstroComponentFactory, props: any, children: any) { export async function renderPage(result: SSRResult, Component: AstroComponentFactory, props: any, children: any) {
const template = await renderToString(result, Component, props, children); const template = await renderToString(result, Component, props, children);
const styles = Array.from(result.styles).filter(uniqueElements).map((style) => renderElement('style', style)); const styles = Array.from(result.styles)
const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => renderElement('script', script)); .filter(uniqueElements)
.map((style) => renderElement('style', style));
const scripts = Array.from(result.scripts)
.filter(uniqueElements)
.map((script) => renderElement('script', script));
return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>'); return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>');
} }

View file

@ -60,7 +60,7 @@ class Metadata {
} }
interface CreateMetadataOptions { interface CreateMetadataOptions {
modules: ModuleInfo[]; modules: ModuleInfo[];
hydratedComponents: any[]; hydratedComponents: any[];
hoisted: any[]; hoisted: any[];
} }

View file

@ -11,7 +11,7 @@ interface AstroPluginOptions {
devServer?: AstroDevServer; devServer?: AstroDevServer;
} }
// esbuild transforms the component-scoped Astro into Astro2, so need to check both. // esbuild transforms the component-scoped Astro into Astro2, so need to check both.
const validAstroGlobalNames = new Set(['Astro', 'Astro2']); const validAstroGlobalNames = new Set(['Astro', 'Astro2']);
export default function astro({ config, devServer }: AstroPluginOptions): Plugin { export default function astro({ config, devServer }: AstroPluginOptions): Plugin {

View file

@ -94,4 +94,4 @@ describe('Astro basics', () => {
expect(result.status).to.equal(404); expect(result.status).to.equal(404);
}); });
}); });
}); });

View file

@ -13,8 +13,8 @@ describe('Dynamic components', () => {
it('Loads packages that only run code in client', async () => { it('Loads packages that only run code in client', async () => {
const html = await fixture.readFile('/index.html'); const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html) const $ = cheerio.load(html);
expect($('script').length).to.eq(2) expect($('script').length).to.eq(2);
}); });
it('Loads pages using client:media hydrator', async () => { it('Loads pages using client:media hydrator', async () => {

View file

@ -3,7 +3,6 @@ import cheerio from 'cheerio';
import { loadFixture } from './test-utils.js'; import { loadFixture } from './test-utils.js';
import markdownRemark from '@astrojs/markdown-remark'; import markdownRemark from '@astrojs/markdown-remark';
describe('Astro Markdown plugins', () => { describe('Astro Markdown plugins', () => {
let fixture; let fixture;
@ -12,13 +11,16 @@ describe('Astro Markdown plugins', () => {
projectRoot: './fixtures/astro-markdown-plugins/', projectRoot: './fixtures/astro-markdown-plugins/',
renderers: ['@astrojs/renderer-preact'], renderers: ['@astrojs/renderer-preact'],
markdownOptions: { markdownOptions: {
render: [markdownRemark, { render: [
remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]], markdownRemark,
rehypePlugins: [ {
['rehype-toc', { headings: ['h2', 'h3'] }], remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]],
['rehype-add-classes', { 'h1,h2,h3': 'title' }], rehypePlugins: [
], ['rehype-toc', { headings: ['h2', 'h3'] }],
}], ['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
},
],
}, },
buildOptions: { buildOptions: {
sitemap: false, sitemap: false,
@ -48,4 +50,4 @@ describe('Astro Markdown plugins', () => {
// teste 2: Added .title to h1 // teste 2: Added .title to h1
expect($('#hello-world').hasClass('title')).to.equal(true); expect($('#hello-world').hasClass('title')).to.equal(true);
}); });
}); });

View file

@ -59,7 +59,7 @@ describe('Astro Markdown', () => {
// test 1: <pre> tag has scopedStyle class passed down // test 1: <pre> tag has scopedStyle class passed down
expect($('pre').is('[class]')).to.equal(true); expect($('pre').is('[class]')).to.equal(true);
expect($('pre').attr('class').split(' ').length).to.equal(2) expect($('pre').attr('class').split(' ').length).to.equal(2);
// test 2: <pre> tag has correct language // test 2: <pre> tag has correct language
expect($('pre').hasClass('language-js')).to.equal(true); expect($('pre').hasClass('language-js')).to.equal(true);
@ -117,7 +117,7 @@ describe('Astro Markdown', () => {
expect($('code:nth-child(2)').text()).to.equal('{...props}'); expect($('code:nth-child(2)').text()).to.equal('{...props}');
// test 4: Rendered curly braces markdown content // test 4: Rendered curly braces markdown content
expect($('code:last-child').text()).to.equal('{/* JavaScript *\/}'); expect($('code:last-child').text()).to.equal('{/* JavaScript */}');
}); });
it('Does not close parent early when using content attribute (#494)', async () => { it('Does not close parent early when using content attribute (#494)', async () => {
@ -140,4 +140,4 @@ describe('Astro Markdown', () => {
// test Markdown rendered correctly via content prop // test Markdown rendered correctly via content prop
expect($('h1').text()).to.equal('Foo'); expect($('h1').text()).to.equal('Foo');
}); });
}); });

View file

@ -24,7 +24,7 @@ describe('Sitemaps', () => {
); );
}); });
}); });
describe('Sitemap Generation', () => { describe('Sitemap Generation', () => {
it('Generates Sitemap correctly', async () => { it('Generates Sitemap correctly', async () => {
let sitemap = await fixture.readFile('/sitemap.xml'); let sitemap = await fixture.readFile('/sitemap.xml');
@ -33,4 +33,4 @@ describe('Sitemaps', () => {
); );
}); });
}); });
}); });

View file

@ -112,4 +112,4 @@ describe('Slots', () => {
expect($('#default')).to.have.lengthOf(1); // the default slot is filled expect($('#default')).to.have.lengthOf(1); // the default slot is filled
} }
}); });
}); });

View file

@ -4,7 +4,7 @@ import { devCLI, loadFixture } from './test-utils.js';
describe('config', () => { describe('config', () => {
let hostnameFixture; let hostnameFixture;
let portFixture; let portFixture;
before(async () => { before(async () => {
[hostnameFixture, portFixture] = await Promise.all([loadFixture({ projectRoot: './fixtures/config-hostname/' }), loadFixture({ projectRoot: './fixtures/config-port/' })]); [hostnameFixture, portFixture] = await Promise.all([loadFixture({ projectRoot: './fixtures/config-hostname/' }), loadFixture({ projectRoot: './fixtures/config-port/' })]);
}); });

View file

@ -32,17 +32,17 @@ export const DEFAULT_REMARK_PLUGINS = [
'remark-footnotes', 'remark-footnotes',
// TODO: reenable smartypants! // TODO: reenable smartypants!
// '@silvenon/remark-smartypants' // '@silvenon/remark-smartypants'
] ];
export const DEFAULT_REHYPE_PLUGINS = [ export const DEFAULT_REHYPE_PLUGINS = [
// empty // empty
] ];
/** Shared utility for rendering markdown */ /** Shared utility for rendering markdown */
export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) { export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) {
const { remarkPlugins = DEFAULT_REMARK_PLUGINS, rehypePlugins = DEFAULT_REHYPE_PLUGINS } = opts ?? {}; const { remarkPlugins = DEFAULT_REMARK_PLUGINS, rehypePlugins = DEFAULT_REHYPE_PLUGINS } = opts ?? {};
const scopedClassName = opts?.$?.scopedClassName; const scopedClassName = opts?.$?.scopedClassName;
const mode = opts?.mode ?? "mdx"; const mode = opts?.mode ?? 'mdx';
const isMDX = mode === 'mdx'; const isMDX = mode === 'mdx';
const { headers, rehypeCollectHeaders } = createCollectHeaders(); const { headers, rehypeCollectHeaders } = createCollectHeaders();
@ -52,7 +52,7 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
.use(markdown) .use(markdown)
.use(isMDX ? [remarkJsx] : []) .use(isMDX ? [remarkJsx] : [])
.use(isMDX ? [remarkExpressions] : []) .use(isMDX ? [remarkExpressions] : [])
.use([remarkUnwrap]) .use([remarkUnwrap]);
const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins)); const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins)); const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
@ -62,28 +62,25 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
}); });
if (scopedClassName) { if (scopedClassName) {
parser.use([scopedStyles(scopedClassName)]); parser.use([scopedStyles(scopedClassName)]);
} }
parser.use([remarkPrism(scopedClassName)]); parser.use([remarkPrism(scopedClassName)]);
parser.use([[markdownToHtml as any, { allowDangerousHtml: true, passThrough: ['raw', 'mdxTextExpression', 'mdxJsxTextElement', 'mdxJsxFlowElement']}]]); parser.use([[markdownToHtml as any, { allowDangerousHtml: true, passThrough: ['raw', 'mdxTextExpression', 'mdxJsxTextElement', 'mdxJsxFlowElement'] }]]);
loadedRehypePlugins.forEach(([plugin, opts]) => { loadedRehypePlugins.forEach(([plugin, opts]) => {
parser.use([[plugin, opts]]); parser.use([[plugin, opts]]);
}); });
parser parser
.use(isMDX ? [rehypeJsx] : []) .use(isMDX ? [rehypeJsx] : [])
.use(isMDX ? [rehypeExpressions] : []) .use(isMDX ? [rehypeExpressions] : [])
.use(isMDX ? [] : [rehypeRaw]) .use(isMDX ? [] : [rehypeRaw])
.use(rehypeIslands) .use(rehypeIslands);
let result: string; let result: string;
try { try {
const vfile = await parser const vfile = await parser.use([rehypeCollectHeaders]).use(rehypeStringify, { allowDangerousHtml: true }).process(content);
.use([rehypeCollectHeaders])
.use(rehypeStringify, { allowDangerousHtml: true })
.process(content);
result = vfile.toString(); result = vfile.toString();
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View file

@ -1,4 +1,4 @@
import {SKIP, visit} from 'unist-util-visit'; import { SKIP, visit } from 'unist-util-visit';
// This fixes some confusing bugs coming from somewhere inside of our Markdown pipeline. // This fixes some confusing bugs coming from somewhere inside of our Markdown pipeline.
// `unist`/`remark`/`rehype` (not sure) often generate malformed HTML inside of <astro-root> // `unist`/`remark`/`rehype` (not sure) often generate malformed HTML inside of <astro-root>
@ -11,11 +11,11 @@ export default function rehypeIslands(): any {
if (el.tagName == 'astro-root') { if (el.tagName == 'astro-root') {
visit(el, 'text', (child, index, parent) => { visit(el, 'text', (child, index, parent) => {
if (child.type === 'text') { if (child.type === 'text') {
// Sometimes comments can be trapped as text, which causes them to be escaped // Sometimes comments can be trapped as text, which causes them to be escaped
// This casts them back to real HTML comments // This casts them back to real HTML comments
if (parent && child.value.indexOf('<!--') > -1 && index != null) { if (parent && child.value.indexOf('<!--') > -1 && index != null) {
parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim()}); parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim() });
return [SKIP, index] return [SKIP, index];
} }
// For some reason `rehype` likes to inject extra linebreaks, // For some reason `rehype` likes to inject extra linebreaks,
// but React and Vue throw hydration errors when they see these! // but React and Vue throw hydration errors when they see these!
@ -24,7 +24,7 @@ export default function rehypeIslands(): any {
child.value = child.value.replace(/\n+/g, ''); child.value = child.value.replace(/\n+/g, '');
return child; return child;
} }
}) });
} }
}); });
}; };

View file

@ -5,22 +5,22 @@ export default function rehypeJsx(): any {
return function (node: any): any { return function (node: any): any {
return map(node, (child: any) => { return map(node, (child: any) => {
if (child.type === 'element') { if (child.type === 'element') {
return { ...child, tagName: `${child.tagName}` } return { ...child, tagName: `${child.tagName}` };
} }
if (MDX_ELEMENTS.has(child.type)) { if (MDX_ELEMENTS.has(child.type)) {
return { return {
...child, ...child,
type: 'element', type: 'element',
tagName: `${child.name}`, tagName: `${child.name}`,
properties: child.attributes.reduce((acc: any[], entry: any) => { properties: child.attributes.reduce((acc: any[], entry: any) => {
let attr = entry.value; let attr = entry.value;
if (attr && typeof attr === 'object') { if (attr && typeof attr === 'object') {
attr = `{${attr.value}}` attr = `{${attr.value}}`;
} else if (attr === null) { } else if (attr === null) {
attr = `{true}` attr = `{true}`;
} }
return Object.assign(acc, { [entry.name]: attr }); return Object.assign(acc, { [entry.name]: attr });
}, {}) }, {}),
}; };
} }
return child; return child;

View file

@ -4,26 +4,24 @@ import { addAstro } from '@astrojs/prism';
import loadLanguages from 'prismjs/components/index.js'; import loadLanguages from 'prismjs/components/index.js';
const noVisit = new Set(['root', 'html', 'text']); const noVisit = new Set(['root', 'html', 'text']);
const languageMap = new Map([ const languageMap = new Map([['ts', 'typescript']]);
['ts', 'typescript']
]);
function runHighlighter(lang: string, code: string) { function runHighlighter(lang: string, code: string) {
let classLanguage = `language-${lang}` let classLanguage = `language-${lang}`;
if (lang == null) { if (lang == null) {
lang = 'plaintext'; lang = 'plaintext';
} }
const ensureLoaded = (lang: string) => { const ensureLoaded = (lang: string) => {
if(lang && !Prism.languages[lang]) { if (lang && !Prism.languages[lang]) {
loadLanguages([lang]); loadLanguages([lang]);
} }
}; };
if(languageMap.has(lang)) { if (languageMap.has(lang)) {
ensureLoaded(languageMap.get(lang)!); ensureLoaded(languageMap.get(lang)!);
} else if(lang === 'astro') { } else if (lang === 'astro') {
ensureLoaded('typescript'); ensureLoaded('typescript');
addAstro(Prism); addAstro(Prism);
} else { } else {
@ -31,7 +29,7 @@ function runHighlighter(lang: string, code: string) {
ensureLoaded(lang); ensureLoaded(lang);
} }
if(lang && !Prism.languages[lang]) { if (lang && !Prism.languages[lang]) {
console.warn(`Unable to load the language: ${lang}`); console.warn(`Unable to load the language: ${lang}`);
} }
@ -48,26 +46,25 @@ type MaybeString = string | null | undefined;
/** */ /** */
function transformer(className: MaybeString) { function transformer(className: MaybeString) {
return function(tree: any) { return function (tree: any) {
const visitor = (node: any) => { const visitor = (node: any) => {
let {lang, value} = node; let { lang, value } = node;
node.type = 'html'; node.type = 'html';
let { html, classLanguage } = runHighlighter(lang, value); let { html, classLanguage } = runHighlighter(lang, value);
let classes = [classLanguage]; let classes = [classLanguage];
if(className) { if (className) {
classes.push(className); classes.push(className);
} }
node.value = `<pre class="${classes.join(' ')}"><code data-astro-raw class="${classLanguage}">${html}</code></pre>`; node.value = `<pre class="${classes.join(' ')}"><code data-astro-raw class="${classLanguage}">${html}</code></pre>`;
return node; return node;
}; };
return visit(tree, 'code', visitor) return visit(tree, 'code', visitor);
} };
} }
function plugin(className: MaybeString) { function plugin(className: MaybeString) {
return transformer.bind(null, className); return transformer.bind(null, className);
} }
export default plugin; export default plugin;

View file

@ -3,11 +3,11 @@
* @typedef {import('hast').Properties} Properties * @typedef {import('hast').Properties} Properties
*/ */
import {toString} from 'mdast-util-to-string' import { toString } from 'mdast-util-to-string';
import {visit} from 'unist-util-visit' import { visit } from 'unist-util-visit';
import BananaSlug from 'github-slugger' import BananaSlug from 'github-slugger';
const slugs = new BananaSlug() const slugs = new BananaSlug();
/** /**
* Plugin to add anchors headings using GitHubs algorithm. * Plugin to add anchors headings using GitHubs algorithm.
@ -16,19 +16,17 @@ const slugs = new BananaSlug()
*/ */
export default function remarkSlug() { export default function remarkSlug() {
return (tree: any) => { return (tree: any) => {
slugs.reset() slugs.reset();
visit(tree, (node) => { visit(tree, (node) => {
console.log(node); console.log(node);
}); });
visit(tree, 'heading', (node) => { visit(tree, 'heading', (node) => {
const data = node.data || (node.data = {}) const data = node.data || (node.data = {});
const props = /** @type {Properties} */ ( const props = /** @type {Properties} */ data.hProperties || (data.hProperties = {});
data.hProperties || (data.hProperties = {}) let id = props.id;
) id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node));
let id = props.id
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node))
data.id = id; data.id = id;
props.id = id; props.id = id;
}) });
} };
} }

View file

@ -1,4 +1,4 @@
import {visit, SKIP} from 'unist-util-visit' import { visit, SKIP } from 'unist-util-visit';
// Remove the wrapping paragraph for <astro-root> islands // Remove the wrapping paragraph for <astro-root> islands
export default function remarkUnwrap() { export default function remarkUnwrap() {
@ -18,21 +18,17 @@ export default function remarkUnwrap() {
insideAstroRoot = false; insideAstroRoot = false;
} }
astroRootNodes.add(node); astroRootNodes.add(node);
}) });
visit(tree, 'paragraph', (node, index, parent) => { visit(tree, 'paragraph', (node, index, parent) => {
if ( if (parent && typeof index === 'number' && containsAstroRootNode(node)) {
parent && parent.children.splice(index, 1, ...node.children);
typeof index === 'number' && return [SKIP, index];
containsAstroRootNode(node)
) {
parent.children.splice(index, 1, ...node.children)
return [SKIP, index]
} }
}) });
} };
function containsAstroRootNode(node: any) { function containsAstroRootNode(node: any) {
return node.children.map((child: any) => astroRootNodes.has(child)).reduce((all: boolean, v: boolean) => all ? all : v, false) return node.children.map((child: any) => astroRootNodes.has(child)).reduce((all: boolean, v: boolean) => (all ? all : v), false);
} }
} }

View file

@ -4,7 +4,7 @@ export type UnifiedPluginImport = Promise<{ default: unified.Plugin }>;
export type Plugin = string | [string, any] | UnifiedPluginImport | [UnifiedPluginImport, any]; export type Plugin = string | [string, any] | UnifiedPluginImport | [UnifiedPluginImport, any];
export interface AstroMarkdownOptions { export interface AstroMarkdownOptions {
mode?: 'md'|'mdx'; mode?: 'md' | 'mdx';
remarkPlugins?: Plugin[]; remarkPlugins?: Plugin[];
rehypePlugins?: Plugin[]; rehypePlugins?: Plugin[];
} }

View file

@ -1 +1 @@
import 'lit/experimental-hydrate-support.js'; import 'lit/experimental-hydrate-support.js';

View file

@ -20,7 +20,7 @@ export default {
'@webcomponents/template-shadowroot/template-shadowroot.js', '@webcomponents/template-shadowroot/template-shadowroot.js',
'lit/experimental-hydrate-support.js', 'lit/experimental-hydrate-support.js',
], ],
exclude: ['@astrojs/renderer-lit/server.js'] exclude: ['@astrojs/renderer-lit/server.js'],
}, },
ssr: { ssr: {
external: [ external: [

View file

@ -15,7 +15,7 @@ export default {
return { return {
alias: { alias: {
react: 'preact/compat', react: 'preact/compat',
'react-dom': 'preact/compat' 'react-dom': 'preact/compat',
}, },
resolve: { resolve: {
dedupe: ['react', 'react-dom'], dedupe: ['react', 'react-dom'],