Skip to content

Instantly share code, notes, and snippets.

@virtuallyunknown
Created April 29, 2026 13:21
Show Gist options
  • Select an option

  • Save virtuallyunknown/99d03bdc864cb67c920ec8dbf013fbe7 to your computer and use it in GitHub Desktop.

Select an option

Save virtuallyunknown/99d03bdc864cb67c920ec8dbf013fbe7 to your computer and use it in GitHub Desktop.
import type { AstroIntegration, AstroIntegrationLogger } from 'astro';
import type { CollectionEntry } from 'astro:content';
import { readFile } from 'node:fs/promises';
import { close, createIndex } from 'pagefind';
type GetCollectionDataArgs =
| { context: 'build', port?: never }
| { context: 'dev', port: number };
async function getCollectionData({ context, port }: GetCollectionDataArgs) {
if (context === 'build') {
const data = await readFile('./dist/build/apps.json', { encoding: 'utf-8' });
return JSON.parse(data) as CollectionEntry<'apps'>[];
}
const data = await fetch(`http://localhost:${port}/build/apps.json`);
return await data.json() as CollectionEntry<'apps'>[];
}
// TODO: figure out how this will be bundled efficiently
async function writePagefindIndexes({ data, logger }: { logger: AstroIntegrationLogger, data: CollectionEntry<'apps'>[] }) {
const { index } = await createIndex();
if (!index) {
logger.error('Failed to create Pagefind index.');
process.exit(1);
}
const promises = await Promise.all(
data.map(app => index.addCustomRecord({
content: app.data.description,
url: `/apps/${app.data.name}/`,
language: 'en',
})),
);
if (promises.some(p => p.errors.length > 0)) {
logger.error('Error adding records to Pagefind index.');
process.exit(1);
}
for (const app of data) {
await index.addCustomRecord({
content: app.data.description,
url: `/apps/${app.data.name}/`,
language: 'en',
});
}
const { errors } = await index.writeFiles({
outputPath: './public/pagefind',
});
await close();
for (const error of errors) {
logger.error(`Error writing Pagefind index: ${error}`);
}
}
export function pageFindIntegration(): AstroIntegration {
return {
name: 'pagefind-integration',
hooks: {
'astro:build:done': async ({ logger }) => {
const apps = await getCollectionData({ context: 'build' });
await writePagefindIndexes({ data: apps, logger });
},
'astro:server:start': async ({ address, logger }) => {
const apps = await getCollectionData({ context: 'dev', port: address.port });
await writePagefindIndexes({ data: apps, logger });
},
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment