diff --git a/docs/blog/island-architecture.md b/docs/blog/island-architecture.md index 87ffa45f8..b178a8efc 100644 --- a/docs/blog/island-architecture.md +++ b/docs/blog/island-architecture.md @@ -3,7 +3,8 @@ layout: ~/layouts/Main.astro title: Island Architecture draft: true --- -
{JSON.stringify(data)}
``` + ### `fetch()` -Astro pages have access to the global `fetch()` function in their setup script. `fetch()` is a native JavaScript API ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)) that lets you make HTTP requests for things like APIs and resources. +Astro pages have access to the global `fetch()` function in their setup script. `fetch()` is a native JavaScript API ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)) that lets you make HTTP requests for things like APIs and resources. Even though Astro component scripts run inside of Node.js (and not in the browser) Astro provides this native API so that you can fetch data at page build time. @@ -49,7 +50,7 @@ Even though Astro component scripts run inside of Node.js (and not in the browse ## Page Templating -All Astro components are responsible for returning HTML. Astro Pages return HTML as well, but have the unique responsibility of returning a full `...` page response, including `` ([MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)) and `` ([MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)). +All Astro components are responsible for returning HTML. Astro Pages return HTML as well, but have the unique responsibility of returning a full `...` page response, including `` ([MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)) and `` ([MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)). `` is optional, and will be added automatically. @@ -67,6 +68,3 @@ All Astro components are responsible for returning HTML. Astro Pages return HTML ``` - - - diff --git a/docs/core-concepts/collections.md b/docs/core-concepts/collections.md index 3bdf5c098..edebca3d7 100644 --- a/docs/core-concepts/collections.md +++ b/docs/core-concepts/collections.md @@ -11,7 +11,7 @@ title: Collections - Working with remote data - Mixing remote and local data -**Use a Collection when you need to generate multiple pages from a single template.** If you just want to generate a single page (ex: a long list of every post on your site) then you can just fetch that data on a normal Astro page without using the Collection API. +**Use a Collection when you need to generate multiple pages from a single template.** If you just want to generate a single page (ex: a long list of every post on your site) then you can just fetch that data on a normal Astro page without using the Collection API. ## Using Collections diff --git a/docs/core-concepts/component-hydration.md b/docs/core-concepts/component-hydration.md index b1dc6c8ad..ee1bdd777 100644 --- a/docs/core-concepts/component-hydration.md +++ b/docs/core-concepts/component-hydration.md @@ -22,6 +22,7 @@ However, there are plenty of cases where you might like to include an interactiv - A "Buy Now" button With Astro, you can hydrate these components individually, without forcing the rest of the page to ship any other unnecesary JavaScript. This technique is called **partial hydration.** + ## Hydrate Frontend Components To hydrate your components in the client, you may use any of the following techniques: @@ -34,4 +35,4 @@ To hydrate your components in the client, you may use any of the following techn Astro components (`.astro`) are HTML-only templating languages with no client-side runtime. You cannot hydrate an Astro component to run on the client (because the JavaScript front-matter only ever runs at build time). -If you want to make your Astro component interactive on the client, you should convert it to React, Svelte, or Vue. Otherwise, you can consider adding a ` ${result.imports.join('\n')} -${result.hasCustomElements ? ` +${ + result.hasCustomElements + ? ` const __astro_element_registry = new AstroElementRegistry({ - candidates: new Map([${Array.from(result.customElementCandidates).map(([identifier, url]) => `[${identifier}, '${url}']`).join(', ')}]) + candidates: new Map([${Array.from(result.customElementCandidates) + .map(([identifier, url]) => `[${identifier}, '${url}']`) + .join(', ')}]) }); -`.trim() : ''} +`.trim() + : '' +} // \`__render()\`: Render the contents of the Astro module. import { h, Fragment } from 'astro/dist/internal/h.js'; diff --git a/packages/astro/src/compiler/transform/styles.ts b/packages/astro/src/compiler/transform/styles.ts index cfade44b0..ed163132c 100644 --- a/packages/astro/src/compiler/transform/styles.ts +++ b/packages/astro/src/compiler/transform/styles.ts @@ -199,8 +199,8 @@ export default function transformStyles({ compileOptions, filename, fileID }: Tr if (node.name === 'Markdown') { injectScopedClassAttribute(node, scopedClass, '$scope'); } - for(let attr of node.attributes) { - if(attr.name === 'class') { + for (let attr of node.attributes) { + if (attr.name === 'class') { injectScopedClassAttribute(node, scopedClass, 'class'); break; } diff --git a/packages/astro/src/config_manager.ts b/packages/astro/src/config_manager.ts index b349cb8c7..d70cbcd51 100644 --- a/packages/astro/src/config_manager.ts +++ b/packages/astro/src/config_manager.ts @@ -80,7 +80,7 @@ export class ConfigManager { const r = await import(entrypoint); return { raw: r.default, - options: _options + options: _options, }; }) ) @@ -106,8 +106,8 @@ export class ConfigManager { throw new Error(`Expected the snowpackPlugin from ${name} to be a "string" but encountered "${typeof snowpackPluginName}"!`); } - const polyfillsNormalized = (raw.polyfills || []).map((p: string) => p.startsWith('.') ? path.join(name, p) : p); - const hydrationPolyfillsNormalized = (raw.hydrationPolyfills || []).map((p: string) => p.startsWith('.') ? path.join(name, p) : p); + const polyfillsNormalized = (raw.polyfills || []).map((p: string) => (p.startsWith('.') ? path.join(name, p) : p)); + const hydrationPolyfillsNormalized = (raw.hydrationPolyfills || []).map((p: string) => (p.startsWith('.') ? path.join(name, p) : p)); return { name, @@ -118,7 +118,7 @@ export class ConfigManager { knownEntrypoints: raw.knownEntrypoints, external: raw.external, polyfills: polyfillsNormalized, - hydrationPolyfills: hydrationPolyfillsNormalized + hydrationPolyfills: hydrationPolyfillsNormalized, }; }); @@ -128,21 +128,25 @@ export class ConfigManager { async buildSource(contents: string): Promise { const renderers = await this.buildRendererInstances(); const rendererServerPackages = renderers.map(({ server }) => server); - const rendererClientPackages = await Promise.all(renderers.filter(({client}) => client).map(({ client }) => this.resolvePackageUrl(client!))); - const rendererPolyfills = await Promise.all(renderers.map(({ polyfills }) => Promise.all(polyfills.map(src => this.resolvePackageUrl(src))))); - const rendererHydrationPolyfills = await Promise.all(renderers.map(({ hydrationPolyfills }) => Promise.all(hydrationPolyfills.map(src => this.resolvePackageUrl(src))))); + const rendererClientPackages = await Promise.all(renderers.filter(({ client }) => client).map(({ client }) => this.resolvePackageUrl(client!))); + const rendererPolyfills = await Promise.all(renderers.map(({ polyfills }) => Promise.all(polyfills.map((src) => this.resolvePackageUrl(src))))); + const rendererHydrationPolyfills = await Promise.all(renderers.map(({ hydrationPolyfills }) => Promise.all(hydrationPolyfills.map((src) => this.resolvePackageUrl(src))))); const result = /* js */ `${rendererServerPackages.map((pkg, i) => `import __renderer_${i} from "${pkg}";`).join('\n')} import { setRenderers } from 'astro/dist/internal/__astro_component.js'; -let rendererInstances = [${renderers.map((r, i) => `{ +let rendererInstances = [${renderers + .map( + (r, i) => `{ source: ${rendererClientPackages[i] ? `"${rendererClientPackages[i]}"` : 'null'}, renderer: __renderer_${i}, options: ${r.options ? JSON.stringify(r.options) : 'null'}, polyfills: ${JSON.stringify(rendererPolyfills[i])}, hydrationPolyfills: ${JSON.stringify(rendererHydrationPolyfills[i])} -}`).join(', ')}]; +}` + ) + .join(', ')}]; ${contents} `; diff --git a/packages/astro/src/internal/__astro_component.ts b/packages/astro/src/internal/__astro_component.ts index d57deb462..2581b2471 100644 --- a/packages/astro/src/internal/__astro_component.ts +++ b/packages/astro/src/internal/__astro_component.ts @@ -22,7 +22,7 @@ const astroRendererInstance: RendererInstance = { renderer: astro as Renderer, options: null, polyfills: [], - hydrationPolyfills: [] + hydrationPolyfills: [], }; const astroHtmlRendererInstance: RendererInstance = { @@ -30,7 +30,7 @@ const astroHtmlRendererInstance: RendererInstance = { renderer: astroHtml as Renderer, options: null, polyfills: [], - hydrationPolyfills: [] + hydrationPolyfills: [], }; let rendererInstances: RendererInstance[] = []; @@ -94,14 +94,16 @@ async function generateHydrateScript({ instance, astroId, props }: HydrateScript const { source } = instance; let hydrationSource = ''; - if(instance.hydrationPolyfills.length) { - hydrationSource += `await Promise.all([${instance.hydrationPolyfills.map(src => `import("${src}")`).join(', ')}]);\n`; + if (instance.hydrationPolyfills.length) { + hydrationSource += `await Promise.all([${instance.hydrationPolyfills.map((src) => `import("${src}")`).join(', ')}]);\n`; } - hydrationSource += source ? ` + hydrationSource += source + ? ` const [{ ${componentExport.value}: Component }, { default: hydrate }] = await Promise.all([import("${componentUrl}"), import("${source}")]); return (el, children) => hydrate(el)(Component, ${serialize(props)}, children); -` : ` +` + : ` await import("${componentUrl}"); return () => {}; `; @@ -141,7 +143,7 @@ export const __astro_component = (Component: any, componentProps: AstroComponent let instance = await resolveRenderer(Component, props, children); if (!instance) { - if(isCustomElementTag(Component)) { + if (isCustomElementTag(Component)) { instance = astroHtmlRendererInstance; } else { // If the user only specifies a single renderer, but the check failed @@ -156,8 +158,8 @@ export const __astro_component = (Component: any, componentProps: AstroComponent } let { html } = await instance.renderer.renderToStaticMarkup(Component, props, children, instance.options); - if(instance.polyfills.length) { - let polyfillScripts = instance.polyfills.map(src => ``).join(''); + if (instance.polyfills.length) { + let polyfillScripts = instance.polyfills.map((src) => ``).join(''); html = html + polyfillScripts; } diff --git a/packages/astro/src/internal/element-registry.ts b/packages/astro/src/internal/element-registry.ts index b9ac35f29..2b9ac1cbf 100644 --- a/packages/astro/src/internal/element-registry.ts +++ b/packages/astro/src/internal/element-registry.ts @@ -14,9 +14,9 @@ class AstroElementRegistry { } find(tagName: string) { - for(let [module, importSpecifier] of this.candidates) { - if(module && typeof module.tagName === 'string') { - if(module.tagName === tagName) { + for (let [module, importSpecifier] of this.candidates) { + if (module && typeof module.tagName === 'string') { + if (module.tagName === tagName) { // Found! return importSpecifier; } @@ -25,11 +25,11 @@ class AstroElementRegistry { } findCached(tagName: string) { - if(this.cache.has(tagName)) { + if (this.cache.has(tagName)) { return this.cache.get(tagName)!; } let specifier = this.find(tagName); - if(specifier) { + if (specifier) { this.cache.set(tagName, specifier); } return specifier; @@ -39,10 +39,10 @@ class AstroElementRegistry { const specifier = this.findCached(tagName); const outProps: AstroComponentProps = { ...props, - componentUrl: specifier || props.componentUrl + componentUrl: specifier || props.componentUrl, }; return [tagName, outProps]; } } -export { AstroElementRegistry }; \ No newline at end of file +export { AstroElementRegistry }; diff --git a/packages/astro/src/internal/renderer-html.ts b/packages/astro/src/internal/renderer-html.ts index e80239b1c..66c98197e 100644 --- a/packages/astro/src/internal/renderer-html.ts +++ b/packages/astro/src/internal/renderer-html.ts @@ -3,10 +3,8 @@ import { h } from './h'; async function renderToStaticMarkup(tag: string, props: Record, children: string) { const html = await h(tag, props, Promise.resolve(children)); return { - html + html, }; } -export { - renderToStaticMarkup -}; \ No newline at end of file +export { renderToStaticMarkup }; diff --git a/packages/astro/src/runtime.ts b/packages/astro/src/runtime.ts index a8a322f84..52601216a 100644 --- a/packages/astro/src/runtime.ts +++ b/packages/astro/src/runtime.ts @@ -367,7 +367,7 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO const knownEntrypoints: string[] = ['astro/dist/internal/__astro_component.js', 'astro/dist/internal/element-registry.js']; for (const renderer of rendererInstances) { knownEntrypoints.push(renderer.server); - if(renderer.client) { + if (renderer.client) { knownEntrypoints.push(renderer.client); } if (renderer.knownEntrypoints) { @@ -377,8 +377,8 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO knownEntrypoints.push(...renderer.hydrationPolyfills); } const external = snowpackExternals.concat([]); - for(const renderer of rendererInstances) { - if(renderer.external) { + for (const renderer of rendererInstances) { + if (renderer.external) { external.push(...renderer.external); } } @@ -418,7 +418,7 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO packageOptions: { knownEntrypoints, external, - } + }, }); const polyfillNode = (snowpackConfig.packageOptions as any).polyfillNode as boolean; diff --git a/packages/astro/test/astro-markdown-plugins.test.js b/packages/astro/test/astro-markdown-plugins.test.js index 44744e5d5..a5284cc4b 100644 --- a/packages/astro/test/astro-markdown-plugins.test.js +++ b/packages/astro/test/astro-markdown-plugins.test.js @@ -24,6 +24,6 @@ MarkdownPlugin('Can render Astro with plugins', async ({ runtime }) = const $ = doc(result.contents); assert.equal($('.toc').length, 1, 'Added a TOC'); assert.ok($('#hello-world').hasClass('title'), 'Added .title to h1'); -}) +}); MarkdownPlugin.run(); diff --git a/packages/astro/test/astro-styles-ssr.test.js b/packages/astro/test/astro-styles-ssr.test.js index d8a1bd904..3097d3970 100644 --- a/packages/astro/test/astro-styles-ssr.test.js +++ b/packages/astro/test/astro-styles-ssr.test.js @@ -138,10 +138,12 @@ StylesSSR('Astro scoped styles can be passed to child components', async ({ runt const $ = doc(result.contents); let scopedClass; - $('style').html().replace(/outer\.(astro-[A-Za-z0-9-]+)/, (match, p1) => { - scopedClass = p1; - return match; - }); + $('style') + .html() + .replace(/outer\.(astro-[A-Za-z0-9-]+)/, (match, p1) => { + scopedClass = p1; + return match; + }); assert.match($('#passed-in').attr('class'), `outer ${scopedClass}`); }); diff --git a/packages/astro/test/helpers.js b/packages/astro/test/helpers.js index baf3e4b76..b2eb0d9a6 100644 --- a/packages/astro/test/helpers.js +++ b/packages/astro/test/helpers.js @@ -36,10 +36,14 @@ export function setup(Suite, fixturePath, { runtimeOptions = {} } = {}) { runtime = await createRuntime(astroConfig, { logging: { level: 'error', dest: process.stderr }, ...runtimeOptions, - }).catch(err => { createRuntimeError = err; }); + }).catch((err) => { + createRuntimeError = err; + }); - if(createRuntimeError) { - setTimeout(() => { throw createRuntimeError }); + if (createRuntimeError) { + setTimeout(() => { + throw createRuntimeError; + }); } context.runtime = runtime; diff --git a/packages/astro/test/preact-component.test.js b/packages/astro/test/preact-component.test.js index 31f206d7e..135e1a31e 100644 --- a/packages/astro/test/preact-component.test.js +++ b/packages/astro/test/preact-component.test.js @@ -37,7 +37,7 @@ PreactComponent('Can export a Fragment', async ({ runtime }) => { if (result.error) throw new Error(result.error); const $ = doc(result.contents); - assert.equal($('body').children().length, 0, 'nothing rendered but it didn\'t throw.'); + assert.equal($('body').children().length, 0, "nothing rendered but it didn't throw."); }); PreactComponent.run(); diff --git a/packages/create-astro/src/config.ts b/packages/create-astro/src/config.ts index 6a2b3cb64..40e6653a0 100644 --- a/packages/create-astro/src/config.ts +++ b/packages/create-astro/src/config.ts @@ -1,5 +1,6 @@ export const createConfig = ({ renderers }: { renderers: string[] }) => { - return [`export default { + return [ + `export default { // projectRoot: '.', // Where to resolve all URLs relative to. Useful if you have a monorepo project. // pages: './src/pages', // Path to Astro components, pages, and data // dist: './dist', // When running \`astro build\`, path to final static output @@ -12,8 +13,11 @@ export const createConfig = ({ renderers }: { renderers: string[] }) => { // port: 3000, // The port to run the dev server on. // tailwindConfig: '', // Path to tailwind.config.js if used, e.g. './tailwind.config.js' },`, - ` renderers: ${JSON.stringify(renderers, undefined, 2).split('\n').map((ln, i) => i !== 0 ? ` ${ln}` : ln).join('\n')},`, -`}; -`].join('\n') -} - + ` renderers: ${JSON.stringify(renderers, undefined, 2) + .split('\n') + .map((ln, i) => (i !== 0 ? ` ${ln}` : ln)) + .join('\n')},`, + `}; +`, + ].join('\n'); +}; diff --git a/packages/create-astro/src/frameworks.ts b/packages/create-astro/src/frameworks.ts index f7db2e0f6..440dc067b 100644 --- a/packages/create-astro/src/frameworks.ts +++ b/packages/create-astro/src/frameworks.ts @@ -17,7 +17,7 @@ export default function PreactCounter({ children }) { ); } -` +`, }, '@astrojs/renderer-react': { filename: `src/components/ReactCounter.jsx`, @@ -36,7 +36,7 @@ export default function ReactCounter({ children }) { ); } -` +`, }, '@astrojs/renderer-svelte': { filename: `src/components/SvelteCounter.svelte`, @@ -57,7 +57,7 @@ export default function ReactCounter({ children }) {
{ count }
-` +`, }, '@astrojs/renderer-vue': { filename: `src/components/VueCounter.vue`, @@ -85,8 +85,8 @@ export default { } } -` - } +`, + }, }; export const FRAMEWORKS = [ @@ -105,5 +105,5 @@ export const FRAMEWORKS = [ { title: 'Vue', value: '@astrojs/renderer-vue', - } + }, ]; diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index dcb87086e..73410d6e3 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -66,9 +66,7 @@ export async function main() { const hash = args.commit ? `#${args.commit}` : ''; - const templateTarget = options.template.includes('/') ? - options.template : - `snowpackjs/astro/examples/${options.template}`; + const templateTarget = options.template.includes('/') ? options.template : `snowpackjs/astro/examples/${options.template}`; const emitter = degit(`${templateTarget}${hash}`, { cache: false, @@ -76,9 +74,9 @@ export async function main() { verbose: false, }); - const selectedTemplate = TEMPLATES.find(template => template.value === options.template); + const selectedTemplate = TEMPLATES.find((template) => template.value === options.template); let renderers: string[] = []; - + if (selectedTemplate?.renderers === true) { const result = /** @type {import('./types/internal').Options} */ await prompts([ { @@ -91,7 +89,7 @@ export async function main() { renderers = result.renderers; } else if (selectedTemplate?.renderers && Array.isArray(selectedTemplate.renderers)) { renderers = selectedTemplate.renderers; - const titles = renderers.map(renderer => FRAMEWORKS.find(item => item.value === renderer)?.title).join(', '); + const titles = renderers.map((renderer) => FRAMEWORKS.find((item) => item.value === renderer)?.title).join(', '); console.log(green(`✔`) + bold(` Using template's default renderers`) + gray(' › ') + titles); } @@ -107,47 +105,57 @@ export async function main() { } // Post-process in parallel - await Promise.all(POSTPROCESS_FILES.map(async (file) => { - const fileLoc = path.resolve(path.join(cwd, file)); + await Promise.all( + POSTPROCESS_FILES.map(async (file) => { + const fileLoc = path.resolve(path.join(cwd, file)); - switch (file) { - case 'CHANGELOG.md': { - if (fs.existsSync(fileLoc)) { - await fs.promises.rm(fileLoc); - } - break; - } - case 'astro.config.mjs': { - if (selectedTemplate?.renderers !== true) { + switch (file) { + case 'CHANGELOG.md': { + if (fs.existsSync(fileLoc)) { + await fs.promises.rm(fileLoc); + } + break; + } + case 'astro.config.mjs': { + if (selectedTemplate?.renderers !== true) { + break; + } + await fs.promises.writeFile(fileLoc, createConfig({ renderers })); + break; + } + case 'package.json': { + const packageJSON = JSON.parse(await fs.promises.readFile(fileLoc, 'utf8')); + delete packageJSON.snowpack; // delete snowpack config only needed in monorepo (can mess up projects) + // Fetch latest versions of selected renderers + const rendererEntries = (await Promise.all( + ['astro', ...renderers].map((renderer: string) => + fetch(`https://registry.npmjs.org/${renderer}/latest`) + .then((res: any) => res.json()) + .then((res: any) => [renderer, `^${res['version']}`]) + ) + )) as any; + packageJSON.devDependencies = { ...(packageJSON.devDependencies ?? {}), ...Object.fromEntries(rendererEntries) }; + await fs.promises.writeFile(fileLoc, JSON.stringify(packageJSON, undefined, 2)); break; } - await fs.promises.writeFile(fileLoc, createConfig({ renderers })); - break; } - case 'package.json': { - const packageJSON = JSON.parse(await fs.promises.readFile(fileLoc, 'utf8')); - delete packageJSON.snowpack; // delete snowpack config only needed in monorepo (can mess up projects) - // Fetch latest versions of selected renderers - const rendererEntries = await Promise.all(['astro', ...renderers].map((renderer: string) => fetch(`https://registry.npmjs.org/${renderer}/latest`).then((res: any) => res.json()).then((res: any) => [renderer, `^${res['version']}`]))) as any; - packageJSON.devDependencies = { ...packageJSON.devDependencies ?? {}, ...Object.fromEntries(rendererEntries) } - await fs.promises.writeFile(fileLoc, JSON.stringify(packageJSON, undefined, 2)); - break; - } - } - })); + }) + ); // Inject framework components into starter template if (selectedTemplate?.value === 'starter') { let importStatements: string[] = []; let components: string[] = []; - await Promise.all(renderers.map(async renderer => { - const component = COUNTER_COMPONENTS[renderer as keyof typeof COUNTER_COMPONENTS]; - const componentName = path.basename(component.filename, path.extname(component.filename)); - const absFileLoc = path.resolve(cwd, component.filename); - importStatements.push(`import ${componentName} from '${component.filename.replace(/^src/, '..')}';`); - components.push(`<${componentName}:visible />`); - await fs.promises.writeFile(absFileLoc, component.content); - })); + await Promise.all( + renderers.map(async (renderer) => { + const component = COUNTER_COMPONENTS[renderer as keyof typeof COUNTER_COMPONENTS]; + const componentName = path.basename(component.filename, path.extname(component.filename)); + const absFileLoc = path.resolve(cwd, component.filename); + importStatements.push(`import ${componentName} from '${component.filename.replace(/^src/, '..')}';`); + components.push(`<${componentName}:visible />`); + await fs.promises.writeFile(absFileLoc, component.content); + }) + ); const pageFileLoc = path.resolve(path.join(cwd, 'src', 'pages', 'index.astro')); const content = (await fs.promises.readFile(pageFileLoc)).toString(); @@ -162,9 +170,19 @@ export async function main() { - See https://github.com/snowpackjs/astro/blob/main/docs/core-concepts/component-hydration.md --> `; - lines.splice(41, 0, importStatements.length > 0 ? doc.split('\n').map(ln => `${indent}${ln}`).join('\n') : '', ...components.map(ln => `${indent}${ln}`)); + lines.splice( + 41, + 0, + importStatements.length > 0 + ? doc + .split('\n') + .map((ln) => `${indent}${ln}`) + .join('\n') + : '', + ...components.map((ln) => `${indent}${ln}`) + ); lines.splice(3, 0, importStatements.length > 0 ? `// Framework Component Imports` : '', ...importStatements); - await fs.promises.writeFile(pageFileLoc, lines.join('\n')) + await fs.promises.writeFile(pageFileLoc, lines.join('\n')); } console.log(bold(green('✔') + ' Done!')); diff --git a/packages/create-astro/src/templates.ts b/packages/create-astro/src/templates.ts index 6852aafb0..e4d9cefc4 100644 --- a/packages/create-astro/src/templates.ts +++ b/packages/create-astro/src/templates.ts @@ -7,16 +7,16 @@ export const TEMPLATES = [ { title: 'Blog', value: 'blog', - renderers: ['@astrojs/renderer-preact'] + renderers: ['@astrojs/renderer-preact'], }, { title: 'Documentation', value: 'docs', - renderers: ['@astrojs/renderer-preact'] + renderers: ['@astrojs/renderer-preact'], }, { title: 'Portfolio', value: 'portfolio', - renderers: ['@astrojs/renderer-preact'] + renderers: ['@astrojs/renderer-preact'], }, ]; diff --git a/packages/create-astro/test/external.test.js b/packages/create-astro/test/external.test.js index 9fac8c202..be4404e53 100644 --- a/packages/create-astro/test/external.test.js +++ b/packages/create-astro/test/external.test.js @@ -10,12 +10,10 @@ async function run(outdir, template) { }); } -const testCases = [ - ['shopify', 'cassidoo/shopify-react-astro'] -]; +const testCases = [['shopify', 'cassidoo/shopify-react-astro']]; async function tests() { - for(let [dir, tmpl] of testCases) { + for (let [dir, tmpl] of testCases) { await run(dir, tmpl); const outPath = new URL('' + dir, FIXTURES_URL); @@ -23,7 +21,7 @@ async function tests() { } } -tests().catch(err => { +tests().catch((err) => { console.error(err); process.exit(1); -}); \ No newline at end of file +}); diff --git a/packages/create-astro/test/helpers.js b/packages/create-astro/test/helpers.js index 295f9c650..ca1f82362 100644 --- a/packages/create-astro/test/helpers.js +++ b/packages/create-astro/test/helpers.js @@ -6,8 +6,4 @@ const GITHUB_SHA = process.env.GITHUB_SHA || execa.sync('git', ['rev-parse', 'HE const FIXTURES_DIR = path.join(fileURLToPath(path.dirname(import.meta.url)), 'fixtures'); const FIXTURES_URL = pathToFileURL(FIXTURES_DIR + '/'); -export { - GITHUB_SHA, - FIXTURES_DIR, - FIXTURES_URL -}; \ No newline at end of file +export { GITHUB_SHA, FIXTURES_DIR, FIXTURES_URL }; diff --git a/packages/markdown-support/src/index.ts b/packages/markdown-support/src/index.ts index f3ceda1a1..168738ea2 100644 --- a/packages/markdown-support/src/index.ts +++ b/packages/markdown-support/src/index.ts @@ -28,7 +28,9 @@ export async function renderMarkdownWithFrontmatter(contents: string, opts?: Mar export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) { const { $: { scopedClassName = null } = {}, footnotes: useFootnotes = true, gfm: useGfm = true, remarkPlugins = [], rehypePlugins = [] } = opts ?? {}; const { headers, rehypeCollectHeaders } = createCollectHeaders(); - let parser = unified().use(markdown).use([remarkExpressions, { addResult: true }]); + let parser = unified() + .use(markdown) + .use([remarkExpressions, { addResult: true }]); if (remarkPlugins.length === 0) { if (useGfm) { @@ -61,7 +63,12 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp let result: string; try { - const vfile = await parser.use(raw).use(rehypeCollectHeaders).use(rehypeCodeBlock()).use(rehypeStringify, { entities: { useNamedReferences: true }}).process(content); + const vfile = await parser + .use(raw) + .use(rehypeCollectHeaders) + .use(rehypeCodeBlock()) + .use(rehypeStringify, { entities: { useNamedReferences: true } }) + .process(content); result = vfile.contents.toString(); } catch (err) { throw err; diff --git a/packages/markdown-support/src/load-plugins.ts b/packages/markdown-support/src/load-plugins.ts index 52bc287f8..df19a082e 100644 --- a/packages/markdown-support/src/load-plugins.ts +++ b/packages/markdown-support/src/load-plugins.ts @@ -1,5 +1,5 @@ -import unified from "unified"; -import type { Plugin, UnifiedPluginImport } from "./types"; +import unified from 'unified'; +import type { Plugin, UnifiedPluginImport } from './types'; async function importPlugin(p: string | UnifiedPluginImport): UnifiedPluginImport { if (typeof p === 'string') { @@ -20,7 +20,7 @@ export function loadPlugins(items: Plugin[]): Promise<[unified.Plugin] | [unifie } return importPlugin(p) - .then((m) => resolve([m.default])) + .then((m) => resolve([m.default])) .catch((e) => reject(e)); }); }); diff --git a/packages/markdown-support/src/rehype-expressions.ts b/packages/markdown-support/src/rehype-expressions.ts index 2762f54fc..016d36aaf 100644 --- a/packages/markdown-support/src/rehype-expressions.ts +++ b/packages/markdown-support/src/rehype-expressions.ts @@ -1,12 +1,12 @@ -import { map } from 'unist-util-map' +import { map } from 'unist-util-map'; export default function rehypeExpressions(): any { - return function(node: any): any { + return function (node: any): any { return map(node, (child) => { if (child.type === 'mdxTextExpression') { - return { type: 'text', value: `{${child.value}}` } + return { type: 'text', value: `{${child.value}}` }; } return child; - }) - } + }); + }; } diff --git a/packages/markdown-support/src/remark-expressions.ts b/packages/markdown-support/src/remark-expressions.ts index 1cdb37894..a38c5f3bf 100644 --- a/packages/markdown-support/src/remark-expressions.ts +++ b/packages/markdown-support/src/remark-expressions.ts @@ -1,18 +1,18 @@ -import {mdxExpression} from 'micromark-extension-mdx-expression' -import {mdxExpressionFromMarkdown, mdxExpressionToMarkdown} from 'mdast-util-mdx-expression' +import { mdxExpression } from 'micromark-extension-mdx-expression'; +import { mdxExpressionFromMarkdown, mdxExpressionToMarkdown } from 'mdast-util-mdx-expression'; function remarkExpressions(this: any, options: any) { - let settings = options || {} - let data = this.data() + let settings = options || {}; + let data = this.data(); - add('micromarkExtensions', mdxExpression({})) - add('fromMarkdownExtensions', mdxExpressionFromMarkdown) - add('toMarkdownExtensions', mdxExpressionToMarkdown) + add('micromarkExtensions', mdxExpression({})); + add('fromMarkdownExtensions', mdxExpressionFromMarkdown); + add('toMarkdownExtensions', mdxExpressionToMarkdown); function add(field: any, value: any) { /* istanbul ignore if - other extensions. */ - if (data[field]) data[field].push(value) - else data[field] = [value] + if (data[field]) data[field].push(value); + else data[field] = [value]; } }