0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-27 22:19:04 -05:00
astro/packages/integrations/partytown/src/index.ts

64 lines
2 KiB
TypeScript
Raw Normal View History

import type { PartytownConfig } from '@builder.io/partytown/integration';
2023-03-28 08:47:15 +00:00
import { partytownSnippet } from '@builder.io/partytown/integration';
import { copyLibFiles, libDirPath } from '@builder.io/partytown/utils';
import type { AstroIntegration } from 'astro';
import { createRequire } from 'module';
import * as fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
2022-06-06 16:49:53 +00:00
import sirv from './sirv.js';
const resolve = createRequire(import.meta.url).resolve;
type PartytownOptions = {
config?: PartytownConfig;
};
function appendForwardSlash(str: string) {
return str.endsWith('/') ? str : str + '/';
}
export default function createPlugin(options?: PartytownOptions): AstroIntegration {
let partytownSnippetHtml: string;
const partytownEntrypoint = resolve('@builder.io/partytown/package.json');
const partytownLibDirectory = path.resolve(partytownEntrypoint, '../lib');
return {
name: '@astrojs/partytown',
hooks: {
'astro:config:setup': ({ config: _config, command, injectScript }) => {
const lib = `${appendForwardSlash(_config.base)}~partytown/`;
const partytownConfig = {
...options?.config,
lib,
debug: options?.config?.debug ?? command === 'dev',
};
partytownSnippetHtml = partytownSnippet(partytownConfig);
injectScript('head-inline', partytownSnippetHtml);
},
'astro:server:setup': ({ server }) => {
const lib = `/~partytown/`;
2022-04-02 14:15:41 -06:00
server.middlewares.use(
sirv(partytownLibDirectory, {
mount: lib,
2022-04-02 14:15:41 -06:00
dev: true,
etag: true,
extensions: [],
})
);
},
'astro:build:done': async ({ dir }) => {
await copyLibFiles(fileURLToPath(new URL('~partytown', dir)), {
debugDir: options?.config?.debug ?? false,
2022-04-02 14:15:41 -06:00
});
},
'astro:build:ssr': async ({ manifest }) => {
const dirpath = libDirPath({ debugDir: false });
const files = await fs.promises.readdir(dirpath);
2022-06-23 13:05:55 +00:00
for (const file of files) {
if (file === 'debug') continue;
manifest.assets.push(`/~partytown/${file}`);
}
2022-06-23 13:05:55 +00:00
},
},
};
}