Compare commits

...

2 commits

Author SHA1 Message Date
bholmesdev
28658936ad feat: add --skip-sync to dev and prod 2023-02-06 09:52:15 -05:00
bholmesdev
a99f5a9301 refactor: move stuff around 2023-02-03 16:47:39 -05:00
10 changed files with 140 additions and 147 deletions

View file

@ -84,6 +84,7 @@ export interface CLIFlags {
port?: number;
config?: string;
drafts?: boolean;
skipSync?: boolean;
}
export interface BuildConfig {

View file

@ -21,7 +21,7 @@ interface Result {
export async function check(settings: AstroSettings, { logging }: { logging: LogOptions }) {
console.log(bold('astro check'));
const { sync } = await import('../sync/index.js');
const { sync } = await import('../../core/sync/index.js');
const syncRet = await sync(settings, { logging, fs });
// early exit on sync failure
if (syncRet === 1) return syncRet;

View file

@ -59,6 +59,7 @@ function printAstroHelp() {
['--base <pathname>', 'Specify your project base.'],
['--verbose', 'Enable verbose logging.'],
['--silent', 'Disable all logging.'],
['--skip-sync', 'Skip automatic content type generation.'],
['--version', 'Show the version number and exit.'],
['--help', 'Show this help message.'],
],
@ -203,7 +204,12 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
case 'build': {
const { default: build } = await import('../core/build/index.js');
return await build(settings, { ...flags, logging, telemetry });
return await build(settings, {
mode: flags.mode,
skipSync: flags['skip-sync'],
logging,
telemetry,
});
}
case 'check': {
@ -212,7 +218,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
}
case 'sync': {
const { sync } = await import('./sync/index.js');
const { sync } = await import('../core/sync/index.js');
const ret = await sync(settings, { logging, fs });
return process.exit(ret);

View file

@ -1,58 +0,0 @@
import { dim } from 'kleur/colors';
import type fsMod from 'node:fs';
import { performance } from 'node:perf_hooks';
import { createServer } from 'vite';
import type { AstroSettings } from '../../@types/astro';
import { createContentTypesGenerator } from '../../content/index.js';
import { globalContentConfigObserver } from '../../content/utils.js';
import { getTimeStat } from '../../core/build/util.js';
import { createVite } from '../../core/create-vite.js';
import { AstroError, AstroErrorData } from '../../core/errors/index.js';
import { info, LogOptions } from '../../core/logger/core.js';
import { setUpEnvTs } from '../../vite-plugin-inject-env-ts/index.js';
export async function sync(
settings: AstroSettings,
{ logging, fs }: { logging: LogOptions; fs: typeof fsMod }
): Promise<0 | 1> {
const timerStart = performance.now();
// Needed to load content config
const tempViteServer = await createServer(
await createVite(
{
server: { middlewareMode: true, hmr: false },
optimizeDeps: { entries: [] },
logLevel: 'silent',
},
{ settings, logging, mode: 'build', fs }
)
);
try {
const contentTypesGenerator = await createContentTypesGenerator({
contentConfigObserver: globalContentConfigObserver,
logging,
fs,
settings,
viteServer: tempViteServer,
});
const typesResult = await contentTypesGenerator.init();
if (typesResult.typesGenerated === false) {
switch (typesResult.reason) {
case 'no-content-dir':
default:
info(logging, 'content', 'No content directory found. Skipping type generation.');
return 0;
}
}
} catch (e) {
throw new AstroError(AstroErrorData.GenerateContentTypesError);
} finally {
await tempViteServer.close();
}
info(logging, 'content', `Types generated ${dim(getTimeStat(timerStart, performance.now()))}`);
await setUpEnvTs({ settings, logging, fs });
return 0;
}

View file

@ -5,6 +5,7 @@ import type { ViteDevServer } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
import { info, LogOptions } from '../core/logger/core.js';
import { appendForwardSlash } from '../core/path.js';
import { setUpEnvTs } from '../core/sync/index.js';
import { createContentTypesGenerator } from './types-generator.js';
import { getContentPaths, globalContentConfigObserver } from './utils.js';
@ -52,6 +53,7 @@ export async function attachContentServerListeners({
contentConfigObserver: globalContentConfigObserver,
});
await contentGenerator.init();
await setUpEnvTs({ settings, logging, fs });
info(logging, 'content', 'Types generated');
viteServer.watcher.on('add', (entry) => {

View file

@ -23,6 +23,7 @@ import { getTimeStat } from './util.js';
export interface BuildOptions {
mode?: RuntimeMode;
skipSync?: boolean;
logging: LogOptions;
telemetry: AstroTelemetry;
}
@ -38,6 +39,7 @@ class AstroBuilder {
private settings: AstroSettings;
private logging: LogOptions;
private mode: RuntimeMode = 'production';
private skipSync: boolean = false;
private origin: string;
private routeCache: RouteCache;
private manifest: ManifestData;
@ -47,6 +49,9 @@ class AstroBuilder {
if (options.mode) {
this.mode = options.mode;
}
if (options.skipSync) {
this.skipSync = options.skipSync;
}
this.settings = settings;
this.logging = options.logging;
this.routeCache = new RouteCache(this.logging);
@ -81,10 +86,12 @@ class AstroBuilder {
);
await runHookConfigDone({ settings: this.settings, logging });
const { sync } = await import('../../cli/sync/index.js');
const syncRet = await sync(this.settings, { logging, fs });
if (syncRet !== 0) {
return process.exit(syncRet);
if (!this.skipSync) {
const { sync } = await import('../sync/index.js');
const syncRet = await sync(this.settings, { logging, fs });
if (syncRet !== 0) {
return process.exit(syncRet);
}
}
return { viteConfig };

View file

@ -17,7 +17,6 @@ import configAliasVitePlugin from '../vite-plugin-config-alias/index.js';
import envVitePlugin from '../vite-plugin-env/index.js';
import astroHeadPropagationPlugin from '../vite-plugin-head-propagation/index.js';
import htmlVitePlugin from '../vite-plugin-html/index.js';
import { astroInjectEnvTsPlugin } from '../vite-plugin-inject-env-ts/index.js';
import astroIntegrationsContainerPlugin from '../vite-plugin-integrations-container/index.js';
import jsxVitePlugin from '../vite-plugin-jsx/index.js';
import astroLoadFallbackPlugin from '../vite-plugin-load-fallback/index.js';
@ -103,7 +102,6 @@ export async function createVite(
astroScriptsPageSSRPlugin({ settings }),
astroHeadPropagationPlugin({ settings }),
astroScannerPlugin({ settings }),
astroInjectEnvTsPlugin({ settings, logging, fs }),
astroContentVirtualModPlugin({ settings }),
astroContentImportPlugin({ fs, settings }),
astroContentAssetPropagationPlugin({ mode }),

View file

@ -72,7 +72,9 @@ export default async function dev(
warn(options.logging, null, msg.fsStrictWarning());
}
await attachContentServerListeners(restart.container);
if (!options.flags?.['skip-sync']) {
await attachContentServerListeners(restart.container);
}
return {
address: devServerAddressInfo,

View file

@ -0,0 +1,114 @@
import { bold, dim } from 'kleur/colors';
import type fsMod from 'node:fs';
import { performance } from 'node:perf_hooks';
import { createServer, normalizePath } from 'vite';
import type { AstroSettings } from '../../@types/astro';
import { createContentTypesGenerator } from '../../content/index.js';
import {
getContentPaths,
getDotAstroTypeReference,
globalContentConfigObserver,
} from '../../content/utils.js';
import { getTimeStat } from '../build/util.js';
import { createVite } from '../create-vite.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
import { info, LogOptions } from '../logger/core.js';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
export async function sync(
settings: AstroSettings,
{ logging, fs }: { logging: LogOptions; fs: typeof fsMod }
): Promise<0 | 1> {
const timerStart = performance.now();
// Needed to load content config
const tempViteServer = await createServer(
await createVite(
{
server: { middlewareMode: true, hmr: false },
optimizeDeps: { entries: [] },
logLevel: 'silent',
},
{ settings, logging, mode: 'build', fs }
)
);
try {
const contentTypesGenerator = await createContentTypesGenerator({
contentConfigObserver: globalContentConfigObserver,
logging,
fs,
settings,
viteServer: tempViteServer,
});
const typesResult = await contentTypesGenerator.init();
if (typesResult.typesGenerated === false) {
switch (typesResult.reason) {
case 'no-content-dir':
default:
info(logging, 'content', 'No content directory found. Skipping type generation.');
return 0;
}
}
} catch (e) {
throw new AstroError(AstroErrorData.GenerateContentTypesError);
} finally {
await tempViteServer.close();
}
info(logging, 'content', `Types generated ${dim(getTimeStat(timerStart, performance.now()))}`);
await setUpEnvTs({ settings, logging, fs });
return 0;
}
export async function setUpEnvTs({
settings,
logging,
fs,
}: {
settings: AstroSettings;
logging: LogOptions;
fs: typeof fsMod;
}) {
const envTsPath = getEnvTsPath(settings.config);
const dotAstroDir = getContentPaths(settings.config).cacheDir;
const dotAstroTypeReference = getDotAstroTypeReference(settings.config);
const envTsPathRelativetoRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);
if (fs.existsSync(envTsPath)) {
// Add `.astro` types reference if none exists
if (!fs.existsSync(dotAstroDir)) return;
let typesEnvContents = await fs.promises.readFile(envTsPath, 'utf-8');
const expectedTypeReference = getDotAstroTypeReference(settings.config);
if (!typesEnvContents.includes(expectedTypeReference)) {
typesEnvContents = `${expectedTypeReference}\n${typesEnvContents}`;
await fs.promises.writeFile(envTsPath, typesEnvContents, 'utf-8');
info(logging, 'content', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
} else {
// Otherwise, inject the `env.d.ts` file
let referenceDefs: string[] = [];
if (settings.config.integrations.find((i) => i.name === '@astrojs/image')) {
referenceDefs.push('/// <reference types="@astrojs/image/client" />');
} else {
referenceDefs.push('/// <reference types="astro/client" />');
}
if (fs.existsSync(dotAstroDir)) {
referenceDefs.push(dotAstroTypeReference);
}
await fs.promises.mkdir(settings.config.srcDir, { recursive: true });
await fs.promises.writeFile(envTsPath, referenceDefs.join('\n'), 'utf-8');
info(logging, 'astro', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
}
function getEnvTsPath({ srcDir }: { srcDir: URL }) {
return new URL('env.d.ts', srcDir);
}

View file

@ -1,79 +0,0 @@
import { bold } from 'kleur/colors';
import type fsMod from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { normalizePath, Plugin } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
import { getContentPaths, getDotAstroTypeReference } from '../content/index.js';
import { info, LogOptions } from '../core/logger/core.js';
export function getEnvTsPath({ srcDir }: { srcDir: URL }) {
return new URL('env.d.ts', srcDir);
}
export function astroInjectEnvTsPlugin({
settings,
logging,
fs,
}: {
settings: AstroSettings;
logging: LogOptions;
fs: typeof fsMod;
}): Plugin {
return {
name: 'astro-inject-env-ts',
// Use `post` to ensure project setup is complete
// Ex. `.astro` types have been written
enforce: 'post',
async config() {
await setUpEnvTs({ settings, logging, fs });
},
};
}
export async function setUpEnvTs({
settings,
logging,
fs,
}: {
settings: AstroSettings;
logging: LogOptions;
fs: typeof fsMod;
}) {
const envTsPath = getEnvTsPath(settings.config);
const dotAstroDir = getContentPaths(settings.config).cacheDir;
const dotAstroTypeReference = getDotAstroTypeReference(settings.config);
const envTsPathRelativetoRoot = normalizePath(
path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath))
);
if (fs.existsSync(envTsPath)) {
// Add `.astro` types reference if none exists
if (!fs.existsSync(dotAstroDir)) return;
let typesEnvContents = await fs.promises.readFile(envTsPath, 'utf-8');
const expectedTypeReference = getDotAstroTypeReference(settings.config);
if (!typesEnvContents.includes(expectedTypeReference)) {
typesEnvContents = `${expectedTypeReference}\n${typesEnvContents}`;
await fs.promises.writeFile(envTsPath, typesEnvContents, 'utf-8');
info(logging, 'content', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
} else {
// Otherwise, inject the `env.d.ts` file
let referenceDefs: string[] = [];
if (settings.config.integrations.find((i) => i.name === '@astrojs/image')) {
referenceDefs.push('/// <reference types="@astrojs/image/client" />');
} else {
referenceDefs.push('/// <reference types="astro/client" />');
}
if (fs.existsSync(dotAstroDir)) {
referenceDefs.push(dotAstroTypeReference);
}
await fs.promises.mkdir(settings.config.srcDir, { recursive: true });
await fs.promises.writeFile(envTsPath, referenceDefs.join('\n'), 'utf-8');
info(logging, 'astro', `Added ${bold(envTsPathRelativetoRoot)} types`);
}
}