Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/astro/src/container/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ function createManifest(
middleware: manifest?.middleware ?? middlewareInstance,
key: createKey(),
csp: manifest?.csp,
devToolbar: {
enabled: false,
latestAstroVersion: undefined,
debugInfoOutput: '',
},
};
}

Expand Down
39 changes: 30 additions & 9 deletions packages/astro/src/core/app/dev/pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import type { ComponentInstance } from '../../../types/astro.js';
import type {
DevToolbarMetadata,
RewritePayload,
RouteData,
SSRElement,
SSRResult,
} from '../../../types/public/index.js';
import { Pipeline, type TryRewriteResult } from '../../base-pipeline.js';
import { type HeadElements, Pipeline, type TryRewriteResult } from '../../base-pipeline.js';
import { ASTRO_VERSION } from '../../constants.js';
import { createModuleScriptElement, createStylesheetElementSet } from '../../render/ssr-element.js';
import { findRouteToRewrite } from '../../routing/rewrite.js';

type DevPipelineCreate = Pick<DevPipeline, 'logger' | 'manifest' | 'streaming'>;

export class DevPipeline extends Pipeline {
static create({
logger,
manifest,
streaming,
}: Pick<DevPipeline, 'logger' | 'manifest' | 'streaming'>) {
async function resolve(specifier: string) {
static create({ logger, manifest, streaming }: DevPipelineCreate) {
async function resolve(specifier: string): Promise<string> {
if (specifier.startsWith('/')) {
return specifier;
} else {
return '/@id/' + specifier;
}
}

const pipeline = new DevPipeline(
logger,
manifest,
Expand All @@ -42,7 +42,7 @@ export class DevPipeline extends Pipeline {
return pipeline;
}

headElements(routeData: RouteData): Pick<SSRResult, 'scripts' | 'styles' | 'links'> {
async headElements(routeData: RouteData): Promise<HeadElements> {
const routeInfo = this.manifest.routes.find((route) => route.routeData === routeData);
// may be used in the future for handling rel=modulepreload, rel=icon, rel=manifest etc.
const links = new Set<never>();
Expand All @@ -67,6 +67,27 @@ export class DevPipeline extends Pipeline {
children: '',
});

if (this.manifest.devToolbar.enabled) {
scripts.add({
props: {
type: 'module',
src: '/@id/astro/runtime/client/dev-toolbar/entrypoint.js',
},
children: '',
});

const additionalMetadata: DevToolbarMetadata['__astro_dev_toolbar__'] = {
root: this.manifest.rootDir.toString(),
version: ASTRO_VERSION,
latestAstroVersion: this.manifest.devToolbar.latestAstroVersion,
debugInfo: this.manifest.devToolbar.debugInfoOutput ?? '',
};

// Additional data for the dev overlay
const children = `window.__astro_dev_toolbar__ = ${JSON.stringify(additionalMetadata)}`;
scripts.add({ props: {}, children });
}

return { links, styles, scripts };
}

Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/core/app/pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ComponentInstance } from '../../types/astro.js';
import type { RewritePayload } from '../../types/public/common.js';
import type { RouteData, SSRElement, SSRResult } from '../../types/public/internal.js';
import { Pipeline, type TryRewriteResult } from '../base-pipeline.js';
import type { RouteData, SSRElement } from '../../types/public/internal.js';
import { type HeadElements, Pipeline, type TryRewriteResult } from '../base-pipeline.js';
import {
createAssetLink,
createModuleScriptElement,
Expand Down Expand Up @@ -46,7 +46,7 @@ export class AppPipeline extends Pipeline {
return pipeline;
}

headElements(routeData: RouteData): Pick<SSRResult, 'scripts' | 'styles' | 'links'> {
async headElements(routeData: RouteData): Promise<HeadElements> {
const routeInfo = this.manifest.routes.find((route) => route.routeData === routeData);
// may be used in the future for handling rel=modulepreload, rel=icon, rel=manifest etc.
const links = new Set<never>();
Expand Down
14 changes: 14 additions & 0 deletions packages/astro/src/core/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ export type SSRManifest = {
buildClientDir: URL;
buildServerDir: URL;
csp: SSRManifestCSP | undefined;
devToolbar: {
// This should always be false in prod/SSR
enabled: boolean;
/**
* Latest version of Astro, will be undefined if:
* - unable to check
* - the user has disabled the check
* - the check has not completed yet
* - the user is on the latest version already
*/
latestAstroVersion: string | undefined;

debugInfoOutput: string | undefined;
};
};

export type SSRActions = {
Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -744,5 +744,10 @@ async function createBuildManifest(
(settings.config.security?.checkOrigin && settings.buildOutput === 'server') ?? false,
key,
csp,
devToolbar: {
latestAstroVersion: settings.latestAstroVersion,
enabled: false,
debugInfoOutput: '',
},
};
}
5 changes: 5 additions & 0 deletions packages/astro/src/core/build/plugins/plugin-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,5 +372,10 @@ async function buildManifest(
key: encodedKey,
sessionConfig: settings.config.session,
csp,
devToolbar: {
enabled: false,
latestAstroVersion: settings.latestAstroVersion,
debugInfoOutput: '',
},
};
}
7 changes: 3 additions & 4 deletions packages/astro/src/core/compile/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { fileURLToPath } from 'node:url';
import type { TransformResult } from '@astrojs/compiler';
import { transform } from '@astrojs/compiler';
import type { ResolvedConfig } from 'vite';
import type { AstroPreferences } from '../../preferences/index.js';
import type { AstroConfig } from '../../types/public/config.js';
import type { AstroError } from '../errors/errors.js';
import { AggregateError, CompilerError } from '../errors/errors.js';
Expand All @@ -14,7 +13,7 @@ import type { CompileCssResult } from './types.js';
export interface CompileProps {
astroConfig: AstroConfig;
viteConfig: ResolvedConfig;
preferences: AstroPreferences;
toolbarEnabled: boolean;
filename: string;
source: string;
}
Expand All @@ -26,7 +25,7 @@ export interface CompileResult extends Omit<TransformResult, 'css'> {
export async function compile({
astroConfig,
viteConfig,
preferences,
toolbarEnabled,
filename,
source,
}: CompileProps): Promise<CompileResult> {
Expand Down Expand Up @@ -54,7 +53,7 @@ export async function compile({
viteConfig.command === 'serve' &&
astroConfig.devToolbar &&
astroConfig.devToolbar.enabled &&
(await preferences.get('devToolbar.enabled')),
toolbarEnabled,
renderScript: true,
preprocessStyle: createStylePreprocessor({
filename,
Expand Down
11 changes: 11 additions & 0 deletions packages/astro/src/manifest/serialized.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Plugin } from 'vite';
import { getInfoOutput } from '../cli/info/index.js';
import { toFallbackType } from '../core/app/common.js';
import { toRoutingStrategy } from '../core/app/index.js';
import type { SerializedSSRManifest, SSRManifestCSP, SSRManifestI18n } from '../core/app/types.js';
Expand Down Expand Up @@ -105,5 +106,15 @@ async function createSerializedManifest(settings: AstroSettings): Promise<Serial
sessionConfig: settings.config.session,
csp,
serverIslandNameMap: [],
devToolbar: {
enabled:
settings.config.devToolbar.enabled &&
(await settings.preferences.get('devToolbar.enabled')),
latestAstroVersion: settings.latestAstroVersion,
debugInfoOutput: await getInfoOutput({
userConfig: settings.config,
print: false,
}),
},
};
}
7 changes: 4 additions & 3 deletions packages/astro/src/preferences/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';

import dget from 'dlv';
import type { AstroConfig } from '../types/public/config.js';
import { DEFAULT_PREFERENCES, type Preferences, type PublicPreferences } from './defaults.js';
import { PreferenceStore } from './store.js';

Expand Down Expand Up @@ -82,7 +80,10 @@ export function coerce(key: string, value: unknown) {
return value as any;
}

export default function createPreferences(config: AstroConfig, dotAstroDir: URL): AstroPreferences {
export default function createPreferences(
config: Record<string, any>,
dotAstroDir: URL,
): AstroPreferences {
const global = new PreferenceStore(getGlobalPreferenceDir());
const project = new PreferenceStore(fileURLToPath(dotAstroDir));
const stores: Record<PreferenceLocation, PreferenceStore> = { global, project };
Expand Down
93 changes: 0 additions & 93 deletions packages/astro/src/vite-plugin-astro-server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,10 @@ import { IncomingMessage } from 'node:http';
import { fileURLToPath } from 'node:url';
import type * as vite from 'vite';
import { isRunnableDevEnvironment } from 'vite';
import { toFallbackType } from '../core/app/common.js';
import { toRoutingStrategy } from '../core/app/index.js';
import type { SSRManifest, SSRManifestCSP, SSRManifestI18n } from '../core/app/types.js';
import {
getAlgorithm,
getDirectives,
getScriptHashes,
getScriptResources,
getStrictDynamic,
getStyleHashes,
getStyleResources,
shouldTrackCspHashes,
} from '../core/csp/common.js';
import { createKey, getEnvironmentKey, hasEnvironmentKey } from '../core/encryption.js';
import { getViteErrorPayload } from '../core/errors/dev/index.js';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { patchOverlay } from '../core/errors/overlay.js';
import type { Logger } from '../core/logger/core.js';
import { NOOP_MIDDLEWARE_FN } from '../core/middleware/noop-middleware.js';
import { createViteLoader } from '../core/module-loader/index.js';
import type { AstroSettings } from '../types/astro.js';
import { baseMiddleware } from './base.js';
Expand Down Expand Up @@ -159,81 +144,3 @@ export default function createVitePluginAstroServer({
},
};
}

/**
* It creates a `SSRManifest` from the `AstroSettings`.
*
* Renderers needs to be pulled out from the page module emitted during the build.
* @param settings
*/
export function createDevelopmentManifest(settings: AstroSettings): SSRManifest {
let i18nManifest: SSRManifestI18n | undefined;
let csp: SSRManifestCSP | undefined;
if (settings.config.i18n) {
i18nManifest = {
fallback: settings.config.i18n.fallback,
strategy: toRoutingStrategy(settings.config.i18n.routing, settings.config.i18n.domains),
defaultLocale: settings.config.i18n.defaultLocale,
locales: settings.config.i18n.locales,
domainLookupTable: {},
fallbackType: toFallbackType(settings.config.i18n.routing),
domains: settings.config.i18n.domains,
};
}

if (shouldTrackCspHashes(settings.config.experimental.csp)) {
const styleHashes = [
...getStyleHashes(settings.config.experimental.csp),
...settings.injectedCsp.styleHashes,
];

csp = {
cspDestination: settings.adapter?.adapterFeatures?.experimentalStaticHeaders
? 'adapter'
: undefined,
scriptHashes: getScriptHashes(settings.config.experimental.csp),
scriptResources: getScriptResources(settings.config.experimental.csp),
styleHashes,
styleResources: getStyleResources(settings.config.experimental.csp),
algorithm: getAlgorithm(settings.config.experimental.csp),
directives: getDirectives(settings),
isStrictDynamic: getStrictDynamic(settings.config.experimental.csp),
};
}

return {
rootDir: settings.config.root,
srcDir: settings.config.srcDir,
cacheDir: settings.config.cacheDir,
outDir: settings.config.outDir,
buildServerDir: settings.config.build.server,
buildClientDir: settings.config.build.client,
publicDir: settings.config.publicDir,
trailingSlash: settings.config.trailingSlash,
buildFormat: settings.config.build.format,
compressHTML: settings.config.compressHTML,
assets: new Set(),
entryModules: {},
routes: [],
adapterName: settings?.adapter?.name ?? '',
clientDirectives: settings.clientDirectives,
renderers: [],
base: settings.config.base,
userAssetsBase: settings.config?.vite?.base,
assetsPrefix: settings.config.build.assetsPrefix,
site: settings.config.site,
componentMetadata: new Map(),
inlinedScripts: new Map(),
i18n: i18nManifest,
checkOrigin:
(settings.config.security?.checkOrigin && settings.buildOutput === 'server') ?? false,
key: hasEnvironmentKey() ? getEnvironmentKey() : createKey(),
middleware() {
return {
onRequest: NOOP_MIDDLEWARE_FN,
};
},
sessionConfig: settings.config.session,
csp,
};
}
5 changes: 3 additions & 2 deletions packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl
}
viteConfig.resolve.conditions.push('astro');
},
configResolved(viteConfig) {
async configResolved(viteConfig) {
const toolbarEnabled = await settings.preferences.get('devToolbar.enabled');
// Initialize `compile` function to simplify usage later
compile = (code, filename) => {
return compileAstro({
compileProps: {
astroConfig: config,
viteConfig,
preferences: settings.preferences,
toolbarEnabled,
filename,
source: code,
},
Expand Down
Loading