Skip to content

Commit

Permalink
[ci] format
Browse files Browse the repository at this point in the history
  • Loading branch information
lilnasy authored and astrobot-houston committed Feb 20, 2024
1 parent 5acc313 commit c1671df
Show file tree
Hide file tree
Showing 20 changed files with 429 additions and 206 deletions.
27 changes: 18 additions & 9 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import type {
ManifestData,
RouteData,
SSRManifest,
} from '../../@types/astro.js';
import type { ManifestData, RouteData, SSRManifest } from '../../@types/astro.js';
import type { SinglePageBuiltModule } from '../build/types.js';
import { getSetCookiesFromResponse } from '../cookies/index.js';
import { consoleLogDestination } from '../logger/console.js';
Expand All @@ -20,7 +16,13 @@ import { matchRoute } from '../routing/match.js';
import { AppPipeline } from './pipeline.js';
import { normalizeTheLocale } from '../../i18n/index.js';
import { RenderContext } from '../render-context.js';
import { clientAddressSymbol, clientLocalsSymbol, responseSentSymbol, REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER } from '../constants.js';
import {
clientAddressSymbol,
clientLocalsSymbol,
responseSentSymbol,
REROUTABLE_STATUS_CODES,
REROUTE_DIRECTIVE_HEADER,
} from '../constants.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
export { deserializeManifest } from './common.js';

Expand Down Expand Up @@ -124,7 +126,7 @@ export class App {
},
serverLike: true,
streaming,
})
});
}

set setManifestData(newManifestData: ManifestData) {
Expand Down Expand Up @@ -294,7 +296,14 @@ export class App {

let response;
try {
const renderContext = RenderContext.create({ pipeline: this.#pipeline, locals, pathname, request, routeData, status: defaultStatus })
const renderContext = RenderContext.create({
pipeline: this.#pipeline,
locals,
pathname,
request,
routeData,
status: defaultStatus,
});
response = await renderContext.render(await mod.page());
} catch (err: any) {
this.#logger.error(null, err.stack || err.message || String(err));
Expand Down Expand Up @@ -386,7 +395,7 @@ export class App {
request,
routeData: errorRouteData,
status,
})
});
const response = await renderContext.render(await mod.page());
return this.#mergeResponses(response, originalResponse);
} catch {
Expand Down
29 changes: 20 additions & 9 deletions packages/astro/src/core/app/pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import type { RouteData, SSRElement, SSRResult } from "../../@types/astro.js";
import { Pipeline } from "../base-pipeline.js";
import { createModuleScriptElement, createStylesheetElementSet } from "../render/ssr-element.js";
import type { RouteData, SSRElement, SSRResult } from '../../@types/astro.js';
import { Pipeline } from '../base-pipeline.js';
import { createModuleScriptElement, createStylesheetElementSet } from '../render/ssr-element.js';

export class AppPipeline extends Pipeline {
static create({ logger, manifest, mode, renderers, resolve, serverLike, streaming }: Pick<AppPipeline, 'logger' | 'manifest' | 'mode' | 'renderers' | 'resolve' | 'serverLike' | 'streaming'>) {
return new AppPipeline(logger, manifest, mode, renderers, resolve, serverLike, streaming);
}
static create({
logger,
manifest,
mode,
renderers,
resolve,
serverLike,
streaming,
}: Pick<
AppPipeline,
'logger' | 'manifest' | 'mode' | 'renderers' | 'resolve' | 'serverLike' | 'streaming'
>) {
return new AppPipeline(logger, manifest, mode, renderers, resolve, serverLike, streaming);
}

headElements(routeData: RouteData): Pick<SSRResult, 'scripts' | 'styles' | 'links'> {
const routeInfo = this.manifest.routes.find(route => route.routeData === routeData);
headElements(routeData: RouteData): Pick<SSRResult, 'scripts' | 'styles' | 'links'> {
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>();
const scripts = new Set<SSRElement>();
Expand All @@ -26,7 +37,7 @@ export class AppPipeline extends Pipeline {
scripts.add(createModuleScriptElement(script));
}
}
return { links, styles, scripts }
return { links, styles, scripts };
}

componentMetadata() {}
Expand Down
21 changes: 15 additions & 6 deletions packages/astro/src/core/base-pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import type { MiddlewareHandler, RouteData, RuntimeMode, SSRLoadedRenderer, SSRManifest, SSRResult } from '../@types/astro.js';
import type {
MiddlewareHandler,
RouteData,
RuntimeMode,
SSRLoadedRenderer,
SSRManifest,
SSRResult,
} from '../@types/astro.js';
import type { Logger } from './logger/core.js';
import { RouteCache } from './render/route-cache.js';
import { createI18nMiddleware } from '../i18n/middleware.js';

/**
* The `Pipeline` represents the static parts of rendering that do not change between requests.
* These are mostly known when the server first starts up and do not change.
*
*
* Thus, a `Pipeline` is created once at process start and then used by every `RenderContext`.
*/
export abstract class Pipeline {
Expand Down Expand Up @@ -38,13 +45,15 @@ export abstract class Pipeline {
/**
* Used for `Astro.site`.
*/
readonly site = manifest.site,
readonly site = manifest.site
) {
this.internalMiddleware = [ createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat) ];
this.internalMiddleware = [
createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat),
];
}

abstract headElements(routeData: RouteData): Promise<HeadElements> | HeadElements
abstract componentMetadata(routeData: RouteData): Promise<SSRResult['componentMetadata']> | void
abstract headElements(routeData: RouteData): Promise<HeadElements> | HeadElements;
abstract componentMetadata(routeData: RouteData): Promise<SSRResult['componentMetadata']> | void;
}

// eslint-disable-next-line @typescript-eslint/no-empty-interface
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ async function generatePath(
logger,
ssr: serverLike,
});
const renderContext = RenderContext.create({ pipeline, pathname, request, routeData: route })
const renderContext = RenderContext.create({ pipeline, pathname, request, routeData: route });

let body: string | Uint8Array;
let response: Response;
Expand Down
48 changes: 38 additions & 10 deletions packages/astro/src/core/build/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,17 @@ import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../vite-plugin-sc
import type { SSRManifest } from '../app/types.js';
import { routeIsFallback, routeIsRedirect } from '../redirects/helpers.js';
import { Pipeline } from '../render/index.js';
import { createAssetLink, createModuleScriptsSet, createStylesheetElementSet } from '../render/ssr-element.js';
import { getPageDataByComponent, type BuildInternals, cssOrder, mergeInlineCss } from './internal.js';
import {
createAssetLink,
createModuleScriptsSet,
createStylesheetElementSet,
} from '../render/ssr-element.js';
import {
getPageDataByComponent,
type BuildInternals,
cssOrder,
mergeInlineCss,
} from './internal.js';
import {
ASTRO_PAGE_RESOLVED_MODULE_ID,
getVirtualModulePageNameFromPath,
Expand Down Expand Up @@ -47,10 +56,22 @@ export class BuildPipeline extends Pipeline {
}
const serverLike = isServerLikeOutput(config);
const streaming = true;
super(options.logger, manifest, options.mode, manifest.renderers, resolve, serverLike, streaming)
super(
options.logger,
manifest,
options.mode,
manifest.renderers,
resolve,
serverLike,
streaming
);
}

static create({ internals, manifest, options }: Pick<BuildPipeline, 'internals' | 'manifest' | 'options'>) {
static create({
internals,
manifest,
options,
}: Pick<BuildPipeline, 'internals' | 'manifest' | 'options'>) {
return new BuildPipeline(internals, manifest, options);
}

Expand Down Expand Up @@ -106,17 +127,24 @@ export class BuildPipeline extends Pipeline {
}

headElements(routeData: RouteData): Pick<SSRResult, 'scripts' | 'styles' | 'links'> {
const { internals, manifest: { assetsPrefix, base }, settings } = this
const {
internals,
manifest: { assetsPrefix, base },
settings,
} = this;
const links = new Set<never>();
const pageBuildData = getPageDataByComponent(internals, routeData.component)
const pageBuildData = getPageDataByComponent(internals, routeData.component);
const scripts = createModuleScriptsSet(
pageBuildData?.hoistedScript ? [pageBuildData.hoistedScript] : [],
base,
assetsPrefix
);
const sortedCssAssets = pageBuildData?.styles.sort(cssOrder).map(({ sheet }) => sheet).reduce(mergeInlineCss, []);
const sortedCssAssets = pageBuildData?.styles
.sort(cssOrder)
.map(({ sheet }) => sheet)
.reduce(mergeInlineCss, []);
const styles = createStylesheetElementSet(sortedCssAssets ?? [], base, assetsPrefix);

if (settings.scripts.some((script) => script.stage === 'page')) {
const hashedFilePath = internals.entrySpecifierToBundleMap.get(PAGE_SCRIPT_ID);
if (typeof hashedFilePath !== 'string') {
Expand All @@ -128,7 +156,7 @@ export class BuildPipeline extends Pipeline {
children: '',
});
}

// Add all injected scripts to the page.
for (const script of settings.scripts) {
if (script.stage === 'head-inline') {
Expand All @@ -138,7 +166,7 @@ export class BuildPipeline extends Pipeline {
});
}
}
return { scripts, styles, links }
return { scripts, styles, links };
}

componentMetadata() {}
Expand Down
10 changes: 3 additions & 7 deletions packages/astro/src/core/endpoint/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import type {
APIContext,
Locales,
Params,
} from '../../@types/astro.js';
import type { APIContext, Locales, Params } from '../../@types/astro.js';
import { ASTRO_VERSION, clientAddressSymbol, clientLocalsSymbol } from '../constants.js';
import type { AstroCookies } from '../cookies/index.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
Expand All @@ -23,7 +19,7 @@ type CreateAPIContext = {
routingStrategy: RoutingStrategies | undefined;
defaultLocale: string | undefined;
route: string;
cookies: AstroCookies
cookies: AstroCookies;
};

/**
Expand All @@ -41,7 +37,7 @@ export function createAPIContext({
routingStrategy,
defaultLocale,
route,
cookies
cookies,
}: CreateAPIContext): APIContext {
let preferredLocale: string | undefined = undefined;
let preferredLocaleList: string[] | undefined = undefined;
Expand Down
19 changes: 14 additions & 5 deletions packages/astro/src/core/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,16 @@ export type CreateContext = {
/**
* Creates a context to be passed to Astro middleware `onRequest` function.
*/
function createContext({ request, params = {}, userDefinedLocales = [] }: CreateContext): APIContext {
function createContext({
request,
params = {},
userDefinedLocales = [],
}: CreateContext): APIContext {
let preferredLocale: string | undefined = undefined;
let preferredLocaleList: string[] | undefined = undefined;
let currentLocale: string | undefined = undefined;
const url = new URL(request.url);
const route = url.pathname
const route = url.pathname;

return {
cookies: new AstroCookies(request),
Expand All @@ -61,13 +65,18 @@ function createContext({ request, params = {}, userDefinedLocales = [] }: Create
});
},
get preferredLocale(): string | undefined {
return preferredLocale ??= computePreferredLocale(request, userDefinedLocales);
return (preferredLocale ??= computePreferredLocale(request, userDefinedLocales));
},
get preferredLocaleList(): string[] | undefined {
return preferredLocaleList ??= computePreferredLocaleList(request, userDefinedLocales);
return (preferredLocaleList ??= computePreferredLocaleList(request, userDefinedLocales));
},
get currentLocale(): string | undefined {
return currentLocale ??= computeCurrentLocale(route, userDefinedLocales, undefined, undefined);
return (currentLocale ??= computeCurrentLocale(
route,
userDefinedLocales,
undefined,
undefined
));
},
url,
get clientAddress() {
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/redirects/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@ export function routeIsRedirect(route: RouteData | undefined): route is Redirect
export function routeIsFallback(route: RouteData | undefined): route is RedirectRouteData {
return route?.type === 'fallback';
}

16 changes: 10 additions & 6 deletions packages/astro/src/core/redirects/render.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import type { RenderContext } from '../render-context.js';

export async function renderRedirect(renderContext: RenderContext) {
const { request: { method }, routeData } = renderContext;
const {
request: { method },
routeData,
} = renderContext;
const { redirect, redirectRoute } = routeData;
const status =
redirectRoute && typeof redirect === "object" ? redirect.status
: method === "GET" ? 301
: 308
const headers = { location: redirectRouteGenerate(renderContext) };
redirectRoute && typeof redirect === 'object' ? redirect.status : method === 'GET' ? 301 : 308;
const headers = { location: redirectRouteGenerate(renderContext) };
return new Response(null, { status, headers });
}

function redirectRouteGenerate(renderContext: RenderContext): string {
const { params, routeData: { redirect, redirectRoute } } = renderContext;
const {
params,
routeData: { redirect, redirectRoute },
} = renderContext;

if (typeof redirectRoute !== 'undefined') {
return redirectRoute?.generate(params) || redirectRoute?.pathname || '/';
Expand Down
Loading

0 comments on commit c1671df

Please sign in to comment.