Merge branch 'main' into redirects-ssg

This commit is contained in:
Matthew Phillips 2023-05-30 17:52:21 -04:00 committed by GitHub
commit fd52bd6bb1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
61 changed files with 549 additions and 460 deletions

View file

@ -1,5 +0,0 @@
---
'@astrojs/sitemap': patch
---
exported enum type to support typescript > 5.0

View file

@ -1,5 +0,0 @@
---
'@astrojs/partytown': patch
---
fix typescript type for partytown options

View file

@ -1,5 +0,0 @@
---
'@astrojs/mdx': patch
---
Add `optimize` option for faster builds and rendering

View file

@ -1,6 +0,0 @@
---
'astro': patch
---
Refactor how pages are emitted during the internal bundling. Now each
page is emitted as a separate entry point.

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
Fix CSS deduping and missing chunks

View file

@ -1,19 +0,0 @@
---
'@astrojs/markdoc': patch
---
Add support for syntax highlighting with Shiki. Apply to your Markdoc config using the `extends` property:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import shiki from '@astrojs/markdoc/shiki';
export default defineMarkdocConfig({
extends: [
shiki({ /** Shiki config options */ }),
],
})
```
Learn more in the [`@astrojs/markdoc` README.](https://docs.astro.build/en/guides/integrations-guide/markdoc/#syntax-highlighting)

View file

@ -1,7 +0,0 @@
---
'@astrojs/preact': patch
'@astrojs/react': patch
'@astrojs/vue': patch
---
Fix `astro-static-slot` hydration mismatch error

View file

@ -1,5 +0,0 @@
---
'@astrojs/webapi': minor
---
Add polyfill for `crypto`

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
Prioritize dynamic prerendered routes over dynamic server routes

View file

@ -1,6 +0,0 @@
---
'@astrojs/mdx': patch
'astro': patch
---
Detect `mdx` files using their full extension

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
Add error message if `Astro.glob` is called outside of an Astro file

View file

@ -1,5 +0,0 @@
---
'@astrojs/vercel': patch
---
Fix `imagesConfig` being wrongly spelt as `imageConfig` in the README

View file

@ -1,17 +0,0 @@
---
'@astrojs/markdoc': patch
---
Add a built-in extension for syntax highlighting with Prism. Apply to your Markdoc config using the `extends` property:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import prism from '@astrojs/markdoc/prism';
export default defineMarkdocConfig({
extends: [prism()],
})
```
Learn more in the [`@astrojs/markdoc` README.](https://docs.astro.build/en/guides/integrations-guide/markdoc/#syntax-highlighting)

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
fix miss a head when the templaterender has a promise

View file

@ -1,5 +0,0 @@
---
'@astrojs/mdx': patch
---
Remove `@mdx-js/rollup` dependency

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
fix: add astro-static-slot to the list of inert tags in astro css

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
Use `AstroError` for `Astro.glob` errors

View file

@ -1,5 +0,0 @@
---
'astro': patch
---
The `src` property returned by ESM importing images with `astro:assets` is now an absolute path, unlocking support for importing images outside the project.

View file

@ -1,5 +1,46 @@
# astro # astro
## 2.5.6
### Patch Changes
- [#7193](https://github.com/withastro/astro/pull/7193) [`8b041bf57`](https://github.com/withastro/astro/commit/8b041bf57c76830c4070330270521e05d8e58474) Thanks [@ematipico](https://github.com/ematipico)! - Refactor how pages are emitted during the internal bundling. Now each
page is emitted as a separate entry point.
- [#7218](https://github.com/withastro/astro/pull/7218) [`6c7df28ab`](https://github.com/withastro/astro/commit/6c7df28ab34b756b8426443bf6976e24d4611a62) Thanks [@bluwy](https://github.com/bluwy)! - Fix CSS deduping and missing chunks
- [#7235](https://github.com/withastro/astro/pull/7235) [`ee2aca80a`](https://github.com/withastro/astro/commit/ee2aca80a71afe843af943b11966fcf77f556cfb) Thanks [@MoustaphaDev](https://github.com/MoustaphaDev)! - Prioritize dynamic prerendered routes over dynamic server routes
- [#7192](https://github.com/withastro/astro/pull/7192) [`7851f9258`](https://github.com/withastro/astro/commit/7851f9258fae2f54795470253df9ce4bcd5f9cb0) Thanks [@ematipico](https://github.com/ematipico)! - Detect `mdx` files using their full extension
- [#7244](https://github.com/withastro/astro/pull/7244) [`bef3a75db`](https://github.com/withastro/astro/commit/bef3a75dbc48d584daff9f7f3d5a8937b0356170) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Remove the auto-generated `$entry` variable for Markdoc entries. To access frontmatter as a variable, you can pass `entry.data` as a prop where you render your content:
```astro
---
import { getEntry } from 'astro:content';
const entry = await getEntry('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<Content frontmatter={entry.data} />
```
- [#7204](https://github.com/withastro/astro/pull/7204) [`52af9ad18`](https://github.com/withastro/astro/commit/52af9ad18840ffa4e2996386c82cbe34d9fd076a) Thanks [@bluwy](https://github.com/bluwy)! - Add error message if `Astro.glob` is called outside of an Astro file
- [#7246](https://github.com/withastro/astro/pull/7246) [`f5063d0a0`](https://github.com/withastro/astro/commit/f5063d0a01e3179da902fdc0a2b22f88cb3c95c7) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Fix content collection build errors for empty collections or underscore files of type `.json`.
- [#7062](https://github.com/withastro/astro/pull/7062) [`cf621340b`](https://github.com/withastro/astro/commit/cf621340b00fda441f4ef43196c0363d09eae70c) Thanks [@wulinsheng123](https://github.com/wulinsheng123)! - fix miss a head when the templaterender has a promise
- [#7189](https://github.com/withastro/astro/pull/7189) [`2bda7fb0b`](https://github.com/withastro/astro/commit/2bda7fb0bce346f7725086980e1648e2636bbefb) Thanks [@elevatebart](https://github.com/elevatebart)! - fix: add astro-static-slot to the list of inert tags in astro css
- [#7219](https://github.com/withastro/astro/pull/7219) [`af3c5a2e2`](https://github.com/withastro/astro/commit/af3c5a2e25bd3e7b2a3f7f08e41ee457093c8cb1) Thanks [@bluwy](https://github.com/bluwy)! - Use `AstroError` for `Astro.glob` errors
- [#7139](https://github.com/withastro/astro/pull/7139) [`f2f18b440`](https://github.com/withastro/astro/commit/f2f18b44055c6334a39d6379de88fe41e518aa1e) Thanks [@Princesseuh](https://github.com/Princesseuh)! - The `src` property returned by ESM importing images with `astro:assets` is now an absolute path, unlocking support for importing images outside the project.
- Updated dependencies [[`bf63f615f`](https://github.com/withastro/astro/commit/bf63f615fc1b97d6fb84db55f7639084e3ada5af)]:
- @astrojs/webapi@2.2.0
## 2.5.5 ## 2.5.5
### Patch Changes ### Patch Changes

View file

@ -1,6 +1,6 @@
{ {
"name": "astro", "name": "astro",
"version": "2.5.5", "version": "2.5.6",
"description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.", "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.",
"type": "module", "type": "module",
"author": "withastro", "author": "withastro",
@ -117,7 +117,7 @@
"@astrojs/language-server": "^1.0.0", "@astrojs/language-server": "^1.0.0",
"@astrojs/markdown-remark": "^2.2.1", "@astrojs/markdown-remark": "^2.2.1",
"@astrojs/telemetry": "^2.1.1", "@astrojs/telemetry": "^2.1.1",
"@astrojs/webapi": "^2.1.1", "@astrojs/webapi": "^2.2.0",
"@babel/core": "^7.21.8", "@babel/core": "^7.21.8",
"@babel/generator": "^7.18.2", "@babel/generator": "^7.18.2",
"@babel/parser": "^7.18.4", "@babel/parser": "^7.18.4",

View file

@ -1275,8 +1275,9 @@ export interface ContentEntryType {
getRenderModule?( getRenderModule?(
this: rollup.PluginContext, this: rollup.PluginContext,
params: { params: {
contents: string;
fileUrl: URL;
viteId: string; viteId: string;
entry: ContentEntryModule;
} }
): rollup.LoadResult | Promise<rollup.LoadResult>; ): rollup.LoadResult | Promise<rollup.LoadResult>;
contentModuleTypes?: string; contentModuleTypes?: string;

View file

@ -11,12 +11,12 @@ import { info, warn, type LogOptions } from '../core/logger/core.js';
import { isRelativePath } from '../core/path.js'; import { isRelativePath } from '../core/path.js';
import { CONTENT_TYPES_FILE, VIRTUAL_MODULE_ID } from './consts.js'; import { CONTENT_TYPES_FILE, VIRTUAL_MODULE_ID } from './consts.js';
import { import {
getContentEntryConfigByExtMap,
getContentEntryIdAndSlug, getContentEntryIdAndSlug,
getContentPaths, getContentPaths,
getDataEntryExts, getDataEntryExts,
getDataEntryId, getDataEntryId,
getEntryCollectionName, getEntryCollectionName,
getEntryConfigByExtMap,
getEntrySlug, getEntrySlug,
getEntryType, getEntryType,
reloadContentConfigObserver, reloadContentConfigObserver,
@ -74,7 +74,7 @@ export async function createContentTypesGenerator({
}: CreateContentGeneratorParams) { }: CreateContentGeneratorParams) {
const collectionEntryMap: CollectionEntryMap = {}; const collectionEntryMap: CollectionEntryMap = {};
const contentPaths = getContentPaths(settings.config, fs); const contentPaths = getContentPaths(settings.config, fs);
const contentEntryConfigByExt = getContentEntryConfigByExtMap(settings); const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const contentEntryExts = [...contentEntryConfigByExt.keys()]; const contentEntryExts = [...contentEntryConfigByExt.keys()];
const dataEntryExts = getDataEntryExts(settings); const dataEntryExts = getDataEntryExts(settings);
@ -414,7 +414,11 @@ async function writeContentFiles({
for (const collectionKey of Object.keys(collectionEntryMap).sort()) { for (const collectionKey of Object.keys(collectionEntryMap).sort()) {
const collectionConfig = contentConfig?.collections[JSON.parse(collectionKey)]; const collectionConfig = contentConfig?.collections[JSON.parse(collectionKey)];
const collection = collectionEntryMap[collectionKey]; const collection = collectionEntryMap[collectionKey];
if (collectionConfig?.type && collection.type !== collectionConfig.type) { if (
collectionConfig?.type &&
collection.type !== 'unknown' &&
collection.type !== collectionConfig.type
) {
viteServer.ws.send({ viteServer.ws.send({
type: 'error', type: 'error',
err: new AstroError({ err: new AstroError({
@ -433,7 +437,14 @@ async function writeContentFiles({
}); });
return; return;
} }
switch (collection.type) { const resolvedType: 'content' | 'data' =
collection.type === 'unknown'
? // Add empty / unknown collections to the data type map by default
// This ensures `getCollection('empty-collection')` doesn't raise a type error
collectionConfig?.type ?? 'data'
: collection.type;
switch (resolvedType) {
case 'content': case 'content':
contentTypesStr += `${collectionKey}: {\n`; contentTypesStr += `${collectionKey}: {\n`;
for (const entryKey of Object.keys(collection.entries).sort()) { for (const entryKey of Object.keys(collection.entries).sort()) {
@ -449,9 +460,6 @@ async function writeContentFiles({
contentTypesStr += `};\n`; contentTypesStr += `};\n`;
break; break;
case 'data': case 'data':
// Add empty / unknown collections to the data type map by default
// This ensures `getCollection('empty-collection')` doesn't raise a type error
case 'unknown':
dataTypesStr += `${collectionKey}: {\n`; dataTypesStr += `${collectionKey}: {\n`;
for (const entryKey of Object.keys(collection.entries).sort()) { for (const entryKey of Object.keys(collection.entries).sort()) {
const dataType = collectionConfig?.schema ? `InferEntrySchema<${collectionKey}>` : 'any'; const dataType = collectionConfig?.schema ? `InferEntrySchema<${collectionKey}>` : 'any';

View file

@ -10,6 +10,7 @@ import type {
AstroConfig, AstroConfig,
AstroSettings, AstroSettings,
ContentEntryType, ContentEntryType,
DataEntryType,
ImageInputFormat, ImageInputFormat,
} from '../@types/astro.js'; } from '../@types/astro.js';
import { VALID_INPUT_FORMATS } from '../assets/consts.js'; import { VALID_INPUT_FORMATS } from '../assets/consts.js';
@ -172,9 +173,11 @@ export function getDataEntryExts(settings: Pick<AstroSettings, 'dataEntryTypes'>
return settings.dataEntryTypes.map((t) => t.extensions).flat(); return settings.dataEntryTypes.map((t) => t.extensions).flat();
} }
export function getContentEntryConfigByExtMap(settings: Pick<AstroSettings, 'contentEntryTypes'>) { export function getEntryConfigByExtMap<TEntryType extends ContentEntryType | DataEntryType>(
const map: Map<string, ContentEntryType> = new Map(); entryTypes: TEntryType[]
for (const entryType of settings.contentEntryTypes) { ): Map<string, TEntryType> {
const map: Map<string, TEntryType> = new Map();
for (const entryType of entryTypes) {
for (const ext of entryType.extensions) { for (const ext of entryType.extensions) {
map.set(ext, entryType); map.set(ext, entryType);
} }

View file

@ -5,6 +5,7 @@ import type { PluginContext } from 'rollup';
import { pathToFileURL } from 'url'; import { pathToFileURL } from 'url';
import type { Plugin } from 'vite'; import type { Plugin } from 'vite';
import type { import type {
AstroConfig,
AstroSettings, AstroSettings,
ContentEntryModule, ContentEntryModule,
ContentEntryType, ContentEntryType,
@ -13,16 +14,16 @@ import type {
} from '../@types/astro.js'; } from '../@types/astro.js';
import { AstroErrorData } from '../core/errors/errors-data.js'; import { AstroErrorData } from '../core/errors/errors-data.js';
import { AstroError } from '../core/errors/errors.js'; import { AstroError } from '../core/errors/errors.js';
import { escapeViteEnvReferences, getFileInfo } from '../vite-plugin-utils/index.js'; import { escapeViteEnvReferences } from '../vite-plugin-utils/index.js';
import { CONTENT_FLAG, DATA_FLAG } from './consts.js'; import { CONTENT_FLAG, DATA_FLAG } from './consts.js';
import { import {
getContentEntryConfigByExtMap,
getContentEntryExts, getContentEntryExts,
getContentEntryIdAndSlug, getContentEntryIdAndSlug,
getContentPaths, getContentPaths,
getDataEntryExts, getDataEntryExts,
getDataEntryId, getDataEntryId,
getEntryCollectionName, getEntryCollectionName,
getEntryConfigByExtMap,
getEntryData, getEntryData,
getEntryType, getEntryType,
globalContentConfigObserver, globalContentConfigObserver,
@ -30,7 +31,6 @@ import {
parseEntrySlug, parseEntrySlug,
reloadContentConfigObserver, reloadContentConfigObserver,
type ContentConfig, type ContentConfig,
type ContentPaths,
} from './utils.js'; } from './utils.js';
function getContentRendererByViteId( function getContentRendererByViteId(
@ -70,14 +70,9 @@ export function astroContentImportPlugin({
const contentEntryExts = getContentEntryExts(settings); const contentEntryExts = getContentEntryExts(settings);
const dataEntryExts = getDataEntryExts(settings); const dataEntryExts = getDataEntryExts(settings);
const contentEntryConfigByExt = getContentEntryConfigByExtMap(settings); const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const dataEntryConfigByExt = getEntryConfigByExtMap(settings.dataEntryTypes);
const dataEntryExtToParser: Map<string, DataEntryType['getEntryInfo']> = new Map(); const { contentDir } = contentPaths;
for (const entryType of settings.dataEntryTypes) {
for (const ext of entryType.extensions) {
dataEntryExtToParser.set(ext, entryType.getEntryInfo);
}
}
const plugins: Plugin[] = [ const plugins: Plugin[] = [
{ {
@ -89,9 +84,9 @@ export function astroContentImportPlugin({
// This cache only exists for the `render()` function specific to content. // This cache only exists for the `render()` function specific to content.
const { id, data, collection, _internal } = await getDataEntryModule({ const { id, data, collection, _internal } = await getDataEntryModule({
fileId, fileId,
dataEntryExtToParser, entryConfigByExt: dataEntryConfigByExt,
contentPaths, contentDir,
settings, config: settings.config,
fs, fs,
pluginContext: this, pluginContext: this,
}); });
@ -109,8 +104,12 @@ export const _internal = {
return code; return code;
} else if (hasContentFlag(viteId, CONTENT_FLAG)) { } else if (hasContentFlag(viteId, CONTENT_FLAG)) {
const fileId = viteId.split('?')[0]; const fileId = viteId.split('?')[0];
const { id, slug, collection, body, data, _internal } = await setContentEntryModuleCache({ const { id, slug, collection, body, data, _internal } = await getContentEntryModule({
fileId, fileId,
entryConfigByExt: contentEntryConfigByExt,
contentDir,
config: settings.config,
fs,
pluginContext: this, pluginContext: this,
}); });
@ -170,112 +169,47 @@ export const _internal = {
if (settings.contentEntryTypes.some((t) => t.getRenderModule)) { if (settings.contentEntryTypes.some((t) => t.getRenderModule)) {
plugins.push({ plugins.push({
name: 'astro:content-render-imports', name: 'astro:content-render-imports',
async transform(_, viteId) { async transform(contents, viteId) {
const contentRenderer = getContentRendererByViteId(viteId, settings); const contentRenderer = getContentRendererByViteId(viteId, settings);
if (!contentRenderer) return; if (!contentRenderer) return;
const { fileId } = getFileInfo(viteId, settings.config); const fileId = viteId.split('?')[0];
const entry = await getContentEntryModuleFromCache(fileId); return contentRenderer.bind(this)({ viteId, contents, fileUrl: pathToFileURL(fileId) });
if (!entry) {
// Cached entry must exist (or be in-flight) when importing the module via content collections.
// This is ensured by the `astro:content-imports` plugin.
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unable to render ${JSON.stringify(
fileId
)}. Did you import this module directly without using a content collection query?`,
});
}
return contentRenderer.bind(this)({ entry, viteId });
}, },
}); });
} }
/** return plugins;
* There are two content collection plugins that depend on the same entry data: }
* - `astro:content-imports` - creates module containing the `getCollection()` result.
* - `astro:content-render-imports` - creates module containing the `collectionEntry.render()` result.
*
* We could run the same transforms to generate the slug and parsed data in each plugin,
* though this would run the user's collection schema _twice_ for each entry.
*
* Instead, we've implemented a cache for all content entry data. To avoid race conditions,
* this may store either the module itself or a queue of promises awaiting this module.
* See the implementations of `getContentEntryModuleFromCache` and `setContentEntryModuleCache`.
*/
const contentEntryModuleByIdCache = new Map<
string,
ContentEntryModule | AwaitingCacheResultQueue
>();
type AwaitingCacheResultQueue = {
awaitingQueue: ((val: ContentEntryModule) => void)[];
};
function isAwaitingQueue(
cacheEntry: ReturnType<typeof contentEntryModuleByIdCache.get>
): cacheEntry is AwaitingCacheResultQueue {
return typeof cacheEntry === 'object' && cacheEntry != null && 'awaitingQueue' in cacheEntry;
}
function getContentEntryModuleFromCache(id: string): Promise<ContentEntryModule | undefined> { type GetEntryModuleParams<TEntryType extends ContentEntryType | DataEntryType> = {
const cacheEntry = contentEntryModuleByIdCache.get(id); fs: typeof fsMod;
// It's possible to request an entry while `setContentEntryModuleCache` is still
// setting that entry. In this case, queue a promise for `setContentEntryModuleCache`
// to resolve once it is complete.
if (isAwaitingQueue(cacheEntry)) {
return new Promise<ContentEntryModule>((resolve, reject) => {
cacheEntry.awaitingQueue.push(resolve);
});
} else if (cacheEntry) {
return Promise.resolve(cacheEntry);
}
return Promise.resolve(undefined);
}
async function setContentEntryModuleCache({
fileId,
pluginContext,
}: {
fileId: string; fileId: string;
contentDir: URL;
pluginContext: PluginContext; pluginContext: PluginContext;
}): Promise<ContentEntryModule> { entryConfigByExt: Map<string, TEntryType>;
// Create a queue so, if `getContentEntryModuleFromCache` is called config: AstroConfig;
// while this function is running, we can resolve all requests };
// in the `awaitingQueue` with the result.
contentEntryModuleByIdCache.set(fileId, { awaitingQueue: [] }); async function getContentEntryModule(
params: GetEntryModuleParams<ContentEntryType>
): Promise<ContentEntryModule> {
const { fileId, contentDir, pluginContext, config } = params;
const { collectionConfig, entryConfig, entry, rawContents, collection } =
await getEntryModuleBaseInfo(params);
const contentConfig = await getContentConfigFromGlobal();
const rawContents = await fs.promises.readFile(fileId, 'utf-8');
const fileExt = extname(fileId);
if (!contentEntryConfigByExt.has(fileExt)) {
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `No parser found for content entry ${JSON.stringify(
fileId
)}. Did you apply an integration for this file type?`,
});
}
const contentEntryConfig = contentEntryConfigByExt.get(fileExt)!;
const { const {
rawData, rawData,
data: unvalidatedData,
body, body,
slug: frontmatterSlug, slug: frontmatterSlug,
data: unvalidatedData, } = await entryConfig.getEntryInfo({
} = await contentEntryConfig.getEntryInfo({
fileUrl: pathToFileURL(fileId), fileUrl: pathToFileURL(fileId),
contents: rawContents, contents: rawContents,
}); });
const entry = pathToFileURL(fileId); const _internal = { filePath: fileId, rawData };
const { contentDir } = contentPaths;
const collection = getEntryCollectionName({ entry, contentDir });
if (collection === undefined)
throw new AstroError(AstroErrorData.UnknownContentCollectionError);
const { id, slug: generatedSlug } = getContentEntryIdAndSlug({ entry, contentDir, collection }); const { id, slug: generatedSlug } = getContentEntryIdAndSlug({ entry, contentDir, collection });
const _internal = { filePath: fileId, rawData: rawData };
// TODO: move slug calculation to the start of the build
// to generate a performant lookup map for `getEntryBySlug`
const slug = parseEntrySlug({ const slug = parseEntrySlug({
id, id,
collection, collection,
@ -283,13 +217,12 @@ export const _internal = {
frontmatterSlug, frontmatterSlug,
}); });
const collectionConfig = contentConfig?.collections[collection]; const data = collectionConfig
let data = collectionConfig
? await getEntryData( ? await getEntryData(
{ id, collection, _internal, unvalidatedData }, { id, collection, _internal, unvalidatedData },
collectionConfig, collectionConfig,
pluginContext, pluginContext,
settings.config config
) )
: unvalidatedData; : unvalidatedData;
@ -302,18 +235,85 @@ export const _internal = {
_internal, _internal,
}; };
const cacheEntry = contentEntryModuleByIdCache.get(fileId);
// Pass the entry to all promises awaiting this result
if (isAwaitingQueue(cacheEntry)) {
for (const resolve of cacheEntry.awaitingQueue) {
resolve(contentEntryModule);
}
}
contentEntryModuleByIdCache.set(fileId, contentEntryModule);
return contentEntryModule; return contentEntryModule;
} }
return plugins; async function getDataEntryModule(
params: GetEntryModuleParams<DataEntryType>
): Promise<DataEntryModule> {
const { fileId, contentDir, pluginContext, config } = params;
const { collectionConfig, entryConfig, entry, rawContents, collection } =
await getEntryModuleBaseInfo(params);
const { rawData = '', data: unvalidatedData } = await entryConfig.getEntryInfo({
fileUrl: pathToFileURL(fileId),
contents: rawContents,
});
const _internal = { filePath: fileId, rawData };
const id = getDataEntryId({ entry, contentDir, collection });
const data = collectionConfig
? await getEntryData(
{ id, collection, _internal, unvalidatedData },
collectionConfig,
pluginContext,
config
)
: unvalidatedData;
const dataEntryModule: DataEntryModule = {
id,
collection,
data,
_internal,
};
return dataEntryModule;
}
// Shared logic for `getContentEntryModule` and `getDataEntryModule`
// Extracting to a helper was easier that conditionals and generics :)
async function getEntryModuleBaseInfo<TEntryType extends ContentEntryType | DataEntryType>({
fileId,
entryConfigByExt,
contentDir,
fs,
}: GetEntryModuleParams<TEntryType>) {
const contentConfig = await getContentConfigFromGlobal();
let rawContents;
try {
rawContents = await fs.promises.readFile(fileId, 'utf-8');
} catch (e) {
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unexpected error reading entry ${JSON.stringify(fileId)}.`,
stack: e instanceof Error ? e.stack : undefined,
});
}
const fileExt = extname(fileId);
const entryConfig = entryConfigByExt.get(fileExt);
if (!entryConfig) {
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `No parser found for data entry ${JSON.stringify(
fileId
)}. Did you apply an integration for this file type?`,
});
}
const entry = pathToFileURL(fileId);
const collection = getEntryCollectionName({ entry, contentDir });
if (collection === undefined) throw new AstroError(AstroErrorData.UnknownContentCollectionError);
const collectionConfig = contentConfig?.collections[collection];
return {
collectionConfig,
entry,
entryConfig,
collection,
rawContents,
};
} }
async function getContentConfigFromGlobal() { async function getContentConfigFromGlobal() {
@ -352,68 +352,3 @@ async function getContentConfigFromGlobal() {
return contentConfig; return contentConfig;
} }
type GetDataEntryModuleParams = {
fs: typeof fsMod;
fileId: string;
contentPaths: Pick<ContentPaths, 'contentDir'>;
pluginContext: PluginContext;
dataEntryExtToParser: Map<string, DataEntryType['getEntryInfo']>;
settings: Pick<AstroSettings, 'config'>;
};
async function getDataEntryModule({
fileId,
dataEntryExtToParser,
contentPaths,
fs,
pluginContext,
settings,
}: GetDataEntryModuleParams): Promise<DataEntryModule> {
const contentConfig = await getContentConfigFromGlobal();
let rawContents;
try {
rawContents = await fs.promises.readFile(fileId, 'utf-8');
} catch (e) {
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unexpected error reading entry ${JSON.stringify(fileId)}.`,
stack: e instanceof Error ? e.stack : undefined,
});
}
const fileExt = extname(fileId);
const dataEntryParser = dataEntryExtToParser.get(fileExt);
if (!dataEntryParser) {
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `No parser found for data entry ${JSON.stringify(
fileId
)}. Did you apply an integration for this file type?`,
});
}
const { data: unvalidatedData, rawData = '' } = await dataEntryParser({
fileUrl: pathToFileURL(fileId),
contents: rawContents,
});
const entry = pathToFileURL(fileId);
const { contentDir } = contentPaths;
const collection = getEntryCollectionName({ entry, contentDir });
if (collection === undefined) throw new AstroError(AstroErrorData.UnknownContentCollectionError);
const id = getDataEntryId({ entry, contentDir, collection });
const _internal = { filePath: fileId, rawData };
const collectionConfig = contentConfig?.collections[collection];
const data = collectionConfig
? await getEntryData(
{ id, collection, _internal, unvalidatedData },
collectionConfig,
pluginContext,
settings.config
)
: unvalidatedData;
return { id, collection, data, _internal };
}

View file

@ -4,17 +4,17 @@ import { extname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url'; import { fileURLToPath, pathToFileURL } from 'node:url';
import pLimit from 'p-limit'; import pLimit from 'p-limit';
import type { Plugin } from 'vite'; import type { Plugin } from 'vite';
import type { AstroSettings } from '../@types/astro.js'; import type { AstroSettings, ContentEntryType } from '../@types/astro.js';
import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { rootRelativePath } from '../core/util.js'; import { rootRelativePath } from '../core/util.js';
import { VIRTUAL_MODULE_ID } from './consts.js'; import { VIRTUAL_MODULE_ID } from './consts.js';
import { import {
getContentEntryConfigByExtMap,
getContentEntryIdAndSlug, getContentEntryIdAndSlug,
getContentPaths, getContentPaths,
getDataEntryExts, getDataEntryExts,
getDataEntryId, getDataEntryId,
getEntryCollectionName, getEntryCollectionName,
getEntryConfigByExtMap,
getEntrySlug, getEntrySlug,
getEntryType, getEntryType,
getExtGlob, getExtGlob,
@ -32,7 +32,7 @@ export function astroContentVirtualModPlugin({
const contentPaths = getContentPaths(settings.config); const contentPaths = getContentPaths(settings.config);
const relContentDir = rootRelativePath(settings.config.root, contentPaths.contentDir); const relContentDir = rootRelativePath(settings.config.root, contentPaths.contentDir);
const contentEntryConfigByExt = getContentEntryConfigByExtMap(settings); const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const contentEntryExts = [...contentEntryConfigByExt.keys()]; const contentEntryExts = [...contentEntryConfigByExt.keys()];
const dataEntryExts = getDataEntryExts(settings); const dataEntryExts = getDataEntryExts(settings);
@ -43,8 +43,12 @@ export function astroContentVirtualModPlugin({
new URL('reference-map.json', contentPaths.cacheDir).pathname new URL('reference-map.json', contentPaths.cacheDir).pathname
) )
.replace('@@CONTENT_DIR@@', relContentDir) .replace('@@CONTENT_DIR@@', relContentDir)
.replace('@@CONTENT_ENTRY_GLOB_PATH@@', `${relContentDir}**/*${getExtGlob(contentEntryExts)}`) .replace(
.replace('@@DATA_ENTRY_GLOB_PATH@@', `${relContentDir}**/*${getExtGlob(dataEntryExts)}`) '@@CONTENT_ENTRY_GLOB_PATH@@',
// [!_] = ignore files starting with "_"
`${relContentDir}**/[!_]*${getExtGlob(contentEntryExts)}`
)
.replace('@@DATA_ENTRY_GLOB_PATH@@', `${relContentDir}**/[!_]*${getExtGlob(dataEntryExts)}`)
.replace( .replace(
'@@RENDER_ENTRY_GLOB_PATH@@', '@@RENDER_ENTRY_GLOB_PATH@@',
`${relContentDir}**/*${getExtGlob(/** Note: data collections excluded */ contentEntryExts)}` `${relContentDir}**/*${getExtGlob(/** Note: data collections excluded */ contentEntryExts)}`
@ -92,7 +96,7 @@ export async function getStringifiedLookupMap({
root, root,
fs, fs,
}: { }: {
contentEntryConfigByExt: ReturnType<typeof getContentEntryConfigByExtMap>; contentEntryConfigByExt: Map<string, ContentEntryType>;
dataEntryExts: string[]; dataEntryExts: string[];
contentPaths: Pick<ContentPaths, 'contentDir' | 'config'>; contentPaths: Pick<ContentPaths, 'contentDir' | 'config'>;
root: URL; root: URL;

View file

@ -119,4 +119,32 @@ title: Post
expect(e.hint).to.include("Try adding `type: 'data'`"); expect(e.hint).to.include("Try adding `type: 'data'`");
} }
}); });
it('does not raise error for empty collection with config', async () => {
const fs = createFsWithFallback(
{
// Add placeholder to ensure directory exists
'/src/content/i18n/_placeholder.txt': 'Need content here',
'/src/content/config.ts': `
import { z, defineCollection } from 'astro:content';
const i18n = defineCollection({
type: 'data',
schema: z.object({
greeting: z.string(),
}),
});
export const collections = { i18n };`,
},
root
);
try {
const res = await sync({ fs });
expect(res).to.equal(0);
} catch (e) {
expect.fail(0, 1, `Did not expect sync to throw: ${e.message}`);
}
});
}); });

View file

@ -43,7 +43,7 @@
"tiny-glob": "^0.2.9" "tiny-glob": "^0.2.9"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"astro": "workspace:*", "astro": "workspace:*",

View file

@ -36,7 +36,7 @@
"esbuild": "^0.15.18" "esbuild": "^0.15.18"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"astro": "workspace:*", "astro": "workspace:*",

View file

@ -62,7 +62,7 @@
"vite": "^4.3.1" "vite": "^4.3.1"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5", "astro": "workspace:^2.5.6",
"sharp": ">=0.31.0" "sharp": ">=0.31.0"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {

View file

@ -1,5 +1,59 @@
# @astrojs/markdoc # @astrojs/markdoc
## 0.3.0
### Minor Changes
- [#7244](https://github.com/withastro/astro/pull/7244) [`bef3a75db`](https://github.com/withastro/astro/commit/bef3a75dbc48d584daff9f7f3d5a8937b0356170) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Remove the auto-generated `$entry` variable for Markdoc entries. To access frontmatter as a variable, you can pass `entry.data` as a prop where you render your content:
```astro
---
import { getEntry } from 'astro:content';
const entry = await getEntry('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<Content frontmatter={entry.data} />
```
### Patch Changes
- [#7187](https://github.com/withastro/astro/pull/7187) [`1efaef6be`](https://github.com/withastro/astro/commit/1efaef6be0265c68eac706623778e8ad23b33247) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add support for syntax highlighting with Shiki. Apply to your Markdoc config using the `extends` property:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import shiki from '@astrojs/markdoc/shiki';
export default defineMarkdocConfig({
extends: [
shiki({
/** Shiki config options */
}),
],
});
```
Learn more in the [`@astrojs/markdoc` README.](https://docs.astro.build/en/guides/integrations-guide/markdoc/#syntax-highlighting)
- [#7209](https://github.com/withastro/astro/pull/7209) [`16b836411`](https://github.com/withastro/astro/commit/16b836411980f18c58ca15712d92cec1b3c95670) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add a built-in extension for syntax highlighting with Prism. Apply to your Markdoc config using the `extends` property:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import prism from '@astrojs/markdoc/prism';
export default defineMarkdocConfig({
extends: [prism()],
});
```
Learn more in the [`@astrojs/markdoc` README.](https://docs.astro.build/en/guides/integrations-guide/markdoc/#syntax-highlighting)
- Updated dependencies [[`8b041bf57`](https://github.com/withastro/astro/commit/8b041bf57c76830c4070330270521e05d8e58474), [`6c7df28ab`](https://github.com/withastro/astro/commit/6c7df28ab34b756b8426443bf6976e24d4611a62), [`ee2aca80a`](https://github.com/withastro/astro/commit/ee2aca80a71afe843af943b11966fcf77f556cfb), [`7851f9258`](https://github.com/withastro/astro/commit/7851f9258fae2f54795470253df9ce4bcd5f9cb0), [`bef3a75db`](https://github.com/withastro/astro/commit/bef3a75dbc48d584daff9f7f3d5a8937b0356170), [`52af9ad18`](https://github.com/withastro/astro/commit/52af9ad18840ffa4e2996386c82cbe34d9fd076a), [`f5063d0a0`](https://github.com/withastro/astro/commit/f5063d0a01e3179da902fdc0a2b22f88cb3c95c7), [`cf621340b`](https://github.com/withastro/astro/commit/cf621340b00fda441f4ef43196c0363d09eae70c), [`2bda7fb0b`](https://github.com/withastro/astro/commit/2bda7fb0bce346f7725086980e1648e2636bbefb), [`af3c5a2e2`](https://github.com/withastro/astro/commit/af3c5a2e25bd3e7b2a3f7f08e41ee457093c8cb1), [`f2f18b440`](https://github.com/withastro/astro/commit/f2f18b44055c6334a39d6379de88fe41e518aa1e)]:
- astro@2.5.6
## 0.2.3 ## 0.2.3
### Patch Changes ### Patch Changes

View file

@ -97,13 +97,9 @@ const { Content } = await entry.render();
`@astrojs/markdoc` offers configuration options to use all of Markdoc's features and connect UI components to your content. `@astrojs/markdoc` offers configuration options to use all of Markdoc's features and connect UI components to your content.
### Using components ### Use Astro components as Markdoc tags
You can add Astro components to your Markdoc using both [Markdoc tags][markdoc-tags] and HTML element [nodes][markdoc-nodes]. You can configure [Markdoc tags][markdoc-tags] that map to `.astro` components. You can add a new tag by creating a `markdoc.config.mjs|ts` file at the root of your project and configuring the `tag` attribute.
#### Render Markdoc tags as Astro components
You may configure [Markdoc tags][markdoc-tags] that map to components. You can configure a new tag by creating a `markdoc.config.mjs|ts` file at the root of your project and configuring the `tag` attribute.
This example renders an `Aside` component, and allows a `type` prop to be passed as a string: This example renders an `Aside` component, and allows a `type` prop to be passed as a string:
@ -141,9 +137,11 @@ Use tags like this fancy "aside" to add some *flair* to your docs.
{% /aside %} {% /aside %}
``` ```
#### Render Markdoc nodes / HTML elements as Astro components ### Custom headings
You may also want to map standard HTML elements like headings and paragraphs to components. For this, you can configure a custom [Markdoc node][markdoc-nodes]. This example overrides Markdoc's `heading` node to render a `Heading` component, and passes through Astro's default heading properties to define attributes and generate heading ids / slugs: `@astrojs/markdoc` automatically adds anchor links to your headings, and [generates a list of `headings` via the content collections API](https://docs.astro.build/en/guides/content-collections/#rendering-content-to-html). To further customize how headings are rendered, you can apply an Astro component [as a Markdoc node][markdoc-nodes].
This example renders a `Heading.astro` component using the `render` property:
```js ```js
// markdoc.config.mjs // markdoc.config.mjs
@ -154,55 +152,20 @@ export default defineMarkdocConfig({
nodes: { nodes: {
heading: { heading: {
render: Heading, render: Heading,
// Preserve default anchor link generation
...nodes.heading, ...nodes.heading,
}, },
}, },
}) })
``` ```
All Markdown headings will render the `Heading.astro` component and pass `attributes` as component props. For headings, Astro provides the following attributes by default: All Markdown headings will render the `Heading.astro` component and pass the following `attributes` as component props:
- `level: number` The heading level 1 - 6 - `level: number` The heading level 1 - 6
- `id: string` An `id` generated from the heading's text contents. This corresponds to the `slug` generated by the [content `render()` function](https://docs.astro.build/en/guides/content-collections/#rendering-content-to-html). - `id: string` An `id` generated from the heading's text contents. This corresponds to the `slug` generated by the [content `render()` function](https://docs.astro.build/en/guides/content-collections/#rendering-content-to-html).
For example, the heading `### Level 3 heading!` will pass `level: 3` and `id: 'level-3-heading'` as component props. For example, the heading `### Level 3 heading!` will pass `level: 3` and `id: 'level-3-heading'` as component props.
📚 [Find all of Markdoc's built-in nodes and node attributes on their documentation.](https://markdoc.dev/docs/nodes#built-in-nodes)
#### Use client-side UI components
Today, the `components` prop does not support the `client:` directive for hydrating components. To embed client-side components, create a wrapper `.astro` file to import your component and apply a `client:` directive manually.
This example wraps a `Aside.tsx` component with a `ClientAside.astro` wrapper:
```astro
---
// src/components/ClientAside.astro
import Aside from './Aside';
---
<Aside {...Astro.props} client:load />
```
This component can be passed to the `render` prop for any [tag][markdoc-tags] or [node][markdoc-nodes] in your config:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import Aside from './src/components/Aside.astro';
export default defineMarkdocConfig({
tags: {
aside: {
render: Aside,
attributes: {
type: { type: String },
}
},
},
})
```
### Syntax highlighting ### Syntax highlighting
`@astrojs/markdoc` provides [Shiki](https://github.com/shikijs/shiki) and [Prism](https://github.com/PrismJS) extensions to highlight your code blocks. `@astrojs/markdoc` provides [Shiki](https://github.com/shikijs/shiki) and [Prism](https://github.com/PrismJS) extensions to highlight your code blocks.
@ -249,21 +212,83 @@ export default defineMarkdocConfig({
}) })
``` ```
📚 To learn about configuring Prism stylesheets, [see our syntax highlighting guide.](https://docs.astro.build/en/guides/markdown-content/#prism-configuration) 📚 To learn about configuring Prism stylesheets, [see our syntax highlighting guide](https://docs.astro.build/en/guides/markdown-content/#prism-configuration).
### Access frontmatter and content collection information from your templates ### Set the root HTML element
You can access content collection information from your Markdoc templates using the `$entry` variable. This includes the entry `slug`, `collection` name, and frontmatter `data` parsed by your content collection schema (if any). This example renders the `title` frontmatter property as a heading: Markdoc wraps documents with an `<article>` tag by default. This can be changed from the `document` Markdoc node. This accepts an HTML element name or `null` if you prefer to remove the wrapper element:
```md ```js
--- // markdoc.config.mjs
title: Welcome to Markdoc 👋 import { defineMarkdocConfig, nodes } from '@astrojs/markdoc/config';
---
# {% $entry.data.title %} export default defineMarkdocConfig({
nodes: {
document: {
render: null, // default 'article'
...nodes.document, // Apply defaults for other options
},
},
})
``` ```
The `$entry` object matches [the `CollectionEntry` type](https://docs.astro.build/en/reference/api-reference/#collection-entry-type), excluding the `.render()` property. ### Custom Markdoc nodes / elements
You may want to render standard Markdown elements, such as paragraphs and bolded text, as Astro components. For this, you can configure a [Markdoc node][markdoc-nodes]. If a given node receives attributes, they will be available as component props.
This example renders blockquotes with a custom `Quote.astro` component:
```js
// markdoc.config.mjs
import { defineMarkdocConfig, nodes } from '@astrojs/markdoc/config';
import Quote from './src/components/Quote.astro';
export default defineMarkdocConfig({
nodes: {
blockquote: {
render: Quote,
// Apply Markdoc's defaults for other options
...nodes.blockquote,
},
},
})
```
📚 [Find all of Markdoc's built-in nodes and node attributes on their documentation.](https://markdoc.dev/docs/nodes#built-in-nodes)
### Use client-side UI components
Tags and nodes are restricted to `.astro` files. To embed client-side UI components in Markdoc, [use a wrapper `.astro` component that renders a framework component](/en/core-concepts/framework-components/#nesting-framework-components) with your desired `client:` directive.
This example wraps a React `Aside.tsx` component with a `ClientAside.astro` component:
```astro
---
// src/components/ClientAside.astro
import Aside from './Aside';
---
<Aside {...Astro.props} client:load />
```
This Astro component can now be passed to the `render` prop for any [tag][markdoc-tags] or [node][markdoc-nodes] in your config:
```js
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import ClientAside from './src/components/ClientAside.astro';
export default defineMarkdocConfig({
tags: {
aside: {
render: ClientAside,
attributes: {
type: { type: String },
}
},
},
})
```
### Markdoc config ### Markdoc config
@ -340,6 +365,23 @@ export default defineMarkdocConfig({
}) })
``` ```
### Access frontmatter from your Markdoc content
To access frontmatter, you can pass the entry `data` property [as a variable](#pass-markdoc-variables) where you render your content:
```astro
---
import { getEntry } from 'astro:content';
const entry = await getEntry('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<Content frontmatter={entry.data} />
```
This can now be accessed as `$frontmatter` in your Markdoc.
## Examples ## Examples
* The [Astro Markdoc starter template](https://github.com/withastro/astro/tree/latest/examples/with-markdoc) shows how to use Markdoc files in your Astro project. * The [Astro Markdoc starter template](https://github.com/withastro/astro/tree/latest/examples/with-markdoc) shows how to use Markdoc files in your Astro project.

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/markdoc", "name": "@astrojs/markdoc",
"description": "Add support for Markdoc in your Astro site", "description": "Add support for Markdoc in your Astro site",
"version": "0.2.3", "version": "0.3.0",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",
@ -51,7 +51,7 @@
"zod": "^3.17.3" "zod": "^3.17.3"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"@astrojs/markdown-remark": "^2.2.1", "@astrojs/markdown-remark": "^2.2.1",

View file

@ -8,6 +8,7 @@ import { isValidUrl, MarkdocError, parseFrontmatter, prependForwardSlash } from
// @ts-expect-error Cannot find module 'astro/assets' or its corresponding type declarations. // @ts-expect-error Cannot find module 'astro/assets' or its corresponding type declarations.
import { emitESMImage } from 'astro/assets'; import { emitESMImage } from 'astro/assets';
import { bold, red, yellow } from 'kleur/colors'; import { bold, red, yellow } from 'kleur/colors';
import path from 'node:path';
import type * as rollup from 'rollup'; import type * as rollup from 'rollup';
import { loadMarkdocConfig, type MarkdocConfigResult } from './load-config.js'; import { loadMarkdocConfig, type MarkdocConfigResult } from './load-config.js';
import { setupConfig } from './runtime.js'; import { setupConfig } from './runtime.js';
@ -61,10 +62,13 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
addContentEntryType({ addContentEntryType({
extensions: ['.mdoc'], extensions: ['.mdoc'],
getEntryInfo, getEntryInfo,
async getRenderModule({ entry, viteId }) { async getRenderModule({ contents, fileUrl, viteId }) {
const entry = getEntryInfo({ contents, fileUrl });
const ast = Markdoc.parse(entry.body); const ast = Markdoc.parse(entry.body);
const pluginContext = this; const pluginContext = this;
const markdocConfig = await setupConfig(userMarkdocConfig, entry); const markdocConfig = await setupConfig(userMarkdocConfig);
const filePath = fileURLToPath(fileUrl);
const validationErrors = Markdoc.validate(ast, markdocConfig).filter((e) => { const validationErrors = Markdoc.validate(ast, markdocConfig).filter((e) => {
return ( return (
@ -77,10 +81,11 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
}); });
if (validationErrors.length) { if (validationErrors.length) {
// Heuristic: take number of newlines for `rawData` and add 2 for the `---` fences // Heuristic: take number of newlines for `rawData` and add 2 for the `---` fences
const frontmatterBlockOffset = entry._internal.rawData.split('\n').length + 2; const frontmatterBlockOffset = entry.rawData.split('\n').length + 2;
const rootRelativePath = path.relative(fileURLToPath(astroConfig.root), filePath);
throw new MarkdocError({ throw new MarkdocError({
message: [ message: [
`**${String(entry.collection)}${String(entry.id)}** contains invalid content:`, `**${String(rootRelativePath)}** contains invalid content:`,
...validationErrors.map((e) => `- ${e.error.message}`), ...validationErrors.map((e) => `- ${e.error.message}`),
].join('\n'), ].join('\n'),
location: { location: {
@ -96,7 +101,7 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
await emitOptimizedImages(ast.children, { await emitOptimizedImages(ast.children, {
astroConfig, astroConfig,
pluginContext, pluginContext,
filePath: entry._internal.filePath, filePath,
}); });
} }

View file

@ -13,13 +13,9 @@ export { default as Markdoc } from '@markdoc/markdoc';
* TODO: virtual module to merge configs per-build instead of per-file? * TODO: virtual module to merge configs per-build instead of per-file?
*/ */
export async function setupConfig( export async function setupConfig(
userConfig: AstroMarkdocConfig, userConfig: AstroMarkdocConfig
entry: ContentEntryModule
): Promise<Omit<AstroMarkdocConfig, 'extends'>> { ): Promise<Omit<AstroMarkdocConfig, 'extends'>> {
let defaultConfig: AstroMarkdocConfig = { let defaultConfig: AstroMarkdocConfig = setupHeadingConfig();
...setupHeadingConfig(),
variables: { entry },
};
if (userConfig.extends) { if (userConfig.extends) {
for (let extension of userConfig.extends) { for (let extension of userConfig.extends) {

View file

@ -1,5 +1,5 @@
{ {
"name": "@test/markdoc-entry-prop", "name": "@test/markdoc-variables",
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"dependencies": { "dependencies": {

View file

@ -14,6 +14,6 @@ const { Content } = await entry.render();
<title>Astro</title> <title>Astro</title>
</head> </head>
<body> <body>
<Content /> <Content {entry} />
</body> </body>
</html> </html>

View file

@ -3,9 +3,9 @@ import { expect } from 'chai';
import { loadFixture } from '../../../astro/test/test-utils.js'; import { loadFixture } from '../../../astro/test/test-utils.js';
import markdoc from '../dist/index.js'; import markdoc from '../dist/index.js';
const root = new URL('./fixtures/entry-prop/', import.meta.url); const root = new URL('./fixtures/variables/', import.meta.url);
describe('Markdoc - Entry prop', () => { describe('Markdoc - Variables', () => {
let baseFixture; let baseFixture;
before(async () => { before(async () => {

View file

@ -1,5 +1,15 @@
# @astrojs/mdx # @astrojs/mdx
## 0.19.5
### Patch Changes
- [#7151](https://github.com/withastro/astro/pull/7151) [`ea16570b1`](https://github.com/withastro/astro/commit/ea16570b1e0929678170c10b06c011dc668d7013) Thanks [@bluwy](https://github.com/bluwy)! - Add `optimize` option for faster builds and rendering
- [#7192](https://github.com/withastro/astro/pull/7192) [`7851f9258`](https://github.com/withastro/astro/commit/7851f9258fae2f54795470253df9ce4bcd5f9cb0) Thanks [@ematipico](https://github.com/ematipico)! - Detect `mdx` files using their full extension
- [#7191](https://github.com/withastro/astro/pull/7191) [`27c6e0182`](https://github.com/withastro/astro/commit/27c6e01826a6da525f1f811d97784accd1ebbd96) Thanks [@bluwy](https://github.com/bluwy)! - Remove `@mdx-js/rollup` dependency
## 0.19.4 ## 0.19.4
### Patch Changes ### Patch Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/mdx", "name": "@astrojs/mdx",
"description": "Add support for MDX pages in your Astro site", "description": "Add support for MDX pages in your Astro site",
"version": "0.19.4", "version": "0.19.5",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",

View file

@ -37,13 +37,13 @@
"test": "npm run test-fn" "test": "npm run test-fn"
}, },
"dependencies": { "dependencies": {
"@astrojs/webapi": "^2.1.1",
"@astrojs/underscore-redirects": "^0.1.0", "@astrojs/underscore-redirects": "^0.1.0",
"@astrojs/webapi": "^2.2.0",
"@netlify/functions": "^1.0.0", "@netlify/functions": "^1.0.0",
"esbuild": "^0.15.18" "esbuild": "^0.15.18"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"@netlify/edge-functions": "^2.0.0", "@netlify/edge-functions": "^2.0.0",

View file

@ -33,12 +33,12 @@
"test": "mocha --exit --timeout 20000 test/" "test": "mocha --exit --timeout 20000 test/"
}, },
"dependencies": { "dependencies": {
"@astrojs/webapi": "^2.1.1", "@astrojs/webapi": "^2.2.0",
"send": "^0.18.0", "send": "^0.18.0",
"server-destroy": "^1.0.1" "server-destroy": "^1.0.1"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"@types/send": "^0.17.1", "@types/send": "^0.17.1",

View file

@ -1,5 +1,11 @@
# @astrojs/partytown # @astrojs/partytown
## 1.2.3
### Patch Changes
- [#7175](https://github.com/withastro/astro/pull/7175) [`59d8c50b8`](https://github.com/withastro/astro/commit/59d8c50b8426cd6825abc07405041779b7999022) Thanks [@AkashRajpurohit](https://github.com/AkashRajpurohit)! - fix typescript type for partytown options
## 1.2.2 ## 1.2.2
### Patch Changes ### Patch Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/partytown", "name": "@astrojs/partytown",
"description": "Use Partytown to move scripts into a web worker in your Astro project", "description": "Use Partytown to move scripts into a web worker in your Astro project",
"version": "1.2.2", "version": "1.2.3",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",

View file

@ -1,5 +1,11 @@
# @astrojs/preact # @astrojs/preact
## 2.2.1
### Patch Changes
- [#7196](https://github.com/withastro/astro/pull/7196) [`1c77779dd`](https://github.com/withastro/astro/commit/1c77779dd66a6db77c81ed235da076a6118decde) Thanks [@bluwy](https://github.com/bluwy)! - Fix `astro-static-slot` hydration mismatch error
## 2.2.0 ## 2.2.0
### Minor Changes ### Minor Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/preact", "name": "@astrojs/preact",
"description": "Use Preact components within Astro", "description": "Use Preact components within Astro",
"version": "2.2.0", "version": "2.2.1",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",

View file

@ -1,5 +1,11 @@
# @astrojs/react # @astrojs/react
## 2.2.1
### Patch Changes
- [#7196](https://github.com/withastro/astro/pull/7196) [`1c77779dd`](https://github.com/withastro/astro/commit/1c77779dd66a6db77c81ed235da076a6118decde) Thanks [@bluwy](https://github.com/bluwy)! - Fix `astro-static-slot` hydration mismatch error
## 2.2.0 ## 2.2.0
### Minor Changes ### Minor Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/react", "name": "@astrojs/react",
"description": "Use React components within Astro", "description": "Use React components within Astro",
"version": "2.2.0", "version": "2.2.1",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",

View file

@ -1,5 +1,11 @@
# @astrojs/sitemap # @astrojs/sitemap
## 1.3.2
### Patch Changes
- [#7028](https://github.com/withastro/astro/pull/7028) [`6ca3b5a9e`](https://github.com/withastro/astro/commit/6ca3b5a9e8b9aa19a9436043f8ead41e7938c32e) Thanks [@alexanderniebuhr](https://github.com/alexanderniebuhr)! - exported enum type to support typescript > 5.0
## 1.3.1 ## 1.3.1
### Patch Changes ### Patch Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/sitemap", "name": "@astrojs/sitemap",
"description": "Generate a sitemap for your Astro site", "description": "Generate a sitemap for your Astro site",
"version": "1.3.1", "version": "1.3.2",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"author": "withastro", "author": "withastro",

View file

@ -48,7 +48,7 @@
"vite": "^4.3.1" "vite": "^4.3.1"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5", "astro": "workspace:^2.5.6",
"svelte": "^3.54.0" "svelte": "^3.54.0"
}, },
"engines": { "engines": {

View file

@ -44,7 +44,7 @@
"vite": "^4.3.1" "vite": "^4.3.1"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5", "astro": "workspace:^2.5.6",
"tailwindcss": "^3.0.24" "tailwindcss": "^3.0.24"
}, },
"pnpm": { "pnpm": {

View file

@ -1,5 +1,15 @@
# @astrojs/vercel # @astrojs/vercel
## 3.4.1
### Patch Changes
- [#7208](https://github.com/withastro/astro/pull/7208) [`f5a8cffac`](https://github.com/withastro/astro/commit/f5a8cffac22c9e33fad6f47f7d166b55c86ad87b) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Fix `imagesConfig` being wrongly spelt as `imageConfig` in the README
- Updated dependencies [[`8b041bf57`](https://github.com/withastro/astro/commit/8b041bf57c76830c4070330270521e05d8e58474), [`6c7df28ab`](https://github.com/withastro/astro/commit/6c7df28ab34b756b8426443bf6976e24d4611a62), [`bf63f615f`](https://github.com/withastro/astro/commit/bf63f615fc1b97d6fb84db55f7639084e3ada5af), [`ee2aca80a`](https://github.com/withastro/astro/commit/ee2aca80a71afe843af943b11966fcf77f556cfb), [`7851f9258`](https://github.com/withastro/astro/commit/7851f9258fae2f54795470253df9ce4bcd5f9cb0), [`bef3a75db`](https://github.com/withastro/astro/commit/bef3a75dbc48d584daff9f7f3d5a8937b0356170), [`52af9ad18`](https://github.com/withastro/astro/commit/52af9ad18840ffa4e2996386c82cbe34d9fd076a), [`f5063d0a0`](https://github.com/withastro/astro/commit/f5063d0a01e3179da902fdc0a2b22f88cb3c95c7), [`cf621340b`](https://github.com/withastro/astro/commit/cf621340b00fda441f4ef43196c0363d09eae70c), [`2bda7fb0b`](https://github.com/withastro/astro/commit/2bda7fb0bce346f7725086980e1648e2636bbefb), [`af3c5a2e2`](https://github.com/withastro/astro/commit/af3c5a2e25bd3e7b2a3f7f08e41ee457093c8cb1), [`f2f18b440`](https://github.com/withastro/astro/commit/f2f18b44055c6334a39d6379de88fe41e518aa1e)]:
- astro@2.5.6
- @astrojs/webapi@2.2.0
## 3.4.0 ## 3.4.0
### Minor Changes ### Minor Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/vercel", "name": "@astrojs/vercel",
"description": "Deploy your site to Vercel", "description": "Deploy your site to Vercel",
"version": "3.4.0", "version": "3.4.1",
"type": "module", "type": "module",
"author": "withastro", "author": "withastro",
"license": "MIT", "license": "MIT",
@ -50,8 +50,8 @@
"test": "mocha --exit --timeout 20000 test/" "test": "mocha --exit --timeout 20000 test/"
}, },
"dependencies": { "dependencies": {
"@astrojs/webapi": "^2.1.1",
"@astrojs/internal-helpers": "^0.1.0", "@astrojs/internal-helpers": "^0.1.0",
"@astrojs/webapi": "^2.2.0",
"@vercel/analytics": "^0.1.8", "@vercel/analytics": "^0.1.8",
"@vercel/nft": "^0.22.1", "@vercel/nft": "^0.22.1",
"esbuild": "^0.17.12", "esbuild": "^0.17.12",
@ -60,7 +60,7 @@
"web-vitals": "^3.1.1" "web-vitals": "^3.1.1"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5" "astro": "workspace:^2.5.6"
}, },
"devDependencies": { "devDependencies": {
"@types/set-cookie-parser": "^2.4.2", "@types/set-cookie-parser": "^2.4.2",

View file

@ -1,5 +1,14 @@
# @astrojs/vue # @astrojs/vue
## 2.2.1
### Patch Changes
- [#7196](https://github.com/withastro/astro/pull/7196) [`1c77779dd`](https://github.com/withastro/astro/commit/1c77779dd66a6db77c81ed235da076a6118decde) Thanks [@bluwy](https://github.com/bluwy)! - Fix `astro-static-slot` hydration mismatch error
- Updated dependencies [[`8b041bf57`](https://github.com/withastro/astro/commit/8b041bf57c76830c4070330270521e05d8e58474), [`6c7df28ab`](https://github.com/withastro/astro/commit/6c7df28ab34b756b8426443bf6976e24d4611a62), [`ee2aca80a`](https://github.com/withastro/astro/commit/ee2aca80a71afe843af943b11966fcf77f556cfb), [`7851f9258`](https://github.com/withastro/astro/commit/7851f9258fae2f54795470253df9ce4bcd5f9cb0), [`bef3a75db`](https://github.com/withastro/astro/commit/bef3a75dbc48d584daff9f7f3d5a8937b0356170), [`52af9ad18`](https://github.com/withastro/astro/commit/52af9ad18840ffa4e2996386c82cbe34d9fd076a), [`f5063d0a0`](https://github.com/withastro/astro/commit/f5063d0a01e3179da902fdc0a2b22f88cb3c95c7), [`cf621340b`](https://github.com/withastro/astro/commit/cf621340b00fda441f4ef43196c0363d09eae70c), [`2bda7fb0b`](https://github.com/withastro/astro/commit/2bda7fb0bce346f7725086980e1648e2636bbefb), [`af3c5a2e2`](https://github.com/withastro/astro/commit/af3c5a2e25bd3e7b2a3f7f08e41ee457093c8cb1), [`f2f18b440`](https://github.com/withastro/astro/commit/f2f18b44055c6334a39d6379de88fe41e518aa1e)]:
- astro@2.5.6
## 2.2.0 ## 2.2.0
### Minor Changes ### Minor Changes

View file

@ -1,6 +1,6 @@
{ {
"name": "@astrojs/vue", "name": "@astrojs/vue",
"version": "2.2.0", "version": "2.2.1",
"description": "Use Vue components within Astro", "description": "Use Vue components within Astro",
"type": "module", "type": "module",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
@ -56,7 +56,7 @@
"vue": "^3.2.37" "vue": "^3.2.37"
}, },
"peerDependencies": { "peerDependencies": {
"astro": "workspace:^2.5.5", "astro": "workspace:^2.5.6",
"vue": "^3.2.30" "vue": "^3.2.30"
}, },
"engines": { "engines": {

View file

@ -1,5 +1,11 @@
# @astrojs/webapi # @astrojs/webapi
## 2.2.0
### Minor Changes
- [#6981](https://github.com/withastro/astro/pull/6981) [`bf63f615f`](https://github.com/withastro/astro/commit/bf63f615fc1b97d6fb84db55f7639084e3ada5af) Thanks [@andremralves](https://github.com/andremralves)! - Add polyfill for `crypto`
## 2.1.1 ## 2.1.1
### Patch Changes ### Patch Changes

View file

@ -1,7 +1,7 @@
{ {
"name": "@astrojs/webapi", "name": "@astrojs/webapi",
"description": "Use Web APIs in Node", "description": "Use Web APIs in Node",
"version": "2.1.1", "version": "2.2.0",
"type": "module", "type": "module",
"exports": { "exports": {
".": { ".": {

View file

@ -410,7 +410,7 @@ importers:
dependencies: dependencies:
'@astrojs/markdoc': '@astrojs/markdoc':
specifier: ^0.2.0 specifier: ^0.2.0
version: link:../../packages/integrations/markdoc version: 0.2.0(astro@packages+astro)
astro: astro:
specifier: ^2.4.1 specifier: ^2.4.1
version: link:../../packages/astro version: link:../../packages/astro
@ -547,7 +547,7 @@ importers:
specifier: ^2.1.1 specifier: ^2.1.1
version: link:../telemetry version: link:../telemetry
'@astrojs/webapi': '@astrojs/webapi':
specifier: ^2.1.1 specifier: ^2.2.0
version: link:../webapi version: link:../webapi
'@babel/core': '@babel/core':
specifier: ^7.21.8 specifier: ^7.21.8
@ -4050,15 +4050,6 @@ importers:
specifier: workspace:* specifier: workspace:*
version: link:../../../../../astro version: link:../../../../../astro
packages/integrations/markdoc/test/fixtures/entry-prop:
dependencies:
'@astrojs/markdoc':
specifier: workspace:*
version: link:../../..
astro:
specifier: workspace:*
version: link:../../../../../astro
packages/integrations/markdoc/test/fixtures/headings: packages/integrations/markdoc/test/fixtures/headings:
dependencies: dependencies:
'@astrojs/markdoc': '@astrojs/markdoc':
@ -4126,6 +4117,15 @@ importers:
specifier: workspace:* specifier: workspace:*
version: link:../../../../../astro version: link:../../../../../astro
packages/integrations/markdoc/test/fixtures/variables:
dependencies:
'@astrojs/markdoc':
specifier: workspace:*
version: link:../../..
astro:
specifier: workspace:*
version: link:../../../../../astro
packages/integrations/mdx: packages/integrations/mdx:
dependencies: dependencies:
'@astrojs/markdown-remark': '@astrojs/markdown-remark':
@ -4394,7 +4394,7 @@ importers:
specifier: ^0.1.0 specifier: ^0.1.0
version: link:../../underscore-redirects version: link:../../underscore-redirects
'@astrojs/webapi': '@astrojs/webapi':
specifier: ^2.1.1 specifier: ^2.2.0
version: link:../../webapi version: link:../../webapi
'@netlify/functions': '@netlify/functions':
specifier: ^1.0.0 specifier: ^1.0.0
@ -4479,7 +4479,7 @@ importers:
packages/integrations/node: packages/integrations/node:
dependencies: dependencies:
'@astrojs/webapi': '@astrojs/webapi':
specifier: ^2.1.1 specifier: ^2.2.0
version: link:../../webapi version: link:../../webapi
send: send:
specifier: ^0.18.0 specifier: ^0.18.0
@ -4849,7 +4849,7 @@ importers:
specifier: ^0.1.0 specifier: ^0.1.0
version: link:../../internal-helpers version: link:../../internal-helpers
'@astrojs/webapi': '@astrojs/webapi':
specifier: ^2.1.1 specifier: ^2.2.0
version: link:../../webapi version: link:../../webapi
'@vercel/analytics': '@vercel/analytics':
specifier: ^0.1.8 specifier: ^0.1.8
@ -5596,6 +5596,24 @@ packages:
vscode-uri: 3.0.7 vscode-uri: 3.0.7
dev: false dev: false
/@astrojs/markdoc@0.2.0(astro@packages+astro):
resolution: {integrity: sha512-sGDdUooNq7I7LDWOrzuAiNvZLqtWzUvMdmWA6O7y54zMVVCx4OPsLCd+oIUGvF5lZ+Yvv1dHGCM1fWnqOc+B4A==}
engines: {node: '>=16.12.0'}
peerDependencies:
astro: '*'
dependencies:
'@markdoc/markdoc': 0.2.2
astro: link:packages/astro
esbuild: 0.17.18
github-slugger: 2.0.0
gray-matter: 4.0.3
kleur: 4.1.5
zod: 3.20.6
transitivePeerDependencies:
- '@types/react'
- react
dev: false
/@babel/code-frame@7.21.4: /@babel/code-frame@7.21.4:
resolution: {integrity: sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==} resolution: {integrity: sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==}
engines: {node: '>=6.9.0'} engines: {node: '>=6.9.0'}
@ -8118,6 +8136,21 @@ packages:
- supports-color - supports-color
dev: false dev: false
/@markdoc/markdoc@0.2.2:
resolution: {integrity: sha512-0TiD9jmA5h5znN4lxo7HECAu3WieU5g5vUsfByeucrdR/x88hEilpt16EydFyJwJddQ/3w5HQgW7Ovy62r4cyw==}
engines: {node: '>=14.7.0'}
peerDependencies:
'@types/react': '*'
react: '*'
peerDependenciesMeta:
'@types/react':
optional: true
react:
optional: true
optionalDependencies:
'@types/markdown-it': 12.2.3
dev: false
/@markdoc/markdoc@0.3.0: /@markdoc/markdoc@0.3.0:
resolution: {integrity: sha512-QWCF8krIIw52ulflfnoff0yG1eKl9CCGA3KAiOjHyYtHNzSEouFh8lO52nAaO3qV2Ctj1GTB8TTb2rTfvISQfA==} resolution: {integrity: sha512-QWCF8krIIw52ulflfnoff0yG1eKl9CCGA3KAiOjHyYtHNzSEouFh8lO52nAaO3qV2Ctj1GTB8TTb2rTfvISQfA==}
engines: {node: '>=14.7.0'} engines: {node: '>=14.7.0'}