🎉 initiate project *astro_rewrite*
This commit is contained in:
parent
ffd4d5e86c
commit
2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions
2
node_modules/astro/dist/core/app/common.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/core/app/common.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
import type { SerializedSSRManifest, SSRManifest } from './types';
|
||||
export declare function deserializeManifest(serializedManifest: SerializedSSRManifest): SSRManifest;
|
25
node_modules/astro/dist/core/app/common.js
generated
vendored
Normal file
25
node_modules/astro/dist/core/app/common.js
generated
vendored
Normal file
|
@ -0,0 +1,25 @@
|
|||
import { deserializeRouteData } from "../routing/manifest/serialization.js";
|
||||
function deserializeManifest(serializedManifest) {
|
||||
const routes = [];
|
||||
for (const serializedRoute of serializedManifest.routes) {
|
||||
routes.push({
|
||||
...serializedRoute,
|
||||
routeData: deserializeRouteData(serializedRoute.routeData)
|
||||
});
|
||||
const route = serializedRoute;
|
||||
route.routeData = deserializeRouteData(serializedRoute.routeData);
|
||||
}
|
||||
const assets = new Set(serializedManifest.assets);
|
||||
const componentMetadata = new Map(serializedManifest.componentMetadata);
|
||||
const clientDirectives = new Map(serializedManifest.clientDirectives);
|
||||
return {
|
||||
...serializedManifest,
|
||||
assets,
|
||||
componentMetadata,
|
||||
clientDirectives,
|
||||
routes
|
||||
};
|
||||
}
|
||||
export {
|
||||
deserializeManifest
|
||||
};
|
15
node_modules/astro/dist/core/app/index.d.ts
generated
vendored
Normal file
15
node_modules/astro/dist/core/app/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import type { ManifestData, RouteData, SSRManifest } from '../../@types/astro';
|
||||
export { deserializeManifest } from './common.js';
|
||||
export interface MatchOptions {
|
||||
matchNotFound?: boolean | undefined;
|
||||
}
|
||||
export declare class App {
|
||||
#private;
|
||||
constructor(manifest: SSRManifest, streaming?: boolean);
|
||||
set setManifest(newManifest: SSRManifest);
|
||||
set setManifestData(newManifestData: ManifestData);
|
||||
removeBase(pathname: string): string;
|
||||
match(request: Request, { matchNotFound }?: MatchOptions): RouteData | undefined;
|
||||
render(request: Request, routeData?: RouteData, locals?: object): Promise<Response>;
|
||||
setCookieHeaders(response: Response): Generator<string, string[], unknown>;
|
||||
}
|
275
node_modules/astro/dist/core/app/index.js
generated
vendored
Normal file
275
node_modules/astro/dist/core/app/index.js
generated
vendored
Normal file
|
@ -0,0 +1,275 @@
|
|||
import mime from "mime";
|
||||
import { attachToResponse, getSetCookiesFromResponse } from "../cookies/index.js";
|
||||
import { callEndpoint } from "../endpoint/index.js";
|
||||
import { consoleLogDestination } from "../logger/console.js";
|
||||
import { error } from "../logger/core.js";
|
||||
import { prependForwardSlash, removeTrailingForwardSlash } from "../path.js";
|
||||
import { RedirectSinglePageBuiltModule } from "../redirects/index.js";
|
||||
import {
|
||||
createEnvironment,
|
||||
createRenderContext,
|
||||
tryRenderPage
|
||||
} from "../render/index.js";
|
||||
import { RouteCache } from "../render/route-cache.js";
|
||||
import {
|
||||
createAssetLink,
|
||||
createModuleScriptElement,
|
||||
createStylesheetElementSet
|
||||
} from "../render/ssr-element.js";
|
||||
import { matchRoute } from "../routing/match.js";
|
||||
import { deserializeManifest } from "./common.js";
|
||||
const clientLocalsSymbol = Symbol.for("astro.locals");
|
||||
const responseSentSymbol = Symbol.for("astro.responseSent");
|
||||
class App {
|
||||
/**
|
||||
* The current environment of the application
|
||||
*/
|
||||
#env;
|
||||
#manifest;
|
||||
#manifestData;
|
||||
#routeDataToRouteInfo;
|
||||
#encoder = new TextEncoder();
|
||||
#logging = {
|
||||
dest: consoleLogDestination,
|
||||
level: "info"
|
||||
};
|
||||
#baseWithoutTrailingSlash;
|
||||
constructor(manifest, streaming = true) {
|
||||
this.#manifest = manifest;
|
||||
this.#manifestData = {
|
||||
routes: manifest.routes.map((route) => route.routeData)
|
||||
};
|
||||
this.#routeDataToRouteInfo = new Map(manifest.routes.map((route) => [route.routeData, route]));
|
||||
this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
|
||||
this.#env = this.#createEnvironment(streaming);
|
||||
}
|
||||
set setManifest(newManifest) {
|
||||
this.#manifest = newManifest;
|
||||
}
|
||||
/**
|
||||
* Creates an environment by reading the stored manifest
|
||||
*
|
||||
* @param streaming
|
||||
* @private
|
||||
*/
|
||||
#createEnvironment(streaming = false) {
|
||||
return createEnvironment({
|
||||
adapterName: this.#manifest.adapterName,
|
||||
logging: this.#logging,
|
||||
markdown: this.#manifest.markdown,
|
||||
mode: "production",
|
||||
compressHTML: this.#manifest.compressHTML,
|
||||
renderers: this.#manifest.renderers,
|
||||
clientDirectives: this.#manifest.clientDirectives,
|
||||
resolve: async (specifier) => {
|
||||
if (!(specifier in this.#manifest.entryModules)) {
|
||||
throw new Error(`Unable to resolve [${specifier}]`);
|
||||
}
|
||||
const bundlePath = this.#manifest.entryModules[specifier];
|
||||
switch (true) {
|
||||
case bundlePath.startsWith("data:"):
|
||||
case bundlePath.length === 0: {
|
||||
return bundlePath;
|
||||
}
|
||||
default: {
|
||||
return createAssetLink(bundlePath, this.#manifest.base, this.#manifest.assetsPrefix);
|
||||
}
|
||||
}
|
||||
},
|
||||
routeCache: new RouteCache(this.#logging),
|
||||
site: this.#manifest.site,
|
||||
ssr: true,
|
||||
streaming
|
||||
});
|
||||
}
|
||||
set setManifestData(newManifestData) {
|
||||
this.#manifestData = newManifestData;
|
||||
}
|
||||
removeBase(pathname) {
|
||||
if (pathname.startsWith(this.#manifest.base)) {
|
||||
return pathname.slice(this.#baseWithoutTrailingSlash.length + 1);
|
||||
}
|
||||
return pathname;
|
||||
}
|
||||
match(request, { matchNotFound = false } = {}) {
|
||||
const url = new URL(request.url);
|
||||
if (this.#manifest.assets.has(url.pathname)) {
|
||||
return void 0;
|
||||
}
|
||||
let pathname = prependForwardSlash(this.removeBase(url.pathname));
|
||||
let routeData = matchRoute(pathname, this.#manifestData);
|
||||
if (routeData) {
|
||||
if (routeData.prerender)
|
||||
return void 0;
|
||||
return routeData;
|
||||
} else if (matchNotFound) {
|
||||
const notFoundRouteData = matchRoute("/404", this.#manifestData);
|
||||
if (notFoundRouteData == null ? void 0 : notFoundRouteData.prerender)
|
||||
return void 0;
|
||||
return notFoundRouteData;
|
||||
} else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
async render(request, routeData, locals) {
|
||||
let defaultStatus = 200;
|
||||
if (!routeData) {
|
||||
routeData = this.match(request);
|
||||
if (!routeData) {
|
||||
defaultStatus = 404;
|
||||
routeData = this.match(request, { matchNotFound: true });
|
||||
}
|
||||
if (!routeData) {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
statusText: "Not found"
|
||||
});
|
||||
}
|
||||
}
|
||||
Reflect.set(request, clientLocalsSymbol, locals ?? {});
|
||||
if (routeData.route === "/404") {
|
||||
defaultStatus = 404;
|
||||
}
|
||||
let mod = await this.#getModuleForRoute(routeData);
|
||||
if (routeData.type === "page" || routeData.type === "redirect") {
|
||||
let response = await this.#renderPage(request, routeData, mod, defaultStatus);
|
||||
if (response.status === 500 || response.status === 404) {
|
||||
const errorRouteData = matchRoute("/" + response.status, this.#manifestData);
|
||||
if (errorRouteData && errorRouteData.route !== routeData.route) {
|
||||
mod = await this.#getModuleForRoute(errorRouteData);
|
||||
try {
|
||||
let errorResponse = await this.#renderPage(
|
||||
request,
|
||||
errorRouteData,
|
||||
mod,
|
||||
response.status
|
||||
);
|
||||
return errorResponse;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
return response;
|
||||
} else if (routeData.type === "endpoint") {
|
||||
return this.#callEndpoint(request, routeData, mod, defaultStatus);
|
||||
} else {
|
||||
throw new Error(`Unsupported route type [${routeData.type}].`);
|
||||
}
|
||||
}
|
||||
setCookieHeaders(response) {
|
||||
return getSetCookiesFromResponse(response);
|
||||
}
|
||||
async #getModuleForRoute(route) {
|
||||
if (route.type === "redirect") {
|
||||
return RedirectSinglePageBuiltModule;
|
||||
} else {
|
||||
if (this.#manifest.pageMap) {
|
||||
const importComponentInstance = this.#manifest.pageMap.get(route.component);
|
||||
if (!importComponentInstance) {
|
||||
throw new Error(
|
||||
`Unexpectedly unable to find a component instance for route ${route.route}`
|
||||
);
|
||||
}
|
||||
const pageModule = await importComponentInstance();
|
||||
return pageModule;
|
||||
} else if (this.#manifest.pageModule) {
|
||||
const importComponentInstance = this.#manifest.pageModule;
|
||||
return importComponentInstance;
|
||||
} else {
|
||||
throw new Error(
|
||||
"Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
async #renderPage(request, routeData, page, status = 200) {
|
||||
const url = new URL(request.url);
|
||||
const pathname = prependForwardSlash(this.removeBase(url.pathname));
|
||||
const info = this.#routeDataToRouteInfo.get(routeData);
|
||||
const links = /* @__PURE__ */ new Set();
|
||||
const styles = createStylesheetElementSet(info.styles);
|
||||
let scripts = /* @__PURE__ */ new Set();
|
||||
for (const script of info.scripts) {
|
||||
if ("stage" in script) {
|
||||
if (script.stage === "head-inline") {
|
||||
scripts.add({
|
||||
props: {},
|
||||
children: script.children
|
||||
});
|
||||
}
|
||||
} else {
|
||||
scripts.add(createModuleScriptElement(script));
|
||||
}
|
||||
}
|
||||
try {
|
||||
const mod = await page.page();
|
||||
const renderContext = await createRenderContext({
|
||||
request,
|
||||
pathname,
|
||||
componentMetadata: this.#manifest.componentMetadata,
|
||||
scripts,
|
||||
styles,
|
||||
links,
|
||||
route: routeData,
|
||||
status,
|
||||
mod,
|
||||
env: this.#env
|
||||
});
|
||||
const response = await tryRenderPage(renderContext, this.#env, mod, page.onRequest);
|
||||
Reflect.set(request, responseSentSymbol, true);
|
||||
return response;
|
||||
} catch (err) {
|
||||
error(this.#logging, "ssr", err.stack || err.message || String(err));
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
statusText: "Internal server error"
|
||||
});
|
||||
}
|
||||
}
|
||||
async #callEndpoint(request, routeData, page, status = 200) {
|
||||
const url = new URL(request.url);
|
||||
const pathname = "/" + this.removeBase(url.pathname);
|
||||
const mod = await page.page();
|
||||
const handler = mod;
|
||||
const ctx = await createRenderContext({
|
||||
request,
|
||||
pathname,
|
||||
route: routeData,
|
||||
status,
|
||||
env: this.#env,
|
||||
mod: handler
|
||||
});
|
||||
const result = await callEndpoint(handler, this.#env, ctx, page.onRequest);
|
||||
if (result.type === "response") {
|
||||
if (result.response.headers.get("X-Astro-Response") === "Not-Found") {
|
||||
const fourOhFourRequest = new Request(new URL("/404", request.url));
|
||||
const fourOhFourRouteData = this.match(fourOhFourRequest);
|
||||
if (fourOhFourRouteData) {
|
||||
return this.render(fourOhFourRequest, fourOhFourRouteData);
|
||||
}
|
||||
}
|
||||
return result.response;
|
||||
} else {
|
||||
const body = result.body;
|
||||
const headers = new Headers();
|
||||
const mimeType = mime.getType(url.pathname);
|
||||
if (mimeType) {
|
||||
headers.set("Content-Type", `${mimeType};charset=utf-8`);
|
||||
} else {
|
||||
headers.set("Content-Type", "text/plain;charset=utf-8");
|
||||
}
|
||||
const bytes = this.#encoder.encode(body);
|
||||
headers.set("Content-Length", bytes.byteLength.toString());
|
||||
const response = new Response(bytes, {
|
||||
status: 200,
|
||||
headers
|
||||
});
|
||||
attachToResponse(response, result.cookies);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
App,
|
||||
deserializeManifest
|
||||
};
|
18
node_modules/astro/dist/core/app/node.d.ts
generated
vendored
Normal file
18
node_modules/astro/dist/core/app/node.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,18 @@
|
|||
/// <reference types="node" />
|
||||
import type { RouteData } from '../../@types/astro';
|
||||
import type { SSRManifest } from './types';
|
||||
import { IncomingMessage } from 'node:http';
|
||||
import { App, type MatchOptions } from './index.js';
|
||||
declare class NodeIncomingMessage extends IncomingMessage {
|
||||
/**
|
||||
* The read-only body property of the Request interface contains a ReadableStream with the body contents that have been added to the request.
|
||||
*/
|
||||
body?: unknown;
|
||||
}
|
||||
export declare class NodeApp extends App {
|
||||
match(req: NodeIncomingMessage | Request, opts?: MatchOptions): RouteData | undefined;
|
||||
render(req: NodeIncomingMessage | Request, routeData?: RouteData, locals?: object): Promise<Response>;
|
||||
}
|
||||
export declare function loadManifest(rootFolder: URL): Promise<SSRManifest>;
|
||||
export declare function loadApp(rootFolder: URL): Promise<NodeApp>;
|
||||
export {};
|
88
node_modules/astro/dist/core/app/node.js
generated
vendored
Normal file
88
node_modules/astro/dist/core/app/node.js
generated
vendored
Normal file
|
@ -0,0 +1,88 @@
|
|||
import * as fs from "node:fs";
|
||||
import { IncomingMessage } from "node:http";
|
||||
import { TLSSocket } from "node:tls";
|
||||
import { deserializeManifest } from "./common.js";
|
||||
import { App } from "./index.js";
|
||||
const clientAddressSymbol = Symbol.for("astro.clientAddress");
|
||||
function createRequestFromNodeRequest(req, body) {
|
||||
var _a;
|
||||
const protocol = req.socket instanceof TLSSocket || req.headers["x-forwarded-proto"] === "https" ? "https" : "http";
|
||||
const hostname = req.headers.host || req.headers[":authority"];
|
||||
const url = `${protocol}://${hostname}${req.url}`;
|
||||
const rawHeaders = req.headers;
|
||||
const entries = Object.entries(rawHeaders);
|
||||
const method = req.method || "GET";
|
||||
const request = new Request(url, {
|
||||
method,
|
||||
headers: new Headers(entries),
|
||||
body: ["HEAD", "GET"].includes(method) ? null : body
|
||||
});
|
||||
if ((_a = req.socket) == null ? void 0 : _a.remoteAddress) {
|
||||
Reflect.set(request, clientAddressSymbol, req.socket.remoteAddress);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
class NodeIncomingMessage extends IncomingMessage {
|
||||
}
|
||||
class NodeApp extends App {
|
||||
match(req, opts = {}) {
|
||||
return super.match(req instanceof Request ? req : createRequestFromNodeRequest(req), opts);
|
||||
}
|
||||
render(req, routeData, locals) {
|
||||
if (typeof req.body === "string" && req.body.length > 0) {
|
||||
return super.render(
|
||||
req instanceof Request ? req : createRequestFromNodeRequest(req, Buffer.from(req.body)),
|
||||
routeData,
|
||||
locals
|
||||
);
|
||||
}
|
||||
if (typeof req.body === "object" && req.body !== null && Object.keys(req.body).length > 0) {
|
||||
return super.render(
|
||||
req instanceof Request ? req : createRequestFromNodeRequest(req, Buffer.from(JSON.stringify(req.body))),
|
||||
routeData,
|
||||
locals
|
||||
);
|
||||
}
|
||||
if ("on" in req) {
|
||||
let body = Buffer.from([]);
|
||||
let reqBodyComplete = new Promise((resolve, reject) => {
|
||||
req.on("data", (d) => {
|
||||
body = Buffer.concat([body, d]);
|
||||
});
|
||||
req.on("end", () => {
|
||||
resolve(body);
|
||||
});
|
||||
req.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
return reqBodyComplete.then(() => {
|
||||
return super.render(
|
||||
req instanceof Request ? req : createRequestFromNodeRequest(req, body),
|
||||
routeData,
|
||||
locals
|
||||
);
|
||||
});
|
||||
}
|
||||
return super.render(
|
||||
req instanceof Request ? req : createRequestFromNodeRequest(req),
|
||||
routeData,
|
||||
locals
|
||||
);
|
||||
}
|
||||
}
|
||||
async function loadManifest(rootFolder) {
|
||||
const manifestFile = new URL("./manifest.json", rootFolder);
|
||||
const rawManifest = await fs.promises.readFile(manifestFile, "utf-8");
|
||||
const serializedManifest = JSON.parse(rawManifest);
|
||||
return deserializeManifest(serializedManifest);
|
||||
}
|
||||
async function loadApp(rootFolder) {
|
||||
const manifest = await loadManifest(rootFolder);
|
||||
return new NodeApp(manifest);
|
||||
}
|
||||
export {
|
||||
NodeApp,
|
||||
loadApp,
|
||||
loadManifest
|
||||
};
|
54
node_modules/astro/dist/core/app/types.d.ts
generated
vendored
Normal file
54
node_modules/astro/dist/core/app/types.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,54 @@
|
|||
import type { MarkdownRenderingOptions } from '@astrojs/markdown-remark';
|
||||
import type { RouteData, SerializedRouteData, SSRComponentMetadata, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
|
||||
import type { SinglePageBuiltModule } from '../build/types';
|
||||
export type ComponentPath = string;
|
||||
export type StylesheetAsset = {
|
||||
type: 'inline';
|
||||
content: string;
|
||||
} | {
|
||||
type: 'external';
|
||||
src: string;
|
||||
};
|
||||
export interface RouteInfo {
|
||||
routeData: RouteData;
|
||||
file: string;
|
||||
links: string[];
|
||||
scripts: ({
|
||||
children: string;
|
||||
stage: string;
|
||||
} | {
|
||||
type: 'inline' | 'external';
|
||||
value: string;
|
||||
})[];
|
||||
styles: StylesheetAsset[];
|
||||
}
|
||||
export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
|
||||
routeData: SerializedRouteData;
|
||||
};
|
||||
export type ImportComponentInstance = () => Promise<SinglePageBuiltModule>;
|
||||
export type SSRManifest = {
|
||||
adapterName: string;
|
||||
routes: RouteInfo[];
|
||||
site?: string;
|
||||
base: string;
|
||||
compressHTML: boolean;
|
||||
assetsPrefix?: string;
|
||||
markdown: MarkdownRenderingOptions;
|
||||
renderers: SSRLoadedRenderer[];
|
||||
/**
|
||||
* Map of directive name (e.g. `load`) to the directive script code
|
||||
*/
|
||||
clientDirectives: Map<string, string>;
|
||||
entryModules: Record<string, string>;
|
||||
assets: Set<string>;
|
||||
componentMetadata: SSRResult['componentMetadata'];
|
||||
pageModule?: SinglePageBuiltModule;
|
||||
pageMap?: Map<ComponentPath, ImportComponentInstance>;
|
||||
};
|
||||
export type SerializedSSRManifest = Omit<SSRManifest, 'routes' | 'assets' | 'componentMetadata' | 'clientDirectives'> & {
|
||||
routes: SerializedRouteInfo[];
|
||||
assets: string[];
|
||||
componentMetadata: [string, SSRComponentMetadata][];
|
||||
clientDirectives: [string, string][];
|
||||
};
|
||||
export type AdapterCreateExports<T = any> = (manifest: SSRManifest, args?: T) => Record<string, any>;
|
0
node_modules/astro/dist/core/app/types.js
generated
vendored
Normal file
0
node_modules/astro/dist/core/app/types.js
generated
vendored
Normal file
2
node_modules/astro/dist/core/build/add-rollup-input.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/core/build/add-rollup-input.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
import type { Rollup } from 'vite';
|
||||
export declare function addRollupInput(inputOptions: Rollup.InputOptions, newInputs: string[]): Rollup.InputOptions;
|
37
node_modules/astro/dist/core/build/add-rollup-input.js
generated
vendored
Normal file
37
node_modules/astro/dist/core/build/add-rollup-input.js
generated
vendored
Normal file
|
@ -0,0 +1,37 @@
|
|||
function fromEntries(entries) {
|
||||
const obj = {};
|
||||
for (const [k, v] of entries) {
|
||||
obj[k] = v;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
function addRollupInput(inputOptions, newInputs) {
|
||||
if (!inputOptions.input) {
|
||||
return { ...inputOptions, input: newInputs };
|
||||
}
|
||||
if (typeof inputOptions.input === "string") {
|
||||
return {
|
||||
...inputOptions,
|
||||
input: [inputOptions.input, ...newInputs]
|
||||
};
|
||||
}
|
||||
if (Array.isArray(inputOptions.input)) {
|
||||
return {
|
||||
...inputOptions,
|
||||
input: [...inputOptions.input, ...newInputs]
|
||||
};
|
||||
}
|
||||
if (typeof inputOptions.input === "object") {
|
||||
return {
|
||||
...inputOptions,
|
||||
input: {
|
||||
...inputOptions.input,
|
||||
...fromEntries(newInputs.map((i) => [i.split("/").slice(-1)[0].split(".")[0], i]))
|
||||
}
|
||||
};
|
||||
}
|
||||
throw new Error(`Unknown rollup input type. Supported inputs are string, array and object.`);
|
||||
}
|
||||
export {
|
||||
addRollupInput
|
||||
};
|
9
node_modules/astro/dist/core/build/common.d.ts
generated
vendored
Normal file
9
node_modules/astro/dist/core/build/common.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
import type { AstroConfig, RouteType } from '../../@types/astro';
|
||||
export declare function getOutFolder(astroConfig: AstroConfig, pathname: string, routeType: RouteType): URL;
|
||||
export declare function getOutFile(astroConfig: AstroConfig, outFolder: URL, pathname: string, routeType: RouteType): URL;
|
||||
/**
|
||||
* Ensures the `outDir` is within `process.cwd()`. If not it will fallback to `<cwd>/.astro`.
|
||||
* This is used for static `ssrBuild` so the output can access node_modules when we import
|
||||
* the output files. A hardcoded fallback dir is fine as it would be cleaned up after build.
|
||||
*/
|
||||
export declare function getOutDirWithinCwd(outDir: URL): URL;
|
66
node_modules/astro/dist/core/build/common.js
generated
vendored
Normal file
66
node_modules/astro/dist/core/build/common.js
generated
vendored
Normal file
|
@ -0,0 +1,66 @@
|
|||
import npath from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { appendForwardSlash } from "../../core/path.js";
|
||||
const STATUS_CODE_PAGES = /* @__PURE__ */ new Set(["/404", "/500"]);
|
||||
const FALLBACK_OUT_DIR_NAME = "./.astro/";
|
||||
function getOutRoot(astroConfig) {
|
||||
if (astroConfig.output === "static") {
|
||||
return new URL("./", astroConfig.outDir);
|
||||
} else {
|
||||
return new URL("./", astroConfig.build.client);
|
||||
}
|
||||
}
|
||||
function getOutFolder(astroConfig, pathname, routeType) {
|
||||
const outRoot = getOutRoot(astroConfig);
|
||||
switch (routeType) {
|
||||
case "endpoint":
|
||||
return new URL("." + appendForwardSlash(npath.dirname(pathname)), outRoot);
|
||||
case "page":
|
||||
case "redirect":
|
||||
switch (astroConfig.build.format) {
|
||||
case "directory": {
|
||||
if (STATUS_CODE_PAGES.has(pathname)) {
|
||||
return new URL("." + appendForwardSlash(npath.dirname(pathname)), outRoot);
|
||||
}
|
||||
return new URL("." + appendForwardSlash(pathname), outRoot);
|
||||
}
|
||||
case "file": {
|
||||
const d = pathname === "" ? pathname : npath.dirname(pathname);
|
||||
return new URL("." + appendForwardSlash(d), outRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function getOutFile(astroConfig, outFolder, pathname, routeType) {
|
||||
switch (routeType) {
|
||||
case "endpoint":
|
||||
return new URL(npath.basename(pathname), outFolder);
|
||||
case "page":
|
||||
case "redirect":
|
||||
switch (astroConfig.build.format) {
|
||||
case "directory": {
|
||||
if (STATUS_CODE_PAGES.has(pathname)) {
|
||||
const baseName = npath.basename(pathname);
|
||||
return new URL("./" + (baseName || "index") + ".html", outFolder);
|
||||
}
|
||||
return new URL("./index.html", outFolder);
|
||||
}
|
||||
case "file": {
|
||||
const baseName = npath.basename(pathname);
|
||||
return new URL("./" + (baseName || "index") + ".html", outFolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function getOutDirWithinCwd(outDir) {
|
||||
if (fileURLToPath(outDir).startsWith(process.cwd())) {
|
||||
return outDir;
|
||||
} else {
|
||||
return new URL(FALLBACK_OUT_DIR_NAME, pathToFileURL(process.cwd() + npath.sep));
|
||||
}
|
||||
}
|
||||
export {
|
||||
getOutDirWithinCwd,
|
||||
getOutFile,
|
||||
getOutFolder
|
||||
};
|
8
node_modules/astro/dist/core/build/css-asset-name.d.ts
generated
vendored
Normal file
8
node_modules/astro/dist/core/build/css-asset-name.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
import type { GetModuleInfo } from 'rollup';
|
||||
import type { AstroSettings } from '../../@types/astro';
|
||||
export declare function shortHashedName(id: string, ctx: {
|
||||
getModuleInfo: GetModuleInfo;
|
||||
}): string;
|
||||
export declare function createSlugger(settings: AstroSettings): (id: string, ctx: {
|
||||
getModuleInfo: GetModuleInfo;
|
||||
}) => string;
|
62
node_modules/astro/dist/core/build/css-asset-name.js
generated
vendored
Normal file
62
node_modules/astro/dist/core/build/css-asset-name.js
generated
vendored
Normal file
|
@ -0,0 +1,62 @@
|
|||
import crypto from "node:crypto";
|
||||
import npath from "node:path";
|
||||
import { viteID } from "../util.js";
|
||||
import { getTopLevelPages } from "./graph.js";
|
||||
function shortHashedName(id, ctx) {
|
||||
var _a;
|
||||
const parents = Array.from(getTopLevelPages(id, ctx));
|
||||
const firstParentId = (_a = parents[0]) == null ? void 0 : _a[0].id;
|
||||
const firstParentName = firstParentId ? npath.parse(firstParentId).name : "index";
|
||||
const hash = crypto.createHash("sha256");
|
||||
for (const [page] of parents) {
|
||||
hash.update(page.id, "utf-8");
|
||||
}
|
||||
const h = hash.digest("hex").slice(0, 8);
|
||||
const proposedName = firstParentName + "." + h;
|
||||
return proposedName;
|
||||
}
|
||||
function createSlugger(settings) {
|
||||
const pagesDir = viteID(new URL("./pages", settings.config.srcDir));
|
||||
const indexPage = viteID(new URL("./pages/index", settings.config.srcDir));
|
||||
const map = /* @__PURE__ */ new Map();
|
||||
const sep = "-";
|
||||
return function(id, ctx) {
|
||||
var _a;
|
||||
const parents = Array.from(getTopLevelPages(id, ctx));
|
||||
const allParentsKey = parents.map(([page]) => page.id).sort().join("-");
|
||||
const firstParentId = ((_a = parents[0]) == null ? void 0 : _a[0].id) || indexPage;
|
||||
let dir = firstParentId;
|
||||
let key = "";
|
||||
let i = 0;
|
||||
while (i < 2) {
|
||||
if (dir === pagesDir) {
|
||||
break;
|
||||
}
|
||||
const name2 = npath.parse(npath.basename(dir)).name;
|
||||
key = key.length ? name2 + sep + key : name2;
|
||||
dir = npath.dirname(dir);
|
||||
i++;
|
||||
}
|
||||
let name = key;
|
||||
if (!map.has(key)) {
|
||||
map.set(key, /* @__PURE__ */ new Map([[allParentsKey, 0]]));
|
||||
} else {
|
||||
const inner = map.get(key);
|
||||
if (inner.has(allParentsKey)) {
|
||||
const num = inner.get(allParentsKey);
|
||||
if (num > 0) {
|
||||
name = name + sep + num;
|
||||
}
|
||||
} else {
|
||||
const num = inner.size;
|
||||
inner.set(allParentsKey, num);
|
||||
name = name + sep + num;
|
||||
}
|
||||
}
|
||||
return name;
|
||||
};
|
||||
}
|
||||
export {
|
||||
createSlugger,
|
||||
shortHashedName
|
||||
};
|
15
node_modules/astro/dist/core/build/generate.d.ts
generated
vendored
Normal file
15
node_modules/astro/dist/core/build/generate.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import type { OutputAsset, OutputChunk } from 'rollup';
|
||||
import type { AstroSettings, SSRLoadedRenderer, SSRManifest } from '../../@types/astro';
|
||||
import { type BuildInternals } from '../../core/build/internal.js';
|
||||
import type { StaticBuildOptions } from './types';
|
||||
export declare function rootRelativeFacadeId(facadeId: string, settings: AstroSettings): string;
|
||||
export declare function chunkIsPage(settings: AstroSettings, output: OutputAsset | OutputChunk, internals: BuildInternals): boolean;
|
||||
export declare function generatePages(opts: StaticBuildOptions, internals: BuildInternals): Promise<void>;
|
||||
/**
|
||||
* It creates a `SSRManifest` from the `AstroSettings`.
|
||||
*
|
||||
* Renderers needs to be pulled out from the page module emitted during the build.
|
||||
* @param settings
|
||||
* @param renderers
|
||||
*/
|
||||
export declare function createBuildManifest(settings: AstroSettings, internals: BuildInternals, renderers: SSRLoadedRenderer[]): SSRManifest;
|
481
node_modules/astro/dist/core/build/generate.js
generated
vendored
Normal file
481
node_modules/astro/dist/core/build/generate.js
generated
vendored
Normal file
|
@ -0,0 +1,481 @@
|
|||
import * as colors from "kleur/colors";
|
||||
import { bgGreen, black, cyan, dim, green, magenta } from "kleur/colors";
|
||||
import fs from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
generateImage as generateImageInternal,
|
||||
getStaticImageList
|
||||
} from "../../assets/generate.js";
|
||||
import {
|
||||
eachPageDataFromEntryPoint,
|
||||
eachRedirectPageData,
|
||||
hasPrerenderedPages
|
||||
} from "../../core/build/internal.js";
|
||||
import {
|
||||
isRelativePath,
|
||||
prependForwardSlash,
|
||||
removeLeadingForwardSlash,
|
||||
removeTrailingForwardSlash
|
||||
} from "../../core/path.js";
|
||||
import { runHookBuildGenerated } from "../../integrations/index.js";
|
||||
import { isServerLikeOutput } from "../../prerender/utils.js";
|
||||
import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from "../../vite-plugin-scripts/index.js";
|
||||
import { callEndpoint, throwIfRedirectNotAllowed } from "../endpoint/index.js";
|
||||
import { AstroError, AstroErrorData } from "../errors/index.js";
|
||||
import { debug, info } from "../logger/core.js";
|
||||
import {
|
||||
getRedirectLocationOrThrow,
|
||||
RedirectSinglePageBuiltModule,
|
||||
routeIsRedirect
|
||||
} from "../redirects/index.js";
|
||||
import { createEnvironment, createRenderContext, tryRenderPage } from "../render/index.js";
|
||||
import { callGetStaticPaths } from "../render/route-cache.js";
|
||||
import {
|
||||
createAssetLink,
|
||||
createModuleScriptsSet,
|
||||
createStylesheetElementSet
|
||||
} from "../render/ssr-element.js";
|
||||
import { createRequest } from "../request.js";
|
||||
import { matchRoute } from "../routing/match.js";
|
||||
import { getOutputFilename } from "../util.js";
|
||||
import { getOutDirWithinCwd, getOutFile, getOutFolder } from "./common.js";
|
||||
import {
|
||||
cssOrder,
|
||||
getEntryFilePathFromComponentPath,
|
||||
getPageDataByComponent,
|
||||
mergeInlineCss
|
||||
} from "./internal.js";
|
||||
import { getTimeStat } from "./util.js";
|
||||
function createEntryURL(filePath, outFolder) {
|
||||
return new URL("./" + filePath + `?time=${Date.now()}`, outFolder);
|
||||
}
|
||||
async function getEntryForRedirectRoute(route, internals, outFolder) {
|
||||
if (route.type !== "redirect") {
|
||||
throw new Error(`Expected a redirect route.`);
|
||||
}
|
||||
if (route.redirectRoute) {
|
||||
const filePath = getEntryFilePathFromComponentPath(internals, route.redirectRoute.component);
|
||||
if (filePath) {
|
||||
const url = createEntryURL(filePath, outFolder);
|
||||
const ssrEntryPage = await import(url.toString());
|
||||
return ssrEntryPage;
|
||||
}
|
||||
}
|
||||
return RedirectSinglePageBuiltModule;
|
||||
}
|
||||
function shouldSkipDraft(pageModule, settings) {
|
||||
var _a;
|
||||
return (
|
||||
// Drafts are disabled
|
||||
!settings.config.markdown.drafts && // This is a draft post
|
||||
"frontmatter" in pageModule && ((_a = pageModule.frontmatter) == null ? void 0 : _a.draft) === true
|
||||
);
|
||||
}
|
||||
function rootRelativeFacadeId(facadeId, settings) {
|
||||
return facadeId.slice(fileURLToPath(settings.config.root).length);
|
||||
}
|
||||
function chunkIsPage(settings, output, internals) {
|
||||
if (output.type !== "chunk") {
|
||||
return false;
|
||||
}
|
||||
const chunk = output;
|
||||
if (chunk.facadeModuleId) {
|
||||
const facadeToEntryId = prependForwardSlash(
|
||||
rootRelativeFacadeId(chunk.facadeModuleId, settings)
|
||||
);
|
||||
return internals.entrySpecifierToBundleMap.has(facadeToEntryId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async function generatePages(opts, internals) {
|
||||
const timer = performance.now();
|
||||
const ssr = isServerLikeOutput(opts.settings.config);
|
||||
const outFolder = ssr ? opts.settings.config.build.server : getOutDirWithinCwd(opts.settings.config.outDir);
|
||||
if (ssr && !hasPrerenderedPages(internals))
|
||||
return;
|
||||
const verb = ssr ? "prerendering" : "generating";
|
||||
info(opts.logging, null, `
|
||||
${bgGreen(black(` ${verb} static routes `))}`);
|
||||
const builtPaths = /* @__PURE__ */ new Set();
|
||||
if (ssr) {
|
||||
for (const [pageData, filePath] of eachPageDataFromEntryPoint(internals)) {
|
||||
if (pageData.route.prerender) {
|
||||
const ssrEntryURLPage = createEntryURL(filePath, outFolder);
|
||||
const ssrEntryPage = await import(ssrEntryURLPage.toString());
|
||||
if (opts.settings.config.build.split) {
|
||||
const manifest = ssrEntryPage.manifest;
|
||||
const ssrEntry = manifest == null ? void 0 : manifest.pageModule;
|
||||
if (ssrEntry) {
|
||||
await generatePage(opts, internals, pageData, ssrEntry, builtPaths, manifest);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unable to find the manifest for the module ${ssrEntryURLPage.toString()}. This is unexpected and likely a bug in Astro, please report.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const ssrEntry = ssrEntryPage;
|
||||
const manifest = createBuildManifest(opts.settings, internals, ssrEntry.renderers);
|
||||
await generatePage(opts, internals, pageData, ssrEntry, builtPaths, manifest);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const pageData of eachRedirectPageData(internals)) {
|
||||
const entry = await getEntryForRedirectRoute(pageData.route, internals, outFolder);
|
||||
const manifest = createBuildManifest(opts.settings, internals, entry.renderers);
|
||||
await generatePage(opts, internals, pageData, entry, builtPaths, manifest);
|
||||
}
|
||||
} else {
|
||||
for (const [pageData, filePath] of eachPageDataFromEntryPoint(internals)) {
|
||||
const ssrEntryURLPage = createEntryURL(filePath, outFolder);
|
||||
const entry = await import(ssrEntryURLPage.toString());
|
||||
const manifest = createBuildManifest(opts.settings, internals, entry.renderers);
|
||||
await generatePage(opts, internals, pageData, entry, builtPaths, manifest);
|
||||
}
|
||||
for (const pageData of eachRedirectPageData(internals)) {
|
||||
const entry = await getEntryForRedirectRoute(pageData.route, internals, outFolder);
|
||||
const manifest = createBuildManifest(opts.settings, internals, entry.renderers);
|
||||
await generatePage(opts, internals, pageData, entry, builtPaths, manifest);
|
||||
}
|
||||
}
|
||||
if (opts.settings.config.experimental.assets) {
|
||||
info(opts.logging, null, `
|
||||
${bgGreen(black(` generating optimized images `))}`);
|
||||
for (const imageData of getStaticImageList()) {
|
||||
await generateImage(opts, imageData[1].options, imageData[1].path);
|
||||
}
|
||||
delete globalThis.astroAsset.addStaticImage;
|
||||
}
|
||||
await runHookBuildGenerated({
|
||||
config: opts.settings.config,
|
||||
logging: opts.logging
|
||||
});
|
||||
info(opts.logging, null, dim(`Completed in ${getTimeStat(timer, performance.now())}.
|
||||
`));
|
||||
}
|
||||
async function generateImage(opts, transform, path) {
|
||||
let timeStart = performance.now();
|
||||
const generationData = await generateImageInternal(opts, transform, path);
|
||||
if (!generationData) {
|
||||
return;
|
||||
}
|
||||
const timeEnd = performance.now();
|
||||
const timeChange = getTimeStat(timeStart, timeEnd);
|
||||
const timeIncrease = `(+${timeChange})`;
|
||||
const statsText = generationData.cached ? `(reused cache entry)` : `(before: ${generationData.weight.before}kb, after: ${generationData.weight.after}kb)`;
|
||||
info(opts.logging, null, ` ${green("\u25B6")} ${path} ${dim(statsText)} ${dim(timeIncrease)}`);
|
||||
}
|
||||
async function generatePage(opts, internals, pageData, ssrEntry, builtPaths, manifest) {
|
||||
if (routeIsRedirect(pageData.route) && !opts.settings.config.experimental.redirects) {
|
||||
throw new Error(`To use redirects first set experimental.redirects to \`true\``);
|
||||
}
|
||||
let timeStart = performance.now();
|
||||
const pageInfo = getPageDataByComponent(internals, pageData.route.component);
|
||||
const linkIds = [];
|
||||
const scripts = (pageInfo == null ? void 0 : pageInfo.hoistedScript) ?? null;
|
||||
const styles = pageData.styles.sort(cssOrder).map(({ sheet }) => sheet).reduce(mergeInlineCss, []);
|
||||
const pageModulePromise = ssrEntry.page;
|
||||
const onRequest = ssrEntry.onRequest;
|
||||
if (!pageModulePromise) {
|
||||
throw new Error(
|
||||
`Unable to find the module for ${pageData.component}. This is unexpected and likely a bug in Astro, please report.`
|
||||
);
|
||||
}
|
||||
const pageModule = await pageModulePromise();
|
||||
if (shouldSkipDraft(pageModule, opts.settings)) {
|
||||
info(opts.logging, null, `${magenta("\u26A0\uFE0F")} Skipping draft ${pageData.route.component}`);
|
||||
return;
|
||||
}
|
||||
const generationOptions = {
|
||||
pageData,
|
||||
internals,
|
||||
linkIds,
|
||||
scripts,
|
||||
styles,
|
||||
mod: pageModule
|
||||
};
|
||||
const icon = pageData.route.type === "page" ? green("\u25B6") : magenta("\u03BB");
|
||||
if (isRelativePath(pageData.route.component)) {
|
||||
info(opts.logging, null, `${icon} ${pageData.route.route}`);
|
||||
} else {
|
||||
info(opts.logging, null, `${icon} ${pageData.route.component}`);
|
||||
}
|
||||
const paths = await getPathsForRoute(pageData, pageModule, opts, builtPaths);
|
||||
for (let i = 0; i < paths.length; i++) {
|
||||
const path = paths[i];
|
||||
await generatePath(path, opts, generationOptions, manifest, onRequest);
|
||||
const timeEnd = performance.now();
|
||||
const timeChange = getTimeStat(timeStart, timeEnd);
|
||||
const timeIncrease = `(+${timeChange})`;
|
||||
const filePath = getOutputFilename(opts.settings.config, path, pageData.route.type);
|
||||
const lineIcon = i === paths.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
|
||||
info(opts.logging, null, ` ${cyan(lineIcon)} ${dim(filePath)} ${dim(timeIncrease)}`);
|
||||
}
|
||||
}
|
||||
async function getPathsForRoute(pageData, mod, opts, builtPaths) {
|
||||
let paths = [];
|
||||
if (pageData.route.pathname) {
|
||||
paths.push(pageData.route.pathname);
|
||||
builtPaths.add(pageData.route.pathname);
|
||||
} else {
|
||||
const route = pageData.route;
|
||||
const staticPaths = await callGetStaticPaths({
|
||||
mod,
|
||||
route,
|
||||
routeCache: opts.routeCache,
|
||||
isValidate: false,
|
||||
logging: opts.logging,
|
||||
ssr: isServerLikeOutput(opts.settings.config)
|
||||
}).catch((err) => {
|
||||
debug("build", `\u251C\u2500\u2500 ${colors.bold(colors.red("\u2717"))} ${route.component}`);
|
||||
throw err;
|
||||
});
|
||||
const label = staticPaths.length === 1 ? "page" : "pages";
|
||||
debug(
|
||||
"build",
|
||||
`\u251C\u2500\u2500 ${colors.bold(colors.green("\u2714"))} ${route.component} \u2192 ${colors.magenta(
|
||||
`[${staticPaths.length} ${label}]`
|
||||
)}`
|
||||
);
|
||||
paths = staticPaths.map((staticPath) => {
|
||||
try {
|
||||
return route.generate(staticPath.params);
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError) {
|
||||
throw getInvalidRouteSegmentError(e, route, staticPath);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}).filter((staticPath) => {
|
||||
if (!builtPaths.has(removeTrailingForwardSlash(staticPath))) {
|
||||
return true;
|
||||
}
|
||||
const matchedRoute = matchRoute(staticPath, opts.manifest);
|
||||
return matchedRoute === route;
|
||||
});
|
||||
for (const staticPath of paths) {
|
||||
builtPaths.add(removeTrailingForwardSlash(staticPath));
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
function getInvalidRouteSegmentError(e, route, staticPath) {
|
||||
var _a, _b;
|
||||
const invalidParam = (_a = e.message.match(/^Expected "([^"]+)"/)) == null ? void 0 : _a[1];
|
||||
const received = invalidParam ? staticPath.params[invalidParam] : void 0;
|
||||
let hint = "Learn about dynamic routes at https://docs.astro.build/en/core-concepts/routing/#dynamic-routes";
|
||||
if (invalidParam && typeof received === "string") {
|
||||
const matchingSegment = (_b = route.segments.find(
|
||||
(segment) => {
|
||||
var _a2;
|
||||
return ((_a2 = segment[0]) == null ? void 0 : _a2.content) === invalidParam;
|
||||
}
|
||||
)) == null ? void 0 : _b[0];
|
||||
const mightBeMissingSpread = (matchingSegment == null ? void 0 : matchingSegment.dynamic) && !(matchingSegment == null ? void 0 : matchingSegment.spread);
|
||||
if (mightBeMissingSpread) {
|
||||
hint = `If the param contains slashes, try using a rest parameter: **[...${invalidParam}]**. Learn more at https://docs.astro.build/en/core-concepts/routing/#dynamic-routes`;
|
||||
}
|
||||
}
|
||||
return new AstroError({
|
||||
...AstroErrorData.InvalidDynamicRoute,
|
||||
message: invalidParam ? AstroErrorData.InvalidDynamicRoute.message(
|
||||
route.route,
|
||||
JSON.stringify(invalidParam),
|
||||
JSON.stringify(received)
|
||||
) : `Generated path for ${route.route} is invalid.`,
|
||||
hint
|
||||
});
|
||||
}
|
||||
function shouldAppendForwardSlash(trailingSlash, buildFormat) {
|
||||
switch (trailingSlash) {
|
||||
case "always":
|
||||
return true;
|
||||
case "never":
|
||||
return false;
|
||||
case "ignore": {
|
||||
switch (buildFormat) {
|
||||
case "directory":
|
||||
return true;
|
||||
case "file":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function addPageName(pathname, opts) {
|
||||
const trailingSlash = opts.settings.config.trailingSlash;
|
||||
const buildFormat = opts.settings.config.build.format;
|
||||
const pageName = shouldAppendForwardSlash(trailingSlash, buildFormat) ? pathname.replace(/\/?$/, "/").replace(/^\//, "") : pathname.replace(/^\//, "");
|
||||
opts.pageNames.push(pageName);
|
||||
}
|
||||
function getUrlForPath(pathname, base, origin, format, routeType) {
|
||||
const ending = format === "directory" ? "/" : ".html";
|
||||
let buildPathname;
|
||||
if (pathname === "/" || pathname === "") {
|
||||
buildPathname = base;
|
||||
} else if (routeType === "endpoint") {
|
||||
const buildPathRelative = removeLeadingForwardSlash(pathname);
|
||||
buildPathname = base + buildPathRelative;
|
||||
} else {
|
||||
const buildPathRelative = removeTrailingForwardSlash(removeLeadingForwardSlash(pathname)) + ending;
|
||||
buildPathname = base + buildPathRelative;
|
||||
}
|
||||
const url = new URL(buildPathname, origin);
|
||||
return url;
|
||||
}
|
||||
async function generatePath(pathname, opts, gopts, manifest, onRequest) {
|
||||
const { settings, logging, origin, routeCache } = opts;
|
||||
const { mod, internals, scripts: hoistedScripts, styles: _styles, pageData } = gopts;
|
||||
if (pageData.route.type === "page") {
|
||||
addPageName(pathname, opts);
|
||||
}
|
||||
debug("build", `Generating: ${pathname}`);
|
||||
const links = /* @__PURE__ */ new Set();
|
||||
const scripts = createModuleScriptsSet(
|
||||
hoistedScripts ? [hoistedScripts] : [],
|
||||
manifest.base,
|
||||
manifest.assetsPrefix
|
||||
);
|
||||
const styles = createStylesheetElementSet(_styles, manifest.base, manifest.assetsPrefix);
|
||||
if (settings.scripts.some((script) => script.stage === "page")) {
|
||||
const hashedFilePath = internals.entrySpecifierToBundleMap.get(PAGE_SCRIPT_ID);
|
||||
if (typeof hashedFilePath !== "string") {
|
||||
throw new Error(`Cannot find the built path for ${PAGE_SCRIPT_ID}`);
|
||||
}
|
||||
const src = createAssetLink(hashedFilePath, manifest.base, manifest.assetsPrefix);
|
||||
scripts.add({
|
||||
props: { type: "module", src },
|
||||
children: ""
|
||||
});
|
||||
}
|
||||
for (const script of settings.scripts) {
|
||||
if (script.stage === "head-inline") {
|
||||
scripts.add({
|
||||
props: {},
|
||||
children: script.content
|
||||
});
|
||||
}
|
||||
}
|
||||
const ssr = isServerLikeOutput(settings.config);
|
||||
const url = getUrlForPath(
|
||||
pathname,
|
||||
opts.settings.config.base,
|
||||
origin,
|
||||
opts.settings.config.build.format,
|
||||
pageData.route.type
|
||||
);
|
||||
const env = createEnvironment({
|
||||
adapterName: manifest.adapterName,
|
||||
logging,
|
||||
markdown: manifest.markdown,
|
||||
mode: opts.mode,
|
||||
renderers: manifest.renderers,
|
||||
clientDirectives: manifest.clientDirectives,
|
||||
compressHTML: manifest.compressHTML,
|
||||
async resolve(specifier) {
|
||||
const hashedFilePath = manifest.entryModules[specifier];
|
||||
if (typeof hashedFilePath !== "string") {
|
||||
if (specifier === BEFORE_HYDRATION_SCRIPT_ID) {
|
||||
return "";
|
||||
}
|
||||
throw new Error(`Cannot find the built path for ${specifier}`);
|
||||
}
|
||||
return createAssetLink(hashedFilePath, manifest.base, manifest.assetsPrefix);
|
||||
},
|
||||
routeCache,
|
||||
site: manifest.site,
|
||||
ssr,
|
||||
streaming: true
|
||||
});
|
||||
const renderContext = await createRenderContext({
|
||||
pathname,
|
||||
request: createRequest({ url, headers: new Headers(), logging, ssr }),
|
||||
componentMetadata: manifest.componentMetadata,
|
||||
scripts,
|
||||
styles,
|
||||
links,
|
||||
route: pageData.route,
|
||||
env,
|
||||
mod
|
||||
});
|
||||
let body;
|
||||
let encoding;
|
||||
if (pageData.route.type === "endpoint") {
|
||||
const endpointHandler = mod;
|
||||
const result = await callEndpoint(
|
||||
endpointHandler,
|
||||
env,
|
||||
renderContext,
|
||||
onRequest
|
||||
);
|
||||
if (result.type === "response") {
|
||||
throwIfRedirectNotAllowed(result.response, opts.settings.config);
|
||||
if (!result.response.body)
|
||||
return;
|
||||
const ab = await result.response.arrayBuffer();
|
||||
body = new Uint8Array(ab);
|
||||
} else {
|
||||
body = result.body;
|
||||
encoding = result.encoding;
|
||||
}
|
||||
} else {
|
||||
let response;
|
||||
try {
|
||||
response = await tryRenderPage(renderContext, env, mod, onRequest);
|
||||
} catch (err) {
|
||||
if (!AstroError.is(err) && !err.id && typeof err === "object") {
|
||||
err.id = pageData.component;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
if (!opts.settings.config.build.redirects) {
|
||||
return;
|
||||
}
|
||||
const location = getRedirectLocationOrThrow(response.headers);
|
||||
const fromPath = new URL(renderContext.request.url).pathname;
|
||||
const delay = response.status === 302 ? 2 : 0;
|
||||
body = `<!doctype html>
|
||||
<title>Redirecting to: ${location}</title>
|
||||
<meta http-equiv="refresh" content="${delay};url=${location}">
|
||||
<meta name="robots" content="noindex">
|
||||
<link rel="canonical" href="${location}">
|
||||
<body>
|
||||
<a href="${location}">Redirecting from <code>${fromPath}</code> to <code>${location}</code></a>
|
||||
</body>`;
|
||||
if (pageData.route.type !== "redirect") {
|
||||
pageData.route.redirect = location;
|
||||
}
|
||||
} else {
|
||||
if (!response.body)
|
||||
return;
|
||||
body = await response.text();
|
||||
}
|
||||
}
|
||||
const outFolder = getOutFolder(settings.config, pathname, pageData.route.type);
|
||||
const outFile = getOutFile(settings.config, outFolder, pathname, pageData.route.type);
|
||||
pageData.route.distURL = outFile;
|
||||
await fs.promises.mkdir(outFolder, { recursive: true });
|
||||
await fs.promises.writeFile(outFile, body, encoding ?? "utf-8");
|
||||
}
|
||||
function createBuildManifest(settings, internals, renderers) {
|
||||
return {
|
||||
assets: /* @__PURE__ */ new Set(),
|
||||
entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries()),
|
||||
routes: [],
|
||||
adapterName: "",
|
||||
markdown: settings.config.markdown,
|
||||
clientDirectives: settings.clientDirectives,
|
||||
compressHTML: settings.config.compressHTML,
|
||||
renderers,
|
||||
base: settings.config.base,
|
||||
assetsPrefix: settings.config.build.assetsPrefix,
|
||||
site: settings.config.site ? new URL(settings.config.base, settings.config.site).toString() : settings.config.site,
|
||||
componentMetadata: internals.componentMetadata
|
||||
};
|
||||
}
|
||||
export {
|
||||
chunkIsPage,
|
||||
createBuildManifest,
|
||||
generatePages,
|
||||
rootRelativeFacadeId
|
||||
};
|
8
node_modules/astro/dist/core/build/graph.d.ts
generated
vendored
Normal file
8
node_modules/astro/dist/core/build/graph.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
import type { GetModuleInfo, ModuleInfo } from 'rollup';
|
||||
export declare function walkParentInfos(id: string, ctx: {
|
||||
getModuleInfo: GetModuleInfo;
|
||||
}, until?: (importer: string) => boolean, depth?: number, order?: number, seen?: Set<string>, childId?: string): Generator<[ModuleInfo, number, number], void, unknown>;
|
||||
export declare function moduleIsTopLevelPage(info: ModuleInfo): boolean;
|
||||
export declare function getTopLevelPages(id: string, ctx: {
|
||||
getModuleInfo: GetModuleInfo;
|
||||
}): Generator<[ModuleInfo, number, number], void, unknown>;
|
42
node_modules/astro/dist/core/build/graph.js
generated
vendored
Normal file
42
node_modules/astro/dist/core/build/graph.js
generated
vendored
Normal file
|
@ -0,0 +1,42 @@
|
|||
import { ASTRO_PAGE_RESOLVED_MODULE_ID } from "./plugins/plugin-pages.js";
|
||||
function* walkParentInfos(id, ctx, until, depth = 0, order = 0, seen = /* @__PURE__ */ new Set(), childId = "") {
|
||||
seen.add(id);
|
||||
const info = ctx.getModuleInfo(id);
|
||||
if (info) {
|
||||
if (childId) {
|
||||
const idx = info.importedIds.indexOf(childId);
|
||||
if (idx === -1) {
|
||||
order += info.importedIds.length;
|
||||
order += info.dynamicallyImportedIds.indexOf(childId);
|
||||
} else {
|
||||
order += idx;
|
||||
}
|
||||
}
|
||||
yield [info, depth, order];
|
||||
}
|
||||
if (until == null ? void 0 : until(id))
|
||||
return;
|
||||
const importers = ((info == null ? void 0 : info.importers) || []).concat((info == null ? void 0 : info.dynamicImporters) || []);
|
||||
for (const imp of importers) {
|
||||
if (seen.has(imp)) {
|
||||
continue;
|
||||
}
|
||||
yield* walkParentInfos(imp, ctx, until, ++depth, order, seen, id);
|
||||
}
|
||||
}
|
||||
function moduleIsTopLevelPage(info) {
|
||||
var _a, _b;
|
||||
return ((_a = info.importers[0]) == null ? void 0 : _a.includes(ASTRO_PAGE_RESOLVED_MODULE_ID)) || ((_b = info.dynamicImporters[0]) == null ? void 0 : _b.includes(ASTRO_PAGE_RESOLVED_MODULE_ID));
|
||||
}
|
||||
function* getTopLevelPages(id, ctx) {
|
||||
for (const res of walkParentInfos(id, ctx)) {
|
||||
if (moduleIsTopLevelPage(res[0])) {
|
||||
yield res;
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
getTopLevelPages,
|
||||
moduleIsTopLevelPage,
|
||||
walkParentInfos
|
||||
};
|
15
node_modules/astro/dist/core/build/index.d.ts
generated
vendored
Normal file
15
node_modules/astro/dist/core/build/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import type yargs from 'yargs-parser';
|
||||
import type { AstroSettings, RuntimeMode } from '../../@types/astro';
|
||||
import { type LogOptions } from '../logger/core.js';
|
||||
export interface BuildOptions {
|
||||
mode?: RuntimeMode;
|
||||
logging: LogOptions;
|
||||
/**
|
||||
* Teardown the compiler WASM instance after build. This can improve performance when
|
||||
* building once, but may cause a performance hit if building multiple times in a row.
|
||||
*/
|
||||
teardownCompiler?: boolean;
|
||||
flags?: yargs.Arguments;
|
||||
}
|
||||
/** `astro build` */
|
||||
export default function build(settings: AstroSettings, options: BuildOptions): Promise<void>;
|
207
node_modules/astro/dist/core/build/index.js
generated
vendored
Normal file
207
node_modules/astro/dist/core/build/index.js
generated
vendored
Normal file
|
@ -0,0 +1,207 @@
|
|||
import * as colors from "kleur/colors";
|
||||
import fs from "node:fs";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import {
|
||||
runHookBuildDone,
|
||||
runHookBuildStart,
|
||||
runHookConfigDone,
|
||||
runHookConfigSetup
|
||||
} from "../../integrations/index.js";
|
||||
import { createVite } from "../create-vite.js";
|
||||
import { debug, info, levels, timerMessage, warn } from "../logger/core.js";
|
||||
import { printHelp } from "../messages.js";
|
||||
import { apply as applyPolyfill } from "../polyfill.js";
|
||||
import { RouteCache } from "../render/route-cache.js";
|
||||
import { createRouteManifest } from "../routing/index.js";
|
||||
import { collectPagesData } from "./page-data.js";
|
||||
import { staticBuild, viteBuild } from "./static-build.js";
|
||||
import { getTimeStat } from "./util.js";
|
||||
async function build(settings, options) {
|
||||
var _a, _b;
|
||||
applyPolyfill();
|
||||
if (((_a = options.flags) == null ? void 0 : _a.help) || ((_b = options.flags) == null ? void 0 : _b.h)) {
|
||||
printHelp({
|
||||
commandName: "astro build",
|
||||
usage: "[...flags]",
|
||||
tables: {
|
||||
Flags: [
|
||||
["--drafts", `Include Markdown draft pages in the build.`],
|
||||
["--help (-h)", "See all available flags."]
|
||||
]
|
||||
},
|
||||
description: `Builds your site for deployment.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
const builder = new AstroBuilder(settings, options);
|
||||
await builder.run();
|
||||
}
|
||||
class AstroBuilder {
|
||||
constructor(settings, options) {
|
||||
this.mode = "production";
|
||||
if (options.mode) {
|
||||
this.mode = options.mode;
|
||||
}
|
||||
this.settings = settings;
|
||||
this.logging = options.logging;
|
||||
this.teardownCompiler = options.teardownCompiler ?? false;
|
||||
this.routeCache = new RouteCache(this.logging);
|
||||
this.origin = settings.config.site ? new URL(settings.config.site).origin : `http://localhost:${settings.config.server.port}`;
|
||||
this.manifest = { routes: [] };
|
||||
this.timer = {};
|
||||
}
|
||||
/** Setup Vite and run any async setup logic that couldn't run inside of the constructor. */
|
||||
async setup() {
|
||||
debug("build", "Initial setup...");
|
||||
const { logging } = this;
|
||||
this.timer.init = performance.now();
|
||||
this.settings = await runHookConfigSetup({
|
||||
settings: this.settings,
|
||||
command: "build",
|
||||
logging
|
||||
});
|
||||
this.manifest = createRouteManifest({ settings: this.settings }, this.logging);
|
||||
const viteConfig = await createVite(
|
||||
{
|
||||
mode: this.mode,
|
||||
server: {
|
||||
hmr: false,
|
||||
middlewareMode: true
|
||||
}
|
||||
},
|
||||
{ settings: this.settings, logging, mode: "build", command: "build" }
|
||||
);
|
||||
await runHookConfigDone({ settings: this.settings, logging });
|
||||
const { sync } = await import("../sync/index.js");
|
||||
const syncRet = await sync(this.settings, { logging, fs });
|
||||
if (syncRet !== 0) {
|
||||
return process.exit(syncRet);
|
||||
}
|
||||
return { viteConfig };
|
||||
}
|
||||
/** Run the build logic. build() is marked private because usage should go through ".run()" */
|
||||
async build({ viteConfig }) {
|
||||
await runHookBuildStart({ config: this.settings.config, logging: this.logging });
|
||||
this.validateConfig();
|
||||
info(this.logging, "build", `output target: ${colors.green(this.settings.config.output)}`);
|
||||
if (this.settings.adapter) {
|
||||
info(this.logging, "build", `deploy adapter: ${colors.green(this.settings.adapter.name)}`);
|
||||
}
|
||||
info(this.logging, "build", "Collecting build info...");
|
||||
this.timer.loadStart = performance.now();
|
||||
const { assets, allPages } = await collectPagesData({
|
||||
settings: this.settings,
|
||||
logging: this.logging,
|
||||
manifest: this.manifest
|
||||
});
|
||||
debug("build", timerMessage("All pages loaded", this.timer.loadStart));
|
||||
const pageNames = [];
|
||||
this.timer.buildStart = performance.now();
|
||||
info(
|
||||
this.logging,
|
||||
"build",
|
||||
colors.dim(`Completed in ${getTimeStat(this.timer.init, performance.now())}.`)
|
||||
);
|
||||
const opts = {
|
||||
allPages,
|
||||
settings: this.settings,
|
||||
logging: this.logging,
|
||||
manifest: this.manifest,
|
||||
mode: this.mode,
|
||||
origin: this.origin,
|
||||
pageNames,
|
||||
routeCache: this.routeCache,
|
||||
teardownCompiler: this.teardownCompiler,
|
||||
viteConfig
|
||||
};
|
||||
const { internals } = await viteBuild(opts);
|
||||
await staticBuild(opts, internals);
|
||||
this.timer.assetsStart = performance.now();
|
||||
Object.keys(assets).map((k) => {
|
||||
if (!assets[k])
|
||||
return;
|
||||
const filePath = new URL(`file://${k}`);
|
||||
fs.mkdirSync(new URL("./", filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, assets[k], "utf8");
|
||||
delete assets[k];
|
||||
});
|
||||
debug("build", timerMessage("Additional assets copied", this.timer.assetsStart));
|
||||
await runHookBuildDone({
|
||||
config: this.settings.config,
|
||||
pages: pageNames,
|
||||
routes: Object.values(allPages).map((pd) => pd.route),
|
||||
logging: this.logging
|
||||
});
|
||||
if (this.logging.level && levels[this.logging.level] <= levels["info"]) {
|
||||
await this.printStats({
|
||||
logging: this.logging,
|
||||
timeStart: this.timer.init,
|
||||
pageCount: pageNames.length,
|
||||
buildMode: this.settings.config.output
|
||||
});
|
||||
}
|
||||
this.settings.timer.writeStats();
|
||||
}
|
||||
/** Build the given Astro project. */
|
||||
async run() {
|
||||
const setupData = await this.setup();
|
||||
try {
|
||||
await this.build(setupData);
|
||||
} catch (_err) {
|
||||
throw _err;
|
||||
}
|
||||
}
|
||||
validateConfig() {
|
||||
const { config } = this.settings;
|
||||
if (config.outDir.toString() === config.root.toString()) {
|
||||
throw new Error(
|
||||
`the outDir cannot be the root folder. Please build to a folder such as dist.`
|
||||
);
|
||||
}
|
||||
if (config.build.split === true) {
|
||||
if (config.output === "static") {
|
||||
warn(
|
||||
this.logging,
|
||||
"configuration",
|
||||
'The option `build.split` won\'t take effect, because `output` is not `"server"` or `"hybrid"`.'
|
||||
);
|
||||
}
|
||||
}
|
||||
if (config.build.excludeMiddleware === true) {
|
||||
if (config.output === "static") {
|
||||
warn(
|
||||
this.logging,
|
||||
"configuration",
|
||||
'The option `build.excludeMiddleware` won\'t take effect, because `output` is not `"server"` or `"hybrid"`.'
|
||||
);
|
||||
}
|
||||
}
|
||||
if (config.build.split === true) {
|
||||
if (config.output !== "server") {
|
||||
throw new Error(
|
||||
'The option `build.split` can only be used when `output` is set to `"server"`.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Stats */
|
||||
async printStats({
|
||||
logging,
|
||||
timeStart,
|
||||
pageCount,
|
||||
buildMode
|
||||
}) {
|
||||
const total = getTimeStat(timeStart, performance.now());
|
||||
let messages = [];
|
||||
if (buildMode === "static") {
|
||||
messages = [`${pageCount} page(s) built in`, colors.bold(total)];
|
||||
} else {
|
||||
messages = ["Server built in", colors.bold(total)];
|
||||
}
|
||||
info(logging, "build", messages.join(" "));
|
||||
info(logging, "build", `${colors.bold("Complete!")}`);
|
||||
}
|
||||
}
|
||||
export {
|
||||
build as default
|
||||
};
|
103
node_modules/astro/dist/core/build/internal.d.ts
generated
vendored
Normal file
103
node_modules/astro/dist/core/build/internal.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,103 @@
|
|||
import type { Rollup } from 'vite';
|
||||
import type { RouteData, SSRResult } from '../../@types/astro';
|
||||
import type { PageOptions } from '../../vite-plugin-astro/types';
|
||||
import type { PageBuildData, StylesheetAsset, ViteID } from './types';
|
||||
export interface BuildInternals {
|
||||
/**
|
||||
* Each CSS module is named with a chunk id derived from the Astro pages they
|
||||
* are used in by default. It's easy to crawl this relation in the SSR build as
|
||||
* the Astro pages are the entrypoint, but not for the client build as hydratable
|
||||
* components are the entrypoint instead. This map is used as a cache from the SSR
|
||||
* build so the client can pick up the same information and use the same chunk ids.
|
||||
*/
|
||||
cssModuleToChunkIdMap: Map<string, string>;
|
||||
hoistedScriptIdToHoistedMap: Map<string, Set<string>>;
|
||||
hoistedScriptIdToPagesMap: Map<string, Set<string>>;
|
||||
entrySpecifierToBundleMap: Map<string, string>;
|
||||
/**
|
||||
* A map to get a specific page's bundled output file.
|
||||
*/
|
||||
pageToBundleMap: Map<string, string>;
|
||||
/**
|
||||
* A map for page-specific information.
|
||||
*/
|
||||
pagesByComponent: Map<string, PageBuildData>;
|
||||
/**
|
||||
* A map for page-specific output.
|
||||
*/
|
||||
pageOptionsByPage: Map<string, PageOptions>;
|
||||
/**
|
||||
* A map for page-specific information by Vite ID (a path-like string)
|
||||
*/
|
||||
pagesByViteID: Map<ViteID, PageBuildData>;
|
||||
/**
|
||||
* A map for page-specific information by a client:only component
|
||||
*/
|
||||
pagesByClientOnly: Map<string, Set<PageBuildData>>;
|
||||
/**
|
||||
* A map of hydrated components to export names that are discovered during the SSR build.
|
||||
* These will be used as the top-level entrypoints for the client build.
|
||||
*
|
||||
* @example
|
||||
* '/project/Component1.jsx' => ['default']
|
||||
* '/project/Component2.jsx' => ['Counter', 'Timer']
|
||||
* '/project/Component3.jsx' => ['*']
|
||||
*/
|
||||
discoveredHydratedComponents: Map<string, string[]>;
|
||||
/**
|
||||
* A list of client:only components to export names that are discovered during the SSR build.
|
||||
* These will be used as the top-level entrypoints for the client build.
|
||||
*
|
||||
* @example
|
||||
* '/project/Component1.jsx' => ['default']
|
||||
* '/project/Component2.jsx' => ['Counter', 'Timer']
|
||||
* '/project/Component3.jsx' => ['*']
|
||||
*/
|
||||
discoveredClientOnlyComponents: Map<string, string[]>;
|
||||
/**
|
||||
* A list of hoisted scripts that are discovered during the SSR build
|
||||
* These will be used as the top-level entrypoints for the client build.
|
||||
*/
|
||||
discoveredScripts: Set<string>;
|
||||
staticFiles: Set<string>;
|
||||
ssrEntryChunk?: Rollup.OutputChunk;
|
||||
entryPoints: Map<RouteData, URL>;
|
||||
ssrSplitEntryChunks: Map<string, Rollup.OutputChunk>;
|
||||
componentMetadata: SSRResult['componentMetadata'];
|
||||
middlewareEntryPoint?: URL;
|
||||
}
|
||||
/**
|
||||
* Creates internal maps used to coordinate the CSS and HTML plugins.
|
||||
* @returns {BuildInternals}
|
||||
*/
|
||||
export declare function createBuildInternals(): BuildInternals;
|
||||
export declare function trackPageData(internals: BuildInternals, component: string, pageData: PageBuildData, componentModuleId: string, componentURL: URL): void;
|
||||
/**
|
||||
* Tracks client-only components to the pages they are associated with.
|
||||
*/
|
||||
export declare function trackClientOnlyPageDatas(internals: BuildInternals, pageData: PageBuildData, clientOnlys: string[]): void;
|
||||
export declare function getPageDatasByChunk(internals: BuildInternals, chunk: Rollup.RenderedChunk): Generator<PageBuildData, void, unknown>;
|
||||
export declare function getPageDatasByClientOnlyID(internals: BuildInternals, viteid: ViteID): Generator<PageBuildData, void, unknown>;
|
||||
export declare function getPageDataByComponent(internals: BuildInternals, component: string): PageBuildData | undefined;
|
||||
export declare function getPageDataByViteID(internals: BuildInternals, viteid: ViteID): PageBuildData | undefined;
|
||||
export declare function hasPageDataByViteID(internals: BuildInternals, viteid: ViteID): boolean;
|
||||
export declare function eachPageData(internals: BuildInternals): Generator<PageBuildData, void, undefined>;
|
||||
export declare function eachRedirectPageData(internals: BuildInternals): Generator<PageBuildData, void, unknown>;
|
||||
export declare function eachPageDataFromEntryPoint(internals: BuildInternals): Generator<[PageBuildData, string]>;
|
||||
export declare function hasPrerenderedPages(internals: BuildInternals): boolean;
|
||||
interface OrderInfo {
|
||||
depth: number;
|
||||
order: number;
|
||||
}
|
||||
/**
|
||||
* Sort a page's CSS by depth. A higher depth means that the CSS comes from shared subcomponents.
|
||||
* A lower depth means it comes directly from the top-level page.
|
||||
* Can be used to sort stylesheets so that shared rules come first
|
||||
* and page-specific rules come after.
|
||||
*/
|
||||
export declare function cssOrder(a: OrderInfo, b: OrderInfo): 1 | -1;
|
||||
export declare function mergeInlineCss(acc: Array<StylesheetAsset>, current: StylesheetAsset): Array<StylesheetAsset>;
|
||||
export declare function isHoistedScript(internals: BuildInternals, id: string): boolean;
|
||||
export declare function getPageDatasByHoistedScriptId(internals: BuildInternals, id: string): Generator<PageBuildData, void, unknown>;
|
||||
export declare function getEntryFilePathFromComponentPath(internals: BuildInternals, path: string): string | undefined;
|
||||
export {};
|
192
node_modules/astro/dist/core/build/internal.js
generated
vendored
Normal file
192
node_modules/astro/dist/core/build/internal.js
generated
vendored
Normal file
|
@ -0,0 +1,192 @@
|
|||
import { prependForwardSlash, removeFileExtension } from "../path.js";
|
||||
import { viteID } from "../util.js";
|
||||
import {
|
||||
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
||||
getVirtualModulePageIdFromPath
|
||||
} from "./plugins/plugin-pages.js";
|
||||
import { RESOLVED_SPLIT_MODULE_ID } from "./plugins/plugin-ssr.js";
|
||||
import { ASTRO_PAGE_EXTENSION_POST_PATTERN } from "./plugins/util.js";
|
||||
function createBuildInternals() {
|
||||
const hoistedScriptIdToHoistedMap = /* @__PURE__ */ new Map();
|
||||
const hoistedScriptIdToPagesMap = /* @__PURE__ */ new Map();
|
||||
return {
|
||||
cssModuleToChunkIdMap: /* @__PURE__ */ new Map(),
|
||||
hoistedScriptIdToHoistedMap,
|
||||
hoistedScriptIdToPagesMap,
|
||||
entrySpecifierToBundleMap: /* @__PURE__ */ new Map(),
|
||||
pageToBundleMap: /* @__PURE__ */ new Map(),
|
||||
pagesByComponent: /* @__PURE__ */ new Map(),
|
||||
pageOptionsByPage: /* @__PURE__ */ new Map(),
|
||||
pagesByViteID: /* @__PURE__ */ new Map(),
|
||||
pagesByClientOnly: /* @__PURE__ */ new Map(),
|
||||
discoveredHydratedComponents: /* @__PURE__ */ new Map(),
|
||||
discoveredClientOnlyComponents: /* @__PURE__ */ new Map(),
|
||||
discoveredScripts: /* @__PURE__ */ new Set(),
|
||||
staticFiles: /* @__PURE__ */ new Set(),
|
||||
componentMetadata: /* @__PURE__ */ new Map(),
|
||||
ssrSplitEntryChunks: /* @__PURE__ */ new Map(),
|
||||
entryPoints: /* @__PURE__ */ new Map()
|
||||
};
|
||||
}
|
||||
function trackPageData(internals, component, pageData, componentModuleId, componentURL) {
|
||||
pageData.moduleSpecifier = componentModuleId;
|
||||
internals.pagesByComponent.set(component, pageData);
|
||||
internals.pagesByViteID.set(viteID(componentURL), pageData);
|
||||
}
|
||||
function trackClientOnlyPageDatas(internals, pageData, clientOnlys) {
|
||||
for (const clientOnlyComponent of clientOnlys) {
|
||||
let pageDataSet;
|
||||
if (internals.pagesByClientOnly.has(clientOnlyComponent)) {
|
||||
pageDataSet = internals.pagesByClientOnly.get(clientOnlyComponent);
|
||||
} else {
|
||||
pageDataSet = /* @__PURE__ */ new Set();
|
||||
internals.pagesByClientOnly.set(clientOnlyComponent, pageDataSet);
|
||||
}
|
||||
pageDataSet.add(pageData);
|
||||
}
|
||||
}
|
||||
function* getPageDatasByChunk(internals, chunk) {
|
||||
const pagesByViteID = internals.pagesByViteID;
|
||||
for (const [modulePath] of Object.entries(chunk.modules)) {
|
||||
if (pagesByViteID.has(modulePath)) {
|
||||
yield pagesByViteID.get(modulePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
function* getPageDatasByClientOnlyID(internals, viteid) {
|
||||
const pagesByClientOnly = internals.pagesByClientOnly;
|
||||
if (pagesByClientOnly.size) {
|
||||
let pageBuildDatas = pagesByClientOnly.get(viteid);
|
||||
if (!pageBuildDatas) {
|
||||
let pathname = `/@fs${prependForwardSlash(viteid)}`;
|
||||
pageBuildDatas = pagesByClientOnly.get(pathname);
|
||||
}
|
||||
if (!pageBuildDatas) {
|
||||
let pathname = `/@fs${prependForwardSlash(removeFileExtension(viteid))}`;
|
||||
pageBuildDatas = pagesByClientOnly.get(pathname);
|
||||
}
|
||||
if (pageBuildDatas) {
|
||||
for (const pageData of pageBuildDatas) {
|
||||
yield pageData;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function getPageDataByComponent(internals, component) {
|
||||
if (internals.pagesByComponent.has(component)) {
|
||||
return internals.pagesByComponent.get(component);
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
function getPageDataByViteID(internals, viteid) {
|
||||
if (internals.pagesByViteID.has(viteid)) {
|
||||
return internals.pagesByViteID.get(viteid);
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
function hasPageDataByViteID(internals, viteid) {
|
||||
return internals.pagesByViteID.has(viteid);
|
||||
}
|
||||
function* eachPageData(internals) {
|
||||
yield* internals.pagesByComponent.values();
|
||||
}
|
||||
function* eachRedirectPageData(internals) {
|
||||
for (const pageData of eachPageData(internals)) {
|
||||
if (pageData.route.type === "redirect") {
|
||||
yield pageData;
|
||||
}
|
||||
}
|
||||
}
|
||||
function* eachPageDataFromEntryPoint(internals) {
|
||||
for (const [entryPoint, filePath] of internals.entrySpecifierToBundleMap) {
|
||||
if (entryPoint.includes(ASTRO_PAGE_RESOLVED_MODULE_ID) || entryPoint.includes(RESOLVED_SPLIT_MODULE_ID)) {
|
||||
const [, pageName] = entryPoint.split(":");
|
||||
const pageData = internals.pagesByComponent.get(
|
||||
`${pageName.replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".")}`
|
||||
);
|
||||
if (!pageData) {
|
||||
throw new Error(
|
||||
"Build failed. Astro couldn't find the emitted page from " + pageName + " pattern"
|
||||
);
|
||||
}
|
||||
yield [pageData, filePath];
|
||||
}
|
||||
}
|
||||
}
|
||||
function hasPrerenderedPages(internals) {
|
||||
for (const pageData of eachPageData(internals)) {
|
||||
if (pageData.route.prerender) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function cssOrder(a, b) {
|
||||
let depthA = a.depth, depthB = b.depth, orderA = a.order, orderB = b.order;
|
||||
if (orderA === -1 && orderB >= 0) {
|
||||
return 1;
|
||||
} else if (orderB === -1 && orderA >= 0) {
|
||||
return -1;
|
||||
} else if (orderA > orderB) {
|
||||
return 1;
|
||||
} else if (orderA < orderB) {
|
||||
return -1;
|
||||
} else {
|
||||
if (depthA === -1) {
|
||||
return -1;
|
||||
} else if (depthB === -1) {
|
||||
return 1;
|
||||
} else {
|
||||
return depthA > depthB ? -1 : 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
function mergeInlineCss(acc, current) {
|
||||
const lastAdded = acc.at(acc.length - 1);
|
||||
const lastWasInline = (lastAdded == null ? void 0 : lastAdded.type) === "inline";
|
||||
const currentIsInline = (current == null ? void 0 : current.type) === "inline";
|
||||
if (lastWasInline && currentIsInline) {
|
||||
const merged = { type: "inline", content: lastAdded.content + current.content };
|
||||
acc[acc.length - 1] = merged;
|
||||
return acc;
|
||||
}
|
||||
acc.push(current);
|
||||
return acc;
|
||||
}
|
||||
function isHoistedScript(internals, id) {
|
||||
return internals.hoistedScriptIdToPagesMap.has(id);
|
||||
}
|
||||
function* getPageDatasByHoistedScriptId(internals, id) {
|
||||
const set = internals.hoistedScriptIdToPagesMap.get(id);
|
||||
if (set) {
|
||||
for (const pageId of set) {
|
||||
const pageData = getPageDataByComponent(internals, pageId.slice(1));
|
||||
if (pageData) {
|
||||
yield pageData;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function getEntryFilePathFromComponentPath(internals, path) {
|
||||
const id = getVirtualModulePageIdFromPath(path);
|
||||
return internals.entrySpecifierToBundleMap.get(id);
|
||||
}
|
||||
export {
|
||||
createBuildInternals,
|
||||
cssOrder,
|
||||
eachPageData,
|
||||
eachPageDataFromEntryPoint,
|
||||
eachRedirectPageData,
|
||||
getEntryFilePathFromComponentPath,
|
||||
getPageDataByComponent,
|
||||
getPageDataByViteID,
|
||||
getPageDatasByChunk,
|
||||
getPageDatasByClientOnlyID,
|
||||
getPageDatasByHoistedScriptId,
|
||||
hasPageDataByViteID,
|
||||
hasPrerenderedPages,
|
||||
isHoistedScript,
|
||||
mergeInlineCss,
|
||||
trackClientOnlyPageDatas,
|
||||
trackPageData
|
||||
};
|
13
node_modules/astro/dist/core/build/page-data.d.ts
generated
vendored
Normal file
13
node_modules/astro/dist/core/build/page-data.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
import type { AstroSettings, ManifestData } from '../../@types/astro';
|
||||
import type { LogOptions } from '../logger/core';
|
||||
import type { AllPagesData } from './types';
|
||||
export interface CollectPagesDataOptions {
|
||||
settings: AstroSettings;
|
||||
logging: LogOptions;
|
||||
manifest: ManifestData;
|
||||
}
|
||||
export interface CollectPagesDataResult {
|
||||
assets: Record<string, string>;
|
||||
allPages: AllPagesData;
|
||||
}
|
||||
export declare function collectPagesData(opts: CollectPagesDataOptions): Promise<CollectPagesDataResult>;
|
62
node_modules/astro/dist/core/build/page-data.js
generated
vendored
Normal file
62
node_modules/astro/dist/core/build/page-data.js
generated
vendored
Normal file
|
@ -0,0 +1,62 @@
|
|||
import { info } from "../logger/core.js";
|
||||
import * as colors from "kleur/colors";
|
||||
import { debug } from "../logger/core.js";
|
||||
async function collectPagesData(opts) {
|
||||
const { settings, manifest } = opts;
|
||||
const assets = {};
|
||||
const allPages = {};
|
||||
const builtPaths = /* @__PURE__ */ new Set();
|
||||
const dataCollectionLogTimeout = setInterval(() => {
|
||||
info(opts.logging, "build", "The data collection step may take longer for larger projects...");
|
||||
clearInterval(dataCollectionLogTimeout);
|
||||
}, 3e4);
|
||||
for (const route of manifest.routes) {
|
||||
if (route.pathname) {
|
||||
const routeCollectionLogTimeout = setInterval(() => {
|
||||
info(
|
||||
opts.logging,
|
||||
"build",
|
||||
`${colors.bold(
|
||||
route.component
|
||||
)} is taking a bit longer to import. This is common for larger "Astro.glob(...)" or "import.meta.glob(...)" calls, for instance. Hang tight!`
|
||||
);
|
||||
clearInterval(routeCollectionLogTimeout);
|
||||
}, 1e4);
|
||||
builtPaths.add(route.pathname);
|
||||
allPages[route.component] = {
|
||||
component: route.component,
|
||||
route,
|
||||
moduleSpecifier: "",
|
||||
styles: [],
|
||||
propagatedStyles: /* @__PURE__ */ new Map(),
|
||||
propagatedScripts: /* @__PURE__ */ new Map(),
|
||||
hoistedScript: void 0
|
||||
};
|
||||
clearInterval(routeCollectionLogTimeout);
|
||||
if (settings.config.output === "static") {
|
||||
const html = `${route.pathname}`.replace(/\/?$/, "/index.html");
|
||||
debug(
|
||||
"build",
|
||||
`\u251C\u2500\u2500 ${colors.bold(colors.green("\u2714"))} ${route.component} \u2192 ${colors.yellow(html)}`
|
||||
);
|
||||
} else {
|
||||
debug("build", `\u251C\u2500\u2500 ${colors.bold(colors.green("\u2714"))} ${route.component}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
allPages[route.component] = {
|
||||
component: route.component,
|
||||
route,
|
||||
moduleSpecifier: "",
|
||||
styles: [],
|
||||
propagatedStyles: /* @__PURE__ */ new Map(),
|
||||
propagatedScripts: /* @__PURE__ */ new Map(),
|
||||
hoistedScript: void 0
|
||||
};
|
||||
}
|
||||
clearInterval(dataCollectionLogTimeout);
|
||||
return { assets, allPages };
|
||||
}
|
||||
export {
|
||||
collectPagesData
|
||||
};
|
41
node_modules/astro/dist/core/build/plugin.d.ts
generated
vendored
Normal file
41
node_modules/astro/dist/core/build/plugin.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,41 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from './internal';
|
||||
import type { StaticBuildOptions, ViteBuildReturn } from './types';
|
||||
type RollupOutputArray = Extract<ViteBuildReturn, Array<any>>;
|
||||
type OutputChunkorAsset = RollupOutputArray[number]['output'][number];
|
||||
type OutputChunk = Extract<OutputChunkorAsset, {
|
||||
type: 'chunk';
|
||||
}>;
|
||||
type MutateChunk = (chunk: OutputChunk, build: 'server' | 'client', newCode: string) => void;
|
||||
export type AstroBuildPlugin = {
|
||||
build: 'ssr' | 'client' | 'both';
|
||||
hooks?: {
|
||||
'build:before'?: (opts: {
|
||||
build: 'ssr' | 'client';
|
||||
input: Set<string>;
|
||||
}) => {
|
||||
enforce?: 'after-user-plugins';
|
||||
vitePlugin: VitePlugin | VitePlugin[] | undefined;
|
||||
};
|
||||
'build:post'?: (opts: {
|
||||
ssrOutputs: RollupOutputArray;
|
||||
clientOutputs: RollupOutputArray;
|
||||
mutate: MutateChunk;
|
||||
}) => void | Promise<void>;
|
||||
};
|
||||
};
|
||||
export declare function createPluginContainer(options: StaticBuildOptions, internals: BuildInternals): {
|
||||
options: StaticBuildOptions;
|
||||
internals: BuildInternals;
|
||||
register(plugin: AstroBuildPlugin): void;
|
||||
runBeforeHook(build: 'ssr' | 'client', input: Set<string>): {
|
||||
vitePlugins: (VitePlugin | VitePlugin[])[];
|
||||
lastVitePlugins: (VitePlugin | VitePlugin[])[];
|
||||
};
|
||||
runPostHook(ssrReturn: ViteBuildReturn, clientReturn: ViteBuildReturn | null): Promise<Map<string, {
|
||||
build: 'server' | 'client';
|
||||
code: string;
|
||||
}>>;
|
||||
};
|
||||
export type AstroBuildPluginContainer = ReturnType<typeof createPluginContainer>;
|
||||
export {};
|
83
node_modules/astro/dist/core/build/plugin.js
generated
vendored
Normal file
83
node_modules/astro/dist/core/build/plugin.js
generated
vendored
Normal file
|
@ -0,0 +1,83 @@
|
|||
function createPluginContainer(options, internals) {
|
||||
const clientPlugins = [];
|
||||
const ssrPlugins = [];
|
||||
const allPlugins = /* @__PURE__ */ new Set();
|
||||
return {
|
||||
options,
|
||||
internals,
|
||||
register(plugin) {
|
||||
allPlugins.add(plugin);
|
||||
switch (plugin.build) {
|
||||
case "client": {
|
||||
clientPlugins.push(plugin);
|
||||
break;
|
||||
}
|
||||
case "ssr": {
|
||||
ssrPlugins.push(plugin);
|
||||
break;
|
||||
}
|
||||
case "both": {
|
||||
clientPlugins.push(plugin);
|
||||
ssrPlugins.push(plugin);
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
// Hooks
|
||||
runBeforeHook(build, input) {
|
||||
var _a;
|
||||
let plugins = build === "ssr" ? ssrPlugins : clientPlugins;
|
||||
let vitePlugins = [];
|
||||
let lastVitePlugins = [];
|
||||
for (const plugin of plugins) {
|
||||
if ((_a = plugin.hooks) == null ? void 0 : _a["build:before"]) {
|
||||
let result = plugin.hooks["build:before"]({ build, input });
|
||||
if (result.vitePlugin) {
|
||||
vitePlugins.push(result.vitePlugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
vitePlugins,
|
||||
lastVitePlugins
|
||||
};
|
||||
},
|
||||
async runPostHook(ssrReturn, clientReturn) {
|
||||
var _a;
|
||||
const mutations = /* @__PURE__ */ new Map();
|
||||
const ssrOutputs = [];
|
||||
const clientOutputs = [];
|
||||
if (Array.isArray(ssrReturn)) {
|
||||
ssrOutputs.push(...ssrReturn);
|
||||
} else if ("output" in ssrReturn) {
|
||||
ssrOutputs.push(ssrReturn);
|
||||
}
|
||||
if (Array.isArray(clientReturn)) {
|
||||
clientOutputs.push(...clientReturn);
|
||||
} else if (clientReturn && "output" in clientReturn) {
|
||||
clientOutputs.push(clientReturn);
|
||||
}
|
||||
const mutate = (chunk, build, newCode) => {
|
||||
chunk.code = newCode;
|
||||
mutations.set(chunk.fileName, {
|
||||
build,
|
||||
code: newCode
|
||||
});
|
||||
};
|
||||
for (const plugin of allPlugins) {
|
||||
const postHook = (_a = plugin.hooks) == null ? void 0 : _a["build:post"];
|
||||
if (postHook) {
|
||||
await postHook({
|
||||
ssrOutputs,
|
||||
clientOutputs,
|
||||
mutate
|
||||
});
|
||||
}
|
||||
}
|
||||
return mutations;
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
createPluginContainer
|
||||
};
|
2
node_modules/astro/dist/core/build/plugins/index.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/core/build/plugins/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
import type { AstroBuildPluginContainer } from '../plugin';
|
||||
export declare function registerAllPlugins({ internals, options, register }: AstroBuildPluginContainer): void;
|
32
node_modules/astro/dist/core/build/plugins/index.js
generated
vendored
Normal file
32
node_modules/astro/dist/core/build/plugins/index.js
generated
vendored
Normal file
|
@ -0,0 +1,32 @@
|
|||
import { astroConfigBuildPlugin } from "../../../content/vite-plugin-content-assets.js";
|
||||
import { astroHeadBuildPlugin } from "../../../vite-plugin-head/index.js";
|
||||
import { pluginAliasResolve } from "./plugin-alias-resolve.js";
|
||||
import { pluginAnalyzer } from "./plugin-analyzer.js";
|
||||
import { pluginComponentEntry } from "./plugin-component-entry.js";
|
||||
import { pluginCSS } from "./plugin-css.js";
|
||||
import { pluginHoistedScripts } from "./plugin-hoisted-scripts.js";
|
||||
import { pluginInternals } from "./plugin-internals.js";
|
||||
import { pluginMiddleware } from "./plugin-middleware.js";
|
||||
import { pluginPages } from "./plugin-pages.js";
|
||||
import { pluginPrerender } from "./plugin-prerender.js";
|
||||
import { pluginRenderers } from "./plugin-renderers.js";
|
||||
import { pluginSSR, pluginSSRSplit } from "./plugin-ssr.js";
|
||||
function registerAllPlugins({ internals, options, register }) {
|
||||
register(pluginComponentEntry(internals));
|
||||
register(pluginAliasResolve(internals));
|
||||
register(pluginAnalyzer(internals));
|
||||
register(pluginInternals(internals));
|
||||
register(pluginRenderers(options));
|
||||
register(pluginMiddleware(options, internals));
|
||||
register(pluginPages(options, internals));
|
||||
register(pluginCSS(options, internals));
|
||||
register(astroHeadBuildPlugin(internals));
|
||||
register(pluginPrerender(options, internals));
|
||||
register(astroConfigBuildPlugin(options, internals));
|
||||
register(pluginHoistedScripts(options, internals));
|
||||
register(pluginSSR(options, internals));
|
||||
register(pluginSSRSplit(options, internals));
|
||||
}
|
||||
export {
|
||||
registerAllPlugins
|
||||
};
|
10
node_modules/astro/dist/core/build/plugins/plugin-alias-resolve.d.ts
generated
vendored
Normal file
10
node_modules/astro/dist/core/build/plugins/plugin-alias-resolve.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin.js';
|
||||
/**
|
||||
* `@rollup/plugin-alias` doesn't resolve aliases in Rollup input by default. This plugin fixes it
|
||||
* with a partial fork of it's resolve function. https://github.com/rollup/plugins/blob/master/packages/alias/src/index.ts
|
||||
* When https://github.com/rollup/plugins/pull/1402 is merged, we can remove this plugin.
|
||||
*/
|
||||
export declare function vitePluginAliasResolve(internals: BuildInternals): VitePlugin;
|
||||
export declare function pluginAliasResolve(internals: BuildInternals): AstroBuildPlugin;
|
50
node_modules/astro/dist/core/build/plugins/plugin-alias-resolve.js
generated
vendored
Normal file
50
node_modules/astro/dist/core/build/plugins/plugin-alias-resolve.js
generated
vendored
Normal file
|
@ -0,0 +1,50 @@
|
|||
function vitePluginAliasResolve(internals) {
|
||||
let aliases;
|
||||
return {
|
||||
name: "@astro/plugin-alias-resolve",
|
||||
enforce: "pre",
|
||||
configResolved(config) {
|
||||
aliases = config.resolve.alias;
|
||||
},
|
||||
async resolveId(id, importer, opts) {
|
||||
if (!importer && (internals.discoveredHydratedComponents.has(id) || internals.discoveredClientOnlyComponents.has(id))) {
|
||||
const matchedEntry = aliases.find((entry) => matches(entry.find, id));
|
||||
if (!matchedEntry) {
|
||||
return null;
|
||||
}
|
||||
const updatedId = id.replace(matchedEntry.find, matchedEntry.replacement);
|
||||
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, opts)).then(
|
||||
(resolved) => resolved || { id: updatedId }
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function matches(pattern, importee) {
|
||||
if (pattern instanceof RegExp) {
|
||||
return pattern.test(importee);
|
||||
}
|
||||
if (importee.length < pattern.length) {
|
||||
return false;
|
||||
}
|
||||
if (importee === pattern) {
|
||||
return true;
|
||||
}
|
||||
return importee.startsWith(pattern + "/");
|
||||
}
|
||||
function pluginAliasResolve(internals) {
|
||||
return {
|
||||
build: "client",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginAliasResolve(internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
pluginAliasResolve,
|
||||
vitePluginAliasResolve
|
||||
};
|
5
node_modules/astro/dist/core/build/plugins/plugin-analyzer.d.ts
generated
vendored
Normal file
5
node_modules/astro/dist/core/build/plugins/plugin-analyzer.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin.js';
|
||||
export declare function vitePluginAnalyzer(internals: BuildInternals): VitePlugin;
|
||||
export declare function pluginAnalyzer(internals: BuildInternals): AstroBuildPlugin;
|
161
node_modules/astro/dist/core/build/plugins/plugin-analyzer.js
generated
vendored
Normal file
161
node_modules/astro/dist/core/build/plugins/plugin-analyzer.js
generated
vendored
Normal file
|
@ -0,0 +1,161 @@
|
|||
import { PROPAGATED_ASSET_FLAG } from "../../../content/consts.js";
|
||||
import { prependForwardSlash } from "../../../core/path.js";
|
||||
import { getTopLevelPages, moduleIsTopLevelPage, walkParentInfos } from "../graph.js";
|
||||
import { getPageDataByViteID, trackClientOnlyPageDatas } from "../internal.js";
|
||||
function isPropagatedAsset(id) {
|
||||
try {
|
||||
return new URL("file://" + id).searchParams.has(PROPAGATED_ASSET_FLAG);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function vitePluginAnalyzer(internals) {
|
||||
function hoistedScriptScanner() {
|
||||
const uniqueHoistedIds = /* @__PURE__ */ new Map();
|
||||
const pageScripts = /* @__PURE__ */ new Map();
|
||||
return {
|
||||
scan(scripts, from) {
|
||||
var _a;
|
||||
const hoistedScripts = /* @__PURE__ */ new Set();
|
||||
for (let i = 0; i < scripts.length; i++) {
|
||||
const hid = `${from.replace("/@fs", "")}?astro&type=script&index=${i}&lang.ts`;
|
||||
hoistedScripts.add(hid);
|
||||
}
|
||||
if (hoistedScripts.size) {
|
||||
for (const [parentInfo] of walkParentInfos(from, this, function until(importer) {
|
||||
return isPropagatedAsset(importer);
|
||||
})) {
|
||||
if (isPropagatedAsset(parentInfo.id)) {
|
||||
for (const [nestedParentInfo] of walkParentInfos(from, this)) {
|
||||
if (moduleIsTopLevelPage(nestedParentInfo)) {
|
||||
for (const hid of hoistedScripts) {
|
||||
if (!pageScripts.has(nestedParentInfo.id)) {
|
||||
pageScripts.set(nestedParentInfo.id, {
|
||||
hoistedSet: /* @__PURE__ */ new Set(),
|
||||
propagatedMapByImporter: /* @__PURE__ */ new Map()
|
||||
});
|
||||
}
|
||||
const entry = pageScripts.get(nestedParentInfo.id);
|
||||
if (!entry.propagatedMapByImporter.has(parentInfo.id)) {
|
||||
entry.propagatedMapByImporter.set(parentInfo.id, /* @__PURE__ */ new Set());
|
||||
}
|
||||
entry.propagatedMapByImporter.get(parentInfo.id).add(hid);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (moduleIsTopLevelPage(parentInfo)) {
|
||||
for (const hid of hoistedScripts) {
|
||||
if (!pageScripts.has(parentInfo.id)) {
|
||||
pageScripts.set(parentInfo.id, {
|
||||
hoistedSet: /* @__PURE__ */ new Set(),
|
||||
propagatedMapByImporter: /* @__PURE__ */ new Map()
|
||||
});
|
||||
}
|
||||
(_a = pageScripts.get(parentInfo.id)) == null ? void 0 : _a.hoistedSet.add(hid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
finalize() {
|
||||
for (const [pageId, { hoistedSet, propagatedMapByImporter }] of pageScripts) {
|
||||
const pageData = getPageDataByViteID(internals, pageId);
|
||||
if (!pageData)
|
||||
continue;
|
||||
const { component } = pageData;
|
||||
const astroModuleId = prependForwardSlash(component);
|
||||
const uniqueHoistedId = JSON.stringify(Array.from(hoistedSet).sort());
|
||||
let moduleId;
|
||||
if (uniqueHoistedIds.has(uniqueHoistedId)) {
|
||||
moduleId = uniqueHoistedIds.get(uniqueHoistedId);
|
||||
} else {
|
||||
moduleId = `/astro/hoisted.js?q=${uniqueHoistedIds.size}`;
|
||||
uniqueHoistedIds.set(uniqueHoistedId, moduleId);
|
||||
}
|
||||
internals.discoveredScripts.add(moduleId);
|
||||
pageData.propagatedScripts = propagatedMapByImporter;
|
||||
for (const propagatedScripts of propagatedMapByImporter.values()) {
|
||||
for (const propagatedScript of propagatedScripts) {
|
||||
internals.discoveredScripts.add(propagatedScript);
|
||||
}
|
||||
}
|
||||
if (internals.hoistedScriptIdToPagesMap.has(moduleId)) {
|
||||
const pages = internals.hoistedScriptIdToPagesMap.get(moduleId);
|
||||
pages.add(astroModuleId);
|
||||
} else {
|
||||
internals.hoistedScriptIdToPagesMap.set(moduleId, /* @__PURE__ */ new Set([astroModuleId]));
|
||||
internals.hoistedScriptIdToHoistedMap.set(moduleId, hoistedSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: "@astro/rollup-plugin-astro-analyzer",
|
||||
async generateBundle() {
|
||||
var _a;
|
||||
const hoistScanner = hoistedScriptScanner();
|
||||
const ids = this.getModuleIds();
|
||||
for (const id of ids) {
|
||||
const info = this.getModuleInfo(id);
|
||||
if (!((_a = info == null ? void 0 : info.meta) == null ? void 0 : _a.astro))
|
||||
continue;
|
||||
const astro = info.meta.astro;
|
||||
const pageData = getPageDataByViteID(internals, id);
|
||||
if (pageData) {
|
||||
internals.pageOptionsByPage.set(id, astro.pageOptions);
|
||||
}
|
||||
for (const c of astro.hydratedComponents) {
|
||||
const rid = c.resolvedPath ? decodeURI(c.resolvedPath) : c.specifier;
|
||||
if (internals.discoveredHydratedComponents.has(rid)) {
|
||||
const exportNames = internals.discoveredHydratedComponents.get(rid);
|
||||
exportNames == null ? void 0 : exportNames.push(c.exportName);
|
||||
} else {
|
||||
internals.discoveredHydratedComponents.set(rid, [c.exportName]);
|
||||
}
|
||||
}
|
||||
hoistScanner.scan.call(this, astro.scripts, id);
|
||||
if (astro.clientOnlyComponents.length) {
|
||||
const clientOnlys = [];
|
||||
for (const c of astro.clientOnlyComponents) {
|
||||
const cid = c.resolvedPath ? decodeURI(c.resolvedPath) : c.specifier;
|
||||
if (internals.discoveredClientOnlyComponents.has(cid)) {
|
||||
const exportNames = internals.discoveredClientOnlyComponents.get(cid);
|
||||
exportNames == null ? void 0 : exportNames.push(c.exportName);
|
||||
} else {
|
||||
internals.discoveredClientOnlyComponents.set(cid, [c.exportName]);
|
||||
}
|
||||
clientOnlys.push(cid);
|
||||
const resolvedId = await this.resolve(c.specifier, id);
|
||||
if (resolvedId) {
|
||||
clientOnlys.push(resolvedId.id);
|
||||
}
|
||||
}
|
||||
for (const [pageInfo] of getTopLevelPages(id, this)) {
|
||||
const newPageData = getPageDataByViteID(internals, pageInfo.id);
|
||||
if (!newPageData)
|
||||
continue;
|
||||
trackClientOnlyPageDatas(internals, newPageData, clientOnlys);
|
||||
}
|
||||
}
|
||||
}
|
||||
hoistScanner.finalize();
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginAnalyzer(internals) {
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginAnalyzer(internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
pluginAnalyzer,
|
||||
vitePluginAnalyzer
|
||||
};
|
12
node_modules/astro/dist/core/build/plugins/plugin-component-entry.d.ts
generated
vendored
Normal file
12
node_modules/astro/dist/core/build/plugins/plugin-component-entry.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin.js';
|
||||
export declare const astroEntryPrefix = "\0astro-entry:";
|
||||
/**
|
||||
* When adding hydrated or client:only components as Rollup inputs, sometimes we're not using all
|
||||
* of the export names, e.g. `import { Counter } from './ManyComponents.jsx'`. This plugin proxies
|
||||
* entries to re-export only the names the user is using.
|
||||
*/
|
||||
export declare function vitePluginComponentEntry(internals: BuildInternals): VitePlugin;
|
||||
export declare function normalizeEntryId(id: string): string;
|
||||
export declare function pluginComponentEntry(internals: BuildInternals): AstroBuildPlugin;
|
75
node_modules/astro/dist/core/build/plugins/plugin-component-entry.js
generated
vendored
Normal file
75
node_modules/astro/dist/core/build/plugins/plugin-component-entry.js
generated
vendored
Normal file
|
@ -0,0 +1,75 @@
|
|||
const astroEntryPrefix = "\0astro-entry:";
|
||||
function vitePluginComponentEntry(internals) {
|
||||
const componentToExportNames = /* @__PURE__ */ new Map();
|
||||
mergeComponentExportNames(internals.discoveredHydratedComponents);
|
||||
mergeComponentExportNames(internals.discoveredClientOnlyComponents);
|
||||
for (const [componentId, exportNames] of componentToExportNames) {
|
||||
if (exportNames.some((name) => name.includes(".") || name === "*")) {
|
||||
componentToExportNames.delete(componentId);
|
||||
} else {
|
||||
componentToExportNames.set(componentId, Array.from(new Set(exportNames)));
|
||||
}
|
||||
}
|
||||
function mergeComponentExportNames(components) {
|
||||
var _a;
|
||||
for (const [componentId, exportNames] of components) {
|
||||
if (componentToExportNames.has(componentId)) {
|
||||
(_a = componentToExportNames.get(componentId)) == null ? void 0 : _a.push(...exportNames);
|
||||
} else {
|
||||
componentToExportNames.set(componentId, exportNames);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: "@astro/plugin-component-entry",
|
||||
enforce: "pre",
|
||||
config(config) {
|
||||
var _a, _b;
|
||||
const rollupInput = (_b = (_a = config.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.input;
|
||||
if (Array.isArray(rollupInput)) {
|
||||
config.build.rollupOptions.input = rollupInput.map((id) => {
|
||||
if (componentToExportNames.has(id)) {
|
||||
return astroEntryPrefix + id;
|
||||
} else {
|
||||
return id;
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
async resolveId(id) {
|
||||
if (id.startsWith(astroEntryPrefix)) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id.startsWith(astroEntryPrefix)) {
|
||||
const componentId = id.slice(astroEntryPrefix.length);
|
||||
const exportNames = componentToExportNames.get(componentId);
|
||||
if (exportNames) {
|
||||
return `export { ${exportNames.join(", ")} } from ${JSON.stringify(componentId)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function normalizeEntryId(id) {
|
||||
return id.startsWith(astroEntryPrefix) ? id.slice(astroEntryPrefix.length) : id;
|
||||
}
|
||||
function pluginComponentEntry(internals) {
|
||||
return {
|
||||
build: "client",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginComponentEntry(internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
astroEntryPrefix,
|
||||
normalizeEntryId,
|
||||
pluginComponentEntry,
|
||||
vitePluginComponentEntry
|
||||
};
|
5
node_modules/astro/dist/core/build/plugins/plugin-css.d.ts
generated
vendored
Normal file
5
node_modules/astro/dist/core/build/plugins/plugin-css.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
import type { BuildInternals } from '../internal';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
/***** ASTRO PLUGIN *****/
|
||||
export declare function pluginCSS(options: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
219
node_modules/astro/dist/core/build/plugins/plugin-css.js
generated
vendored
Normal file
219
node_modules/astro/dist/core/build/plugins/plugin-css.js
generated
vendored
Normal file
|
@ -0,0 +1,219 @@
|
|||
import * as crypto from "node:crypto";
|
||||
import * as npath from "node:path";
|
||||
import { isBuildableCSSRequest } from "../../render/dev/util.js";
|
||||
import { PROPAGATED_ASSET_FLAG } from "../../../content/consts.js";
|
||||
import * as assetName from "../css-asset-name.js";
|
||||
import { moduleIsTopLevelPage, walkParentInfos } from "../graph.js";
|
||||
import {
|
||||
eachPageData,
|
||||
getPageDataByViteID,
|
||||
getPageDatasByClientOnlyID,
|
||||
getPageDatasByHoistedScriptId,
|
||||
isHoistedScript
|
||||
} from "../internal.js";
|
||||
import { extendManualChunks } from "./util.js";
|
||||
function pluginCSS(options, internals) {
|
||||
return {
|
||||
build: "both",
|
||||
hooks: {
|
||||
"build:before": ({ build }) => {
|
||||
let plugins = rollupPluginAstroBuildCSS({
|
||||
buildOptions: options,
|
||||
internals,
|
||||
target: build === "ssr" ? "server" : "client"
|
||||
});
|
||||
return {
|
||||
vitePlugin: plugins
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function rollupPluginAstroBuildCSS(options) {
|
||||
const { internals, buildOptions } = options;
|
||||
const { settings } = buildOptions;
|
||||
let resolvedConfig;
|
||||
const pagesToCss = {};
|
||||
const pagesToPropagatedCss = {};
|
||||
const cssBuildPlugin = {
|
||||
name: "astro:rollup-plugin-build-css",
|
||||
outputOptions(outputOptions) {
|
||||
const assetFileNames = outputOptions.assetFileNames;
|
||||
const namingIncludesHash = assetFileNames == null ? void 0 : assetFileNames.toString().includes("[hash]");
|
||||
const createNameForParentPages = namingIncludesHash ? assetName.shortHashedName : assetName.createSlugger(settings);
|
||||
extendManualChunks(outputOptions, {
|
||||
after(id, meta) {
|
||||
if (isBuildableCSSRequest(id)) {
|
||||
if (options.target === "client") {
|
||||
return internals.cssModuleToChunkIdMap.get(id);
|
||||
}
|
||||
for (const [pageInfo] of walkParentInfos(id, {
|
||||
getModuleInfo: meta.getModuleInfo
|
||||
})) {
|
||||
if (new URL(pageInfo.id, "file://").searchParams.has(PROPAGATED_ASSET_FLAG)) {
|
||||
const chunkId2 = createNameHash(id, [id]);
|
||||
internals.cssModuleToChunkIdMap.set(id, chunkId2);
|
||||
return chunkId2;
|
||||
}
|
||||
}
|
||||
const chunkId = createNameForParentPages(id, meta);
|
||||
internals.cssModuleToChunkIdMap.set(id, chunkId);
|
||||
return chunkId;
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
async generateBundle(_outputOptions, bundle) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type !== "chunk")
|
||||
continue;
|
||||
if ("viteMetadata" in chunk === false)
|
||||
continue;
|
||||
const meta = chunk.viteMetadata;
|
||||
if (meta.importedCss.size < 1)
|
||||
continue;
|
||||
if (options.target === "client") {
|
||||
for (const id of Object.keys(chunk.modules)) {
|
||||
for (const pageData of getParentClientOnlys(id, this, internals)) {
|
||||
for (const importedCssImport of meta.importedCss) {
|
||||
const cssToInfoRecord = pagesToCss[pageData.moduleSpecifier] ??= {};
|
||||
cssToInfoRecord[importedCssImport] = { depth: -1, order: -1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const id of Object.keys(chunk.modules)) {
|
||||
for (const [pageInfo, depth, order] of walkParentInfos(
|
||||
id,
|
||||
this,
|
||||
function until(importer) {
|
||||
return new URL(importer, "file://").searchParams.has(PROPAGATED_ASSET_FLAG);
|
||||
}
|
||||
)) {
|
||||
if (new URL(pageInfo.id, "file://").searchParams.has(PROPAGATED_ASSET_FLAG)) {
|
||||
for (const parent of walkParentInfos(id, this)) {
|
||||
const parentInfo = parent[0];
|
||||
if (moduleIsTopLevelPage(parentInfo) === false)
|
||||
continue;
|
||||
const pageViteID = parentInfo.id;
|
||||
const pageData = getPageDataByViteID(internals, pageViteID);
|
||||
if (pageData === void 0)
|
||||
continue;
|
||||
for (const css of meta.importedCss) {
|
||||
const propagatedStyles = pagesToPropagatedCss[pageData.moduleSpecifier] ??= {};
|
||||
const existingCss = propagatedStyles[pageInfo.id] ??= /* @__PURE__ */ new Set();
|
||||
existingCss.add(css);
|
||||
}
|
||||
}
|
||||
} else if (moduleIsTopLevelPage(pageInfo)) {
|
||||
const pageViteID = pageInfo.id;
|
||||
const pageData = getPageDataByViteID(internals, pageViteID);
|
||||
if (pageData) {
|
||||
appendCSSToPage(pageData, meta, pagesToCss, depth, order);
|
||||
}
|
||||
} else if (options.target === "client" && isHoistedScript(internals, pageInfo.id)) {
|
||||
for (const pageData of getPageDatasByHoistedScriptId(internals, pageInfo.id)) {
|
||||
appendCSSToPage(pageData, meta, pagesToCss, -1, order);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const singleCssPlugin = {
|
||||
name: "astro:rollup-plugin-single-css",
|
||||
enforce: "post",
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
},
|
||||
generateBundle(_, bundle) {
|
||||
if (resolvedConfig.build.cssCodeSplit)
|
||||
return;
|
||||
const cssChunk = Object.values(bundle).find(
|
||||
(chunk) => chunk.type === "asset" && chunk.name === "style.css"
|
||||
);
|
||||
if (cssChunk === void 0)
|
||||
return;
|
||||
for (const pageData of eachPageData(internals)) {
|
||||
const cssToInfoMap = pagesToCss[pageData.moduleSpecifier] ??= {};
|
||||
cssToInfoMap[cssChunk.fileName] = { depth: -1, order: -1 };
|
||||
}
|
||||
}
|
||||
};
|
||||
const inlineStylesheetsPlugin = {
|
||||
name: "astro:rollup-plugin-inline-stylesheets",
|
||||
enforce: "post",
|
||||
async generateBundle(_outputOptions, bundle) {
|
||||
var _a;
|
||||
const inlineConfig = settings.config.build.inlineStylesheets;
|
||||
const { assetsInlineLimit = 4096 } = ((_a = settings.config.vite) == null ? void 0 : _a.build) ?? {};
|
||||
Object.entries(bundle).forEach(([id, stylesheet]) => {
|
||||
var _a2;
|
||||
if (stylesheet.type !== "asset" || ((_a2 = stylesheet.name) == null ? void 0 : _a2.endsWith(".css")) !== true || typeof stylesheet.source !== "string")
|
||||
return;
|
||||
const assetSize = new TextEncoder().encode(stylesheet.source).byteLength;
|
||||
const toBeInlined = inlineConfig === "always" ? true : inlineConfig === "never" ? false : assetSize <= assetsInlineLimit;
|
||||
if (toBeInlined)
|
||||
delete bundle[id];
|
||||
const sheet = toBeInlined ? { type: "inline", content: stylesheet.source } : { type: "external", src: stylesheet.fileName };
|
||||
const pages = Array.from(eachPageData(internals));
|
||||
pages.forEach((pageData) => {
|
||||
var _a3;
|
||||
const orderingInfo = (_a3 = pagesToCss[pageData.moduleSpecifier]) == null ? void 0 : _a3[stylesheet.fileName];
|
||||
if (orderingInfo !== void 0)
|
||||
return pageData.styles.push({ ...orderingInfo, sheet });
|
||||
const propagatedPaths = pagesToPropagatedCss[pageData.moduleSpecifier];
|
||||
if (propagatedPaths === void 0)
|
||||
return;
|
||||
Object.entries(propagatedPaths).forEach(([pageInfoId, css]) => {
|
||||
if (css.has(stylesheet.fileName) !== true)
|
||||
return;
|
||||
if (pageData.styles.some((s) => s.sheet === sheet))
|
||||
return;
|
||||
const propagatedStyles = pageData.propagatedStyles.get(pageInfoId) ?? pageData.propagatedStyles.set(pageInfoId, /* @__PURE__ */ new Set()).get(pageInfoId);
|
||||
propagatedStyles.add(sheet);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
return [cssBuildPlugin, singleCssPlugin, inlineStylesheetsPlugin];
|
||||
}
|
||||
function createNameHash(baseId, hashIds) {
|
||||
const baseName = baseId ? npath.parse(baseId).name : "index";
|
||||
const hash = crypto.createHash("sha256");
|
||||
for (const id of hashIds) {
|
||||
hash.update(id, "utf-8");
|
||||
}
|
||||
const h = hash.digest("hex").slice(0, 8);
|
||||
const proposedName = baseName + "." + h;
|
||||
return proposedName;
|
||||
}
|
||||
function* getParentClientOnlys(id, ctx, internals) {
|
||||
for (const [info] of walkParentInfos(id, ctx)) {
|
||||
yield* getPageDatasByClientOnlyID(internals, info.id);
|
||||
}
|
||||
}
|
||||
function appendCSSToPage(pageData, meta, pagesToCss, depth, order) {
|
||||
var _a;
|
||||
for (const importedCssImport of meta.importedCss) {
|
||||
const cssInfo = (_a = pagesToCss[pageData.moduleSpecifier]) == null ? void 0 : _a[importedCssImport];
|
||||
if (cssInfo !== void 0) {
|
||||
if (depth < cssInfo.depth) {
|
||||
cssInfo.depth = depth;
|
||||
}
|
||||
if (cssInfo.order === -1) {
|
||||
cssInfo.order = order;
|
||||
} else if (order < cssInfo.order && order > -1) {
|
||||
cssInfo.order = order;
|
||||
}
|
||||
} else {
|
||||
const cssToInfoRecord = pagesToCss[pageData.moduleSpecifier] ??= {};
|
||||
cssToInfoRecord[importedCssImport] = { depth, order };
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
pluginCSS
|
||||
};
|
7
node_modules/astro/dist/core/build/plugins/plugin-hoisted-scripts.d.ts
generated
vendored
Normal file
7
node_modules/astro/dist/core/build/plugins/plugin-hoisted-scripts.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { AstroSettings } from '../../../@types/astro';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
export declare function vitePluginHoistedScripts(settings: AstroSettings, internals: BuildInternals): VitePlugin;
|
||||
export declare function pluginHoistedScripts(options: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
89
node_modules/astro/dist/core/build/plugins/plugin-hoisted-scripts.js
generated
vendored
Normal file
89
node_modules/astro/dist/core/build/plugins/plugin-hoisted-scripts.js
generated
vendored
Normal file
|
@ -0,0 +1,89 @@
|
|||
import { viteID } from "../../util.js";
|
||||
import { getPageDataByViteID } from "../internal.js";
|
||||
function virtualHoistedEntry(id) {
|
||||
return id.startsWith("/astro/hoisted.js?q=");
|
||||
}
|
||||
function vitePluginHoistedScripts(settings, internals) {
|
||||
return {
|
||||
name: "@astro/rollup-plugin-astro-hoisted-scripts",
|
||||
resolveId(id) {
|
||||
if (virtualHoistedEntry(id)) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if (virtualHoistedEntry(id)) {
|
||||
let code = "";
|
||||
for (let path of internals.hoistedScriptIdToHoistedMap.get(id)) {
|
||||
let importPath = path;
|
||||
if (importPath.startsWith("/@fs")) {
|
||||
importPath = importPath.slice("/@fs".length);
|
||||
}
|
||||
code += `import "${importPath}";`;
|
||||
}
|
||||
return {
|
||||
code
|
||||
};
|
||||
}
|
||||
return void 0;
|
||||
},
|
||||
async generateBundle(_options, bundle) {
|
||||
var _a, _b;
|
||||
let assetInlineLimit = 4096;
|
||||
if (((_a = settings.config.vite) == null ? void 0 : _a.build) && settings.config.vite.build.assetsInlineLimit !== void 0) {
|
||||
assetInlineLimit = (_b = settings.config.vite) == null ? void 0 : _b.build.assetsInlineLimit;
|
||||
}
|
||||
const considerInlining = /* @__PURE__ */ new Map();
|
||||
const importedByOtherScripts = /* @__PURE__ */ new Set();
|
||||
Object.entries(bundle).forEach(([id, output]) => {
|
||||
if (output.type === "chunk" && output.facadeModuleId && virtualHoistedEntry(output.facadeModuleId)) {
|
||||
considerInlining.set(id, output);
|
||||
output.imports.forEach((imported) => importedByOtherScripts.add(imported));
|
||||
}
|
||||
});
|
||||
for (const [id, output] of considerInlining.entries()) {
|
||||
const canBeInlined = importedByOtherScripts.has(output.fileName) === false && output.imports.length === 0 && output.dynamicImports.length === 0 && Buffer.byteLength(output.code) <= assetInlineLimit;
|
||||
let removeFromBundle = false;
|
||||
const facadeId = output.facadeModuleId;
|
||||
const pages = internals.hoistedScriptIdToPagesMap.get(facadeId);
|
||||
for (const pathname of pages) {
|
||||
const vid = viteID(new URL("." + pathname, settings.config.root));
|
||||
const pageInfo = getPageDataByViteID(internals, vid);
|
||||
if (pageInfo) {
|
||||
if (canBeInlined) {
|
||||
pageInfo.hoistedScript = {
|
||||
type: "inline",
|
||||
value: output.code
|
||||
};
|
||||
removeFromBundle = true;
|
||||
} else {
|
||||
pageInfo.hoistedScript = {
|
||||
type: "external",
|
||||
value: id
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removeFromBundle) {
|
||||
delete bundle[id];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginHoistedScripts(options, internals) {
|
||||
return {
|
||||
build: "client",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginHoistedScripts(options.settings, internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
pluginHoistedScripts,
|
||||
vitePluginHoistedScripts
|
||||
};
|
5
node_modules/astro/dist/core/build/plugins/plugin-internals.d.ts
generated
vendored
Normal file
5
node_modules/astro/dist/core/build/plugins/plugin-internals.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
export declare function vitePluginInternals(input: Set<string>, internals: BuildInternals): VitePlugin;
|
||||
export declare function pluginInternals(internals: BuildInternals): AstroBuildPlugin;
|
69
node_modules/astro/dist/core/build/plugins/plugin-internals.js
generated
vendored
Normal file
69
node_modules/astro/dist/core/build/plugins/plugin-internals.js
generated
vendored
Normal file
|
@ -0,0 +1,69 @@
|
|||
import { normalizeEntryId } from "./plugin-component-entry.js";
|
||||
function vitePluginInternals(input, internals) {
|
||||
return {
|
||||
name: "@astro/plugin-build-internals",
|
||||
config(config, options) {
|
||||
var _a;
|
||||
const extra = {};
|
||||
const noExternal = [], external = [];
|
||||
if (options.command === "build" && ((_a = config.build) == null ? void 0 : _a.ssr)) {
|
||||
noExternal.push("astro");
|
||||
external.push("shiki");
|
||||
}
|
||||
extra.ssr = {
|
||||
external,
|
||||
noExternal
|
||||
};
|
||||
return extra;
|
||||
},
|
||||
async generateBundle(_options, bundle) {
|
||||
const promises = [];
|
||||
const mapping = /* @__PURE__ */ new Map();
|
||||
for (const specifier of input) {
|
||||
promises.push(
|
||||
this.resolve(specifier).then((result) => {
|
||||
if (result) {
|
||||
if (mapping.has(result.id)) {
|
||||
mapping.get(result.id).add(specifier);
|
||||
} else {
|
||||
mapping.set(result.id, /* @__PURE__ */ new Set([specifier]));
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
await Promise.all(promises);
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "chunk" && chunk.facadeModuleId) {
|
||||
const specifiers = mapping.get(chunk.facadeModuleId) || /* @__PURE__ */ new Set([chunk.facadeModuleId]);
|
||||
for (const specifier of specifiers) {
|
||||
internals.entrySpecifierToBundleMap.set(normalizeEntryId(specifier), chunk.fileName);
|
||||
}
|
||||
} else if (chunk.type === "chunk") {
|
||||
for (const id of Object.keys(chunk.modules)) {
|
||||
const pageData = internals.pagesByViteID.get(id);
|
||||
if (pageData) {
|
||||
internals.pageToBundleMap.set(pageData.moduleSpecifier, chunk.fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginInternals(internals) {
|
||||
return {
|
||||
build: "both",
|
||||
hooks: {
|
||||
"build:before": ({ input }) => {
|
||||
return {
|
||||
vitePlugin: vitePluginInternals(input, internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
pluginInternals,
|
||||
vitePluginInternals
|
||||
};
|
7
node_modules/astro/dist/core/build/plugins/plugin-middleware.d.ts
generated
vendored
Normal file
7
node_modules/astro/dist/core/build/plugins/plugin-middleware.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { BuildInternals } from '../internal';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
export declare const MIDDLEWARE_MODULE_ID = "@astro-middleware";
|
||||
export declare function vitePluginMiddleware(opts: StaticBuildOptions, internals: BuildInternals): VitePlugin;
|
||||
export declare function pluginMiddleware(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
68
node_modules/astro/dist/core/build/plugins/plugin-middleware.js
generated
vendored
Normal file
68
node_modules/astro/dist/core/build/plugins/plugin-middleware.js
generated
vendored
Normal file
|
@ -0,0 +1,68 @@
|
|||
import { MIDDLEWARE_PATH_SEGMENT_NAME } from "../../constants.js";
|
||||
import { addRollupInput } from "../add-rollup-input.js";
|
||||
const MIDDLEWARE_MODULE_ID = "@astro-middleware";
|
||||
const EMPTY_MIDDLEWARE = "\0empty-middleware";
|
||||
function vitePluginMiddleware(opts, internals) {
|
||||
let resolvedMiddlewareId;
|
||||
return {
|
||||
name: "@astro/plugin-middleware",
|
||||
options(options) {
|
||||
return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
|
||||
},
|
||||
async resolveId(id) {
|
||||
if (id === MIDDLEWARE_MODULE_ID) {
|
||||
const middlewareId = await this.resolve(
|
||||
`${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
|
||||
);
|
||||
if (middlewareId) {
|
||||
resolvedMiddlewareId = middlewareId.id;
|
||||
return middlewareId.id;
|
||||
} else {
|
||||
return EMPTY_MIDDLEWARE;
|
||||
}
|
||||
}
|
||||
if (id === EMPTY_MIDDLEWARE) {
|
||||
return EMPTY_MIDDLEWARE;
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if (id === EMPTY_MIDDLEWARE) {
|
||||
return "export const onRequest = undefined";
|
||||
} else if (id === resolvedMiddlewareId) {
|
||||
this.emitFile({
|
||||
type: "chunk",
|
||||
preserveSignature: "strict",
|
||||
fileName: "middleware.mjs",
|
||||
id
|
||||
});
|
||||
}
|
||||
},
|
||||
writeBundle(_, bundle) {
|
||||
for (const [chunkName, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "asset") {
|
||||
continue;
|
||||
}
|
||||
if (chunk.fileName === "middleware.mjs") {
|
||||
internals.middlewareEntryPoint = new URL(chunkName, opts.settings.config.build.server);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginMiddleware(opts, internals) {
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginMiddleware(opts, internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
MIDDLEWARE_MODULE_ID,
|
||||
pluginMiddleware,
|
||||
vitePluginMiddleware
|
||||
};
|
14
node_modules/astro/dist/core/build/plugins/plugin-pages.d.ts
generated
vendored
Normal file
14
node_modules/astro/dist/core/build/plugins/plugin-pages.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,14 @@
|
|||
import { type BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
export declare const ASTRO_PAGE_MODULE_ID = "@astro-page:";
|
||||
export declare const ASTRO_PAGE_RESOLVED_MODULE_ID: string;
|
||||
/**
|
||||
* 1. We add a fixed prefix, which is used as virtual module naming convention;
|
||||
* 2. We replace the dot that belongs extension with an arbitrary string.
|
||||
*
|
||||
* @param path
|
||||
*/
|
||||
export declare function getVirtualModulePageNameFromPath(path: string): string;
|
||||
export declare function getVirtualModulePageIdFromPath(path: string): string;
|
||||
export declare function pluginPages(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
85
node_modules/astro/dist/core/build/plugins/plugin-pages.js
generated
vendored
Normal file
85
node_modules/astro/dist/core/build/plugins/plugin-pages.js
generated
vendored
Normal file
|
@ -0,0 +1,85 @@
|
|||
import { extname } from "node:path";
|
||||
import { routeIsRedirect } from "../../redirects/index.js";
|
||||
import { addRollupInput } from "../add-rollup-input.js";
|
||||
import { MIDDLEWARE_MODULE_ID } from "./plugin-middleware.js";
|
||||
import { RENDERERS_MODULE_ID } from "./plugin-renderers.js";
|
||||
import { ASTRO_PAGE_EXTENSION_POST_PATTERN, getPathFromVirtualModulePageName } from "./util.js";
|
||||
const ASTRO_PAGE_MODULE_ID = "@astro-page:";
|
||||
const ASTRO_PAGE_RESOLVED_MODULE_ID = "\0" + ASTRO_PAGE_MODULE_ID;
|
||||
function getVirtualModulePageNameFromPath(path) {
|
||||
const extension = extname(path);
|
||||
return `${ASTRO_PAGE_MODULE_ID}${path.replace(
|
||||
extension,
|
||||
extension.replace(".", ASTRO_PAGE_EXTENSION_POST_PATTERN)
|
||||
)}`;
|
||||
}
|
||||
function getVirtualModulePageIdFromPath(path) {
|
||||
const name = getVirtualModulePageNameFromPath(path);
|
||||
return "\0" + name;
|
||||
}
|
||||
function vitePluginPages(opts, internals) {
|
||||
return {
|
||||
name: "@astro/plugin-build-pages",
|
||||
options(options) {
|
||||
if (opts.settings.config.output === "static") {
|
||||
const inputs = /* @__PURE__ */ new Set();
|
||||
for (const [path, pageData] of Object.entries(opts.allPages)) {
|
||||
if (routeIsRedirect(pageData.route)) {
|
||||
continue;
|
||||
}
|
||||
inputs.add(getVirtualModulePageNameFromPath(path));
|
||||
}
|
||||
return addRollupInput(options, Array.from(inputs));
|
||||
}
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id.startsWith(ASTRO_PAGE_MODULE_ID)) {
|
||||
return "\0" + id;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id.startsWith(ASTRO_PAGE_RESOLVED_MODULE_ID)) {
|
||||
const imports = [];
|
||||
const exports = [];
|
||||
const pageName = getPathFromVirtualModulePageName(ASTRO_PAGE_RESOLVED_MODULE_ID, id);
|
||||
const pageData = internals.pagesByComponent.get(pageName);
|
||||
if (pageData) {
|
||||
const resolvedPage = await this.resolve(pageData.moduleSpecifier);
|
||||
if (resolvedPage) {
|
||||
imports.push(`const page = () => import(${JSON.stringify(pageData.moduleSpecifier)});`);
|
||||
exports.push(`export { page }`);
|
||||
imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
|
||||
exports.push(`export { renderers };`);
|
||||
if (!opts.settings.config.build.excludeMiddleware) {
|
||||
const middlewareModule = await this.resolve(MIDDLEWARE_MODULE_ID);
|
||||
if (middlewareModule) {
|
||||
imports.push(`import { onRequest } from "${middlewareModule.id}";`);
|
||||
exports.push(`export { onRequest };`);
|
||||
}
|
||||
}
|
||||
return `${imports.join("\n")}${exports.join("\n")}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginPages(opts, internals) {
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginPages(opts, internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
ASTRO_PAGE_MODULE_ID,
|
||||
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
||||
getVirtualModulePageIdFromPath,
|
||||
getVirtualModulePageNameFromPath,
|
||||
pluginPages
|
||||
};
|
4
node_modules/astro/dist/core/build/plugins/plugin-prerender.d.ts
generated
vendored
Normal file
4
node_modules/astro/dist/core/build/plugins/plugin-prerender.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
import type { BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin.js';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
export declare function pluginPrerender(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
41
node_modules/astro/dist/core/build/plugins/plugin-prerender.js
generated
vendored
Normal file
41
node_modules/astro/dist/core/build/plugins/plugin-prerender.js
generated
vendored
Normal file
|
@ -0,0 +1,41 @@
|
|||
import path from "node:path";
|
||||
import { getPrerenderMetadata } from "../../../prerender/metadata.js";
|
||||
import { extendManualChunks } from "./util.js";
|
||||
function vitePluginPrerender(opts, internals) {
|
||||
return {
|
||||
name: "astro:rollup-plugin-prerender",
|
||||
outputOptions(outputOptions) {
|
||||
extendManualChunks(outputOptions, {
|
||||
after(id, meta) {
|
||||
if (id.includes("astro/dist")) {
|
||||
return "astro";
|
||||
}
|
||||
const pageInfo = internals.pagesByViteID.get(id);
|
||||
if (pageInfo) {
|
||||
if (getPrerenderMetadata(meta.getModuleInfo(id))) {
|
||||
pageInfo.route.prerender = true;
|
||||
return "prerender";
|
||||
}
|
||||
pageInfo.route.prerender = false;
|
||||
return `pages/${path.basename(pageInfo.component)}`;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginPrerender(opts, internals) {
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginPrerender(opts, internals)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
pluginPrerender
|
||||
};
|
7
node_modules/astro/dist/core/build/plugins/plugin-renderers.d.ts
generated
vendored
Normal file
7
node_modules/astro/dist/core/build/plugins/plugin-renderers.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { StaticBuildOptions } from '../types';
|
||||
export declare const RENDERERS_MODULE_ID = "@astro-renderers";
|
||||
export declare const RESOLVED_RENDERERS_MODULE_ID: string;
|
||||
export declare function vitePluginRenderers(opts: StaticBuildOptions): VitePlugin;
|
||||
export declare function pluginRenderers(opts: StaticBuildOptions): AstroBuildPlugin;
|
53
node_modules/astro/dist/core/build/plugins/plugin-renderers.js
generated
vendored
Normal file
53
node_modules/astro/dist/core/build/plugins/plugin-renderers.js
generated
vendored
Normal file
|
@ -0,0 +1,53 @@
|
|||
import { addRollupInput } from "../add-rollup-input.js";
|
||||
const RENDERERS_MODULE_ID = "@astro-renderers";
|
||||
const RESOLVED_RENDERERS_MODULE_ID = `\0${RENDERERS_MODULE_ID}`;
|
||||
function vitePluginRenderers(opts) {
|
||||
return {
|
||||
name: "@astro/plugin-renderers",
|
||||
options(options) {
|
||||
return addRollupInput(options, [RENDERERS_MODULE_ID]);
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id === RENDERERS_MODULE_ID) {
|
||||
return RESOLVED_RENDERERS_MODULE_ID;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id === RESOLVED_RENDERERS_MODULE_ID) {
|
||||
if (opts.settings.renderers.length > 0) {
|
||||
const imports = [];
|
||||
const exports = [];
|
||||
let i = 0;
|
||||
let rendererItems = "";
|
||||
for (const renderer of opts.settings.renderers) {
|
||||
const variable = `_renderer${i}`;
|
||||
imports.push(`import ${variable} from '${renderer.serverEntrypoint}';`);
|
||||
rendererItems += `Object.assign(${JSON.stringify(renderer)}, { ssr: ${variable} }),`;
|
||||
i++;
|
||||
}
|
||||
exports.push(`export const renderers = [${rendererItems}];`);
|
||||
return `${imports.join("\n")}
|
||||
${exports.join("\n")}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginRenderers(opts) {
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
return {
|
||||
vitePlugin: vitePluginRenderers(opts)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
RENDERERS_MODULE_ID,
|
||||
RESOLVED_RENDERERS_MODULE_ID,
|
||||
pluginRenderers,
|
||||
vitePluginRenderers
|
||||
};
|
17
node_modules/astro/dist/core/build/plugins/plugin-ssr.d.ts
generated
vendored
Normal file
17
node_modules/astro/dist/core/build/plugins/plugin-ssr.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import type { SerializedSSRManifest } from '../../app/types';
|
||||
import { type BuildInternals } from '../internal.js';
|
||||
import type { AstroBuildPlugin } from '../plugin';
|
||||
import type { OutputChunk, StaticBuildOptions } from '../types';
|
||||
export declare const SSR_VIRTUAL_MODULE_ID = "@astrojs-ssr-virtual-entry";
|
||||
export declare function pluginSSR(options: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
||||
export declare const SPLIT_MODULE_ID = "@astro-page-split:";
|
||||
export declare const RESOLVED_SPLIT_MODULE_ID = "\0@astro-page-split:";
|
||||
export declare function pluginSSRSplit(options: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
|
||||
/**
|
||||
* It injects the manifest in the given output rollup chunk. It returns the new emitted code
|
||||
* @param buildOpts
|
||||
* @param internals
|
||||
* @param chunk
|
||||
*/
|
||||
export declare function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly<OutputChunk>): string;
|
||||
export declare function createManifest(buildOpts: StaticBuildOptions, internals: BuildInternals): Promise<SerializedSSRManifest>;
|
388
node_modules/astro/dist/core/build/plugins/plugin-ssr.js
generated
vendored
Normal file
388
node_modules/astro/dist/core/build/plugins/plugin-ssr.js
generated
vendored
Normal file
|
@ -0,0 +1,388 @@
|
|||
import glob from "fast-glob";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { runHookBuildSsr } from "../../../integrations/index.js";
|
||||
import { isServerLikeOutput } from "../../../prerender/utils.js";
|
||||
import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from "../../../vite-plugin-scripts/index.js";
|
||||
import { joinPaths, prependForwardSlash } from "../../path.js";
|
||||
import { routeIsRedirect } from "../../redirects/index.js";
|
||||
import { serializeRouteData } from "../../routing/index.js";
|
||||
import { addRollupInput } from "../add-rollup-input.js";
|
||||
import { getOutFile, getOutFolder } from "../common.js";
|
||||
import { cssOrder, mergeInlineCss } from "../internal.js";
|
||||
import { ASTRO_PAGE_MODULE_ID } from "./plugin-pages.js";
|
||||
import { RENDERERS_MODULE_ID } from "./plugin-renderers.js";
|
||||
import { getPathFromVirtualModulePageName, getVirtualModulePageNameFromPath } from "./util.js";
|
||||
const SSR_VIRTUAL_MODULE_ID = "@astrojs-ssr-virtual-entry";
|
||||
const RESOLVED_SSR_VIRTUAL_MODULE_ID = "\0" + SSR_VIRTUAL_MODULE_ID;
|
||||
const manifestReplace = "@@ASTRO_MANIFEST_REPLACE@@";
|
||||
const replaceExp = new RegExp(`['"](${manifestReplace})['"]`, "g");
|
||||
function vitePluginSSR(internals, adapter, options) {
|
||||
return {
|
||||
name: "@astrojs/vite-plugin-astro-ssr-server",
|
||||
enforce: "post",
|
||||
options(opts) {
|
||||
return addRollupInput(opts, [SSR_VIRTUAL_MODULE_ID]);
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id === SSR_VIRTUAL_MODULE_ID) {
|
||||
return RESOLVED_SSR_VIRTUAL_MODULE_ID;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id === RESOLVED_SSR_VIRTUAL_MODULE_ID) {
|
||||
const { allPages } = options;
|
||||
const imports = [];
|
||||
const contents = [];
|
||||
const exports = [];
|
||||
let i = 0;
|
||||
const pageMap = [];
|
||||
for (const [path, pageData] of Object.entries(allPages)) {
|
||||
if (routeIsRedirect(pageData.route)) {
|
||||
continue;
|
||||
}
|
||||
const virtualModuleName = getVirtualModulePageNameFromPath(ASTRO_PAGE_MODULE_ID, path);
|
||||
let module = await this.resolve(virtualModuleName);
|
||||
if (module) {
|
||||
const variable = `_page${i}`;
|
||||
imports.push(`const ${variable} = () => import("${virtualModuleName}");`);
|
||||
const pageData2 = internals.pagesByComponent.get(path);
|
||||
if (pageData2) {
|
||||
pageMap.push(`[${JSON.stringify(pageData2.component)}, ${variable}]`);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
contents.push(`const pageMap = new Map([${pageMap.join(",")}]);`);
|
||||
exports.push(`export { pageMap }`);
|
||||
const ssrCode = generateSSRCode(options.settings.config, adapter);
|
||||
imports.push(...ssrCode.imports);
|
||||
contents.push(...ssrCode.contents);
|
||||
return `${imports.join("\n")}${contents.join("\n")}${exports.join("\n")}`;
|
||||
}
|
||||
return void 0;
|
||||
},
|
||||
async generateBundle(_opts, bundle) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "asset") {
|
||||
internals.staticFiles.add(chunk.fileName);
|
||||
}
|
||||
}
|
||||
for (const [chunkName, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "asset") {
|
||||
continue;
|
||||
}
|
||||
if (chunk.modules[RESOLVED_SSR_VIRTUAL_MODULE_ID]) {
|
||||
internals.ssrEntryChunk = chunk;
|
||||
delete bundle[chunkName];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginSSR(options, internals) {
|
||||
const ssr = isServerLikeOutput(options.settings.config);
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
let vitePlugin = ssr && !options.settings.config.build.split ? vitePluginSSR(internals, options.settings.adapter, options) : void 0;
|
||||
return {
|
||||
enforce: "after-user-plugins",
|
||||
vitePlugin
|
||||
};
|
||||
},
|
||||
"build:post": async ({ mutate }) => {
|
||||
if (!ssr) {
|
||||
return;
|
||||
}
|
||||
if (options.settings.config.build.split) {
|
||||
return;
|
||||
}
|
||||
if (!internals.ssrEntryChunk) {
|
||||
throw new Error(`Did not generate an entry chunk for SSR`);
|
||||
}
|
||||
internals.ssrEntryChunk.fileName = options.settings.config.build.serverEntry;
|
||||
const manifest = await createManifest(options, internals);
|
||||
await runHookBuildSsr({
|
||||
config: options.settings.config,
|
||||
manifest,
|
||||
logging: options.logging,
|
||||
entryPoints: internals.entryPoints,
|
||||
middlewareEntryPoint: internals.middlewareEntryPoint
|
||||
});
|
||||
const code = injectManifest(manifest, internals.ssrEntryChunk);
|
||||
mutate(internals.ssrEntryChunk, "server", code);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
const SPLIT_MODULE_ID = "@astro-page-split:";
|
||||
const RESOLVED_SPLIT_MODULE_ID = "\0@astro-page-split:";
|
||||
function vitePluginSSRSplit(internals, adapter, options) {
|
||||
return {
|
||||
name: "@astrojs/vite-plugin-astro-ssr-split",
|
||||
enforce: "post",
|
||||
options(opts) {
|
||||
if (options.settings.config.build.split) {
|
||||
const inputs = /* @__PURE__ */ new Set();
|
||||
for (const path of Object.keys(options.allPages)) {
|
||||
inputs.add(getVirtualModulePageNameFromPath(SPLIT_MODULE_ID, path));
|
||||
}
|
||||
return addRollupInput(opts, Array.from(inputs));
|
||||
}
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id.startsWith(SPLIT_MODULE_ID)) {
|
||||
return "\0" + id;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
|
||||
const imports = [];
|
||||
const contents = [];
|
||||
const exports = [];
|
||||
const path = getPathFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, id);
|
||||
const virtualModuleName = getVirtualModulePageNameFromPath(ASTRO_PAGE_MODULE_ID, path);
|
||||
let module = await this.resolve(virtualModuleName);
|
||||
if (module) {
|
||||
imports.push(`import * as pageModule from "${virtualModuleName}";`);
|
||||
}
|
||||
const ssrCode = generateSSRCode(options.settings.config, adapter);
|
||||
imports.push(...ssrCode.imports);
|
||||
contents.push(...ssrCode.contents);
|
||||
return `${imports.join("\n")}${contents.join("\n")}${exports.join("\n")}`;
|
||||
}
|
||||
return void 0;
|
||||
},
|
||||
async generateBundle(_opts, bundle) {
|
||||
for (const [, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "asset") {
|
||||
internals.staticFiles.add(chunk.fileName);
|
||||
}
|
||||
}
|
||||
for (const [chunkName, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "asset") {
|
||||
continue;
|
||||
}
|
||||
let shouldDeleteBundle = false;
|
||||
for (const moduleKey of Object.keys(chunk.modules)) {
|
||||
if (moduleKey.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
|
||||
internals.ssrSplitEntryChunks.set(moduleKey, chunk);
|
||||
storeEntryPoint(moduleKey, options, internals, chunk.fileName);
|
||||
shouldDeleteBundle = true;
|
||||
}
|
||||
}
|
||||
if (shouldDeleteBundle) {
|
||||
delete bundle[chunkName];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function pluginSSRSplit(options, internals) {
|
||||
const ssr = isServerLikeOutput(options.settings.config);
|
||||
return {
|
||||
build: "ssr",
|
||||
hooks: {
|
||||
"build:before": () => {
|
||||
let vitePlugin = ssr && options.settings.config.build.split ? vitePluginSSRSplit(internals, options.settings.adapter, options) : void 0;
|
||||
return {
|
||||
enforce: "after-user-plugins",
|
||||
vitePlugin
|
||||
};
|
||||
},
|
||||
"build:post": async ({ mutate }) => {
|
||||
if (!ssr) {
|
||||
return;
|
||||
}
|
||||
if (!options.settings.config.build.split) {
|
||||
return;
|
||||
}
|
||||
if (internals.ssrSplitEntryChunks.size === 0) {
|
||||
throw new Error(`Did not generate an entry chunk for SSR serverless`);
|
||||
}
|
||||
const manifest = await createManifest(options, internals);
|
||||
await runHookBuildSsr({
|
||||
config: options.settings.config,
|
||||
manifest,
|
||||
logging: options.logging,
|
||||
entryPoints: internals.entryPoints,
|
||||
middlewareEntryPoint: internals.middlewareEntryPoint
|
||||
});
|
||||
for (const [, chunk] of internals.ssrSplitEntryChunks) {
|
||||
const code = injectManifest(manifest, chunk);
|
||||
mutate(chunk, "server", code);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function generateSSRCode(config, adapter) {
|
||||
const imports = [];
|
||||
const contents = [];
|
||||
let pageMap;
|
||||
if (config.build.split) {
|
||||
pageMap = "pageModule";
|
||||
} else {
|
||||
pageMap = "pageMap";
|
||||
}
|
||||
contents.push(`import * as adapter from '${adapter.serverEntrypoint}';
|
||||
import { renderers } from '${RENDERERS_MODULE_ID}';
|
||||
import { deserializeManifest as _deserializeManifest } from 'astro/app';
|
||||
import { _privateSetManifestDontUseThis } from 'astro:ssr-manifest';
|
||||
const _manifest = Object.assign(_deserializeManifest('${manifestReplace}'), {
|
||||
${pageMap},
|
||||
renderers,
|
||||
});
|
||||
_privateSetManifestDontUseThis(_manifest);
|
||||
const _args = ${adapter.args ? JSON.stringify(adapter.args) : "undefined"};
|
||||
|
||||
${adapter.exports ? `const _exports = adapter.createExports(_manifest, _args);
|
||||
${adapter.exports.map((name) => {
|
||||
if (name === "default") {
|
||||
return `const _default = _exports['default'];
|
||||
export { _default as default };`;
|
||||
} else {
|
||||
return `export const ${name} = _exports['${name}'];`;
|
||||
}
|
||||
}).join("\n")}
|
||||
` : ""}
|
||||
const _start = 'start';
|
||||
if(_start in adapter) {
|
||||
adapter[_start](_manifest, _args);
|
||||
}`);
|
||||
return {
|
||||
imports,
|
||||
contents
|
||||
};
|
||||
}
|
||||
function injectManifest(manifest, chunk) {
|
||||
const code = chunk.code;
|
||||
return code.replace(replaceExp, () => {
|
||||
return JSON.stringify(manifest);
|
||||
});
|
||||
}
|
||||
async function createManifest(buildOpts, internals) {
|
||||
if (buildOpts.settings.config.build.split) {
|
||||
if (internals.ssrSplitEntryChunks.size === 0) {
|
||||
throw new Error(`Did not generate an entry chunk for SSR in serverless mode`);
|
||||
}
|
||||
} else {
|
||||
if (!internals.ssrEntryChunk) {
|
||||
throw new Error(`Did not generate an entry chunk for SSR`);
|
||||
}
|
||||
}
|
||||
const clientStatics = new Set(
|
||||
await glob("**/*", {
|
||||
cwd: fileURLToPath(buildOpts.settings.config.build.client)
|
||||
})
|
||||
);
|
||||
for (const file of clientStatics) {
|
||||
internals.staticFiles.add(file);
|
||||
}
|
||||
const staticFiles = internals.staticFiles;
|
||||
return buildManifest(buildOpts, internals, Array.from(staticFiles));
|
||||
}
|
||||
function storeEntryPoint(moduleKey, options, internals, fileName) {
|
||||
const componentPath = getPathFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, moduleKey);
|
||||
for (const [page, pageData] of Object.entries(options.allPages)) {
|
||||
if (componentPath == page) {
|
||||
const publicPath = fileURLToPath(options.settings.config.build.server);
|
||||
internals.entryPoints.set(pageData.route, pathToFileURL(join(publicPath, fileName)));
|
||||
}
|
||||
}
|
||||
}
|
||||
function buildManifest(opts, internals, staticFiles) {
|
||||
const { settings } = opts;
|
||||
const routes = [];
|
||||
const entryModules = Object.fromEntries(internals.entrySpecifierToBundleMap.entries());
|
||||
if (settings.scripts.some((script) => script.stage === "page")) {
|
||||
staticFiles.push(entryModules[PAGE_SCRIPT_ID]);
|
||||
}
|
||||
const prefixAssetPath = (pth) => {
|
||||
if (settings.config.build.assetsPrefix) {
|
||||
return joinPaths(settings.config.build.assetsPrefix, pth);
|
||||
} else {
|
||||
return prependForwardSlash(joinPaths(settings.config.base, pth));
|
||||
}
|
||||
};
|
||||
for (const route of opts.manifest.routes) {
|
||||
if (!route.prerender)
|
||||
continue;
|
||||
if (!route.pathname)
|
||||
continue;
|
||||
const outFolder = getOutFolder(opts.settings.config, route.pathname, route.type);
|
||||
const outFile = getOutFile(opts.settings.config, outFolder, route.pathname, route.type);
|
||||
const file = outFile.toString().replace(opts.settings.config.build.client.toString(), "");
|
||||
routes.push({
|
||||
file,
|
||||
links: [],
|
||||
scripts: [],
|
||||
styles: [],
|
||||
routeData: serializeRouteData(route, settings.config.trailingSlash)
|
||||
});
|
||||
staticFiles.push(file);
|
||||
}
|
||||
for (const route of opts.manifest.routes) {
|
||||
const pageData = internals.pagesByComponent.get(route.component);
|
||||
if (route.prerender || !pageData)
|
||||
continue;
|
||||
const scripts = [];
|
||||
if (pageData.hoistedScript) {
|
||||
const hoistedValue = pageData.hoistedScript.value;
|
||||
const value = hoistedValue.endsWith(".js") ? prefixAssetPath(hoistedValue) : hoistedValue;
|
||||
scripts.unshift(
|
||||
Object.assign({}, pageData.hoistedScript, {
|
||||
value
|
||||
})
|
||||
);
|
||||
}
|
||||
if (settings.scripts.some((script) => script.stage === "page")) {
|
||||
const src = entryModules[PAGE_SCRIPT_ID];
|
||||
scripts.push({
|
||||
type: "external",
|
||||
value: prefixAssetPath(src)
|
||||
});
|
||||
}
|
||||
const links = [];
|
||||
const styles = pageData.styles.sort(cssOrder).map(({ sheet }) => sheet).map((s) => s.type === "external" ? { ...s, src: prefixAssetPath(s.src) } : s).reduce(mergeInlineCss, []);
|
||||
routes.push({
|
||||
file: "",
|
||||
links,
|
||||
scripts: [
|
||||
...scripts,
|
||||
...settings.scripts.filter((script) => script.stage === "head-inline").map(({ stage, content }) => ({ stage, children: content }))
|
||||
],
|
||||
styles,
|
||||
routeData: serializeRouteData(route, settings.config.trailingSlash)
|
||||
});
|
||||
}
|
||||
if (!(BEFORE_HYDRATION_SCRIPT_ID in entryModules)) {
|
||||
entryModules[BEFORE_HYDRATION_SCRIPT_ID] = "";
|
||||
}
|
||||
const ssrManifest = {
|
||||
adapterName: opts.settings.adapter.name,
|
||||
routes,
|
||||
site: settings.config.site,
|
||||
base: settings.config.base,
|
||||
compressHTML: settings.config.compressHTML,
|
||||
assetsPrefix: settings.config.build.assetsPrefix,
|
||||
markdown: settings.config.markdown,
|
||||
componentMetadata: Array.from(internals.componentMetadata),
|
||||
renderers: [],
|
||||
clientDirectives: Array.from(settings.clientDirectives),
|
||||
entryModules,
|
||||
assets: staticFiles.map(prefixAssetPath)
|
||||
};
|
||||
return ssrManifest;
|
||||
}
|
||||
export {
|
||||
RESOLVED_SPLIT_MODULE_ID,
|
||||
SPLIT_MODULE_ID,
|
||||
SSR_VIRTUAL_MODULE_ID,
|
||||
createManifest,
|
||||
injectManifest,
|
||||
pluginSSR,
|
||||
pluginSSRSplit
|
||||
};
|
24
node_modules/astro/dist/core/build/plugins/util.d.ts
generated
vendored
Normal file
24
node_modules/astro/dist/core/build/plugins/util.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import type { Plugin as VitePlugin } from 'vite';
|
||||
type OutputOptionsHook = Extract<VitePlugin['outputOptions'], Function>;
|
||||
type OutputOptions = Parameters<OutputOptionsHook>[0];
|
||||
type ExtendManualChunksHooks = {
|
||||
before?: (id: string, meta: any) => string | undefined;
|
||||
after?: (id: string, meta: any) => string | undefined;
|
||||
};
|
||||
export declare function extendManualChunks(outputOptions: OutputOptions, hooks: ExtendManualChunksHooks): void;
|
||||
export declare const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
|
||||
/**
|
||||
* 1. We add a fixed prefix, which is used as virtual module naming convention;
|
||||
* 2. We replace the dot that belongs extension with an arbitrary string.
|
||||
*
|
||||
* @param virtualModulePrefix
|
||||
* @param path
|
||||
*/
|
||||
export declare function getVirtualModulePageNameFromPath(virtualModulePrefix: string, path: string): string;
|
||||
/**
|
||||
*
|
||||
* @param virtualModulePrefix
|
||||
* @param id
|
||||
*/
|
||||
export declare function getPathFromVirtualModulePageName(virtualModulePrefix: string, id: string): string;
|
||||
export {};
|
45
node_modules/astro/dist/core/build/plugins/util.js
generated
vendored
Normal file
45
node_modules/astro/dist/core/build/plugins/util.js
generated
vendored
Normal file
|
@ -0,0 +1,45 @@
|
|||
import { extname } from "node:path";
|
||||
function extendManualChunks(outputOptions, hooks) {
|
||||
const manualChunks = outputOptions.manualChunks;
|
||||
outputOptions.manualChunks = function(id, meta) {
|
||||
if (hooks.before) {
|
||||
let value = hooks.before(id, meta);
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (typeof manualChunks == "object") {
|
||||
if (id in manualChunks) {
|
||||
let value = manualChunks[id];
|
||||
return value[0];
|
||||
}
|
||||
} else if (typeof manualChunks === "function") {
|
||||
const outid = manualChunks.call(this, id, meta);
|
||||
if (outid) {
|
||||
return outid;
|
||||
}
|
||||
}
|
||||
if (hooks.after) {
|
||||
return hooks.after(id, meta) || null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
|
||||
function getVirtualModulePageNameFromPath(virtualModulePrefix, path) {
|
||||
const extension = extname(path);
|
||||
return `${virtualModulePrefix}${path.replace(
|
||||
extension,
|
||||
extension.replace(".", ASTRO_PAGE_EXTENSION_POST_PATTERN)
|
||||
)}`;
|
||||
}
|
||||
function getPathFromVirtualModulePageName(virtualModulePrefix, id) {
|
||||
const pageName = id.slice(virtualModulePrefix.length);
|
||||
return pageName.replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".");
|
||||
}
|
||||
export {
|
||||
ASTRO_PAGE_EXTENSION_POST_PATTERN,
|
||||
extendManualChunks,
|
||||
getPathFromVirtualModulePageName,
|
||||
getVirtualModulePageNameFromPath
|
||||
};
|
39
node_modules/astro/dist/core/build/static-build.d.ts
generated
vendored
Normal file
39
node_modules/astro/dist/core/build/static-build.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,39 @@
|
|||
import type { RouteData } from '../../@types/astro';
|
||||
import { type BuildInternals } from '../../core/build/internal.js';
|
||||
import type { StaticBuildOptions } from './types';
|
||||
export declare function viteBuild(opts: StaticBuildOptions): Promise<{
|
||||
internals: BuildInternals;
|
||||
}>;
|
||||
export declare function staticBuild(opts: StaticBuildOptions, internals: BuildInternals): Promise<void>;
|
||||
/**
|
||||
* This function takes the virtual module name of any page entrypoint and
|
||||
* transforms it to generate a final `.mjs` output file.
|
||||
*
|
||||
* Input: `@astro-page:src/pages/index@_@astro`
|
||||
* Output: `pages/index.astro.mjs`
|
||||
* Input: `@astro-page:../node_modules/my-dep/injected@_@astro`
|
||||
* Output: `pages/injected.mjs`
|
||||
*
|
||||
* 1. We clean the `facadeModuleId` by removing the `ASTRO_PAGE_MODULE_ID` prefix and `ASTRO_PAGE_EXTENSION_POST_PATTERN`.
|
||||
* 2. We find the matching route pattern in the manifest (or fallback to the cleaned module id)
|
||||
* 3. We replace square brackets with underscore (`[slug]` => `_slug_`) and `...` with `` (`[...slug]` => `_---slug_`).
|
||||
* 4. We append the `.mjs` extension, so the file will always be an ESM module
|
||||
*
|
||||
* @param prefix string
|
||||
* @param facadeModuleId string
|
||||
* @param pages AllPagesData
|
||||
*/
|
||||
export declare function makeAstroPageEntryPointFileName(prefix: string, facadeModuleId: string, routes: RouteData[]): string;
|
||||
/**
|
||||
* The `facadeModuleId` has a shape like: \0@astro-serverless-page:src/pages/index@_@astro.
|
||||
*
|
||||
* 1. We call `makeAstroPageEntryPointFileName` which normalise its name, making it like a file path
|
||||
* 2. We split the file path using the file system separator and attempt to retrieve the last entry
|
||||
* 3. The last entry should be the file
|
||||
* 4. We prepend the file name with `entry.`
|
||||
* 5. We built the file path again, using the new entry built in the previous step
|
||||
*
|
||||
* @param facadeModuleId
|
||||
* @param opts
|
||||
*/
|
||||
export declare function makeSplitEntryPointFileName(facadeModuleId: string, routes: RouteData[]): string;
|
368
node_modules/astro/dist/core/build/static-build.js
generated
vendored
Normal file
368
node_modules/astro/dist/core/build/static-build.js
generated
vendored
Normal file
|
@ -0,0 +1,368 @@
|
|||
import { teardown } from "@astrojs/compiler";
|
||||
import * as eslexer from "es-module-lexer";
|
||||
import glob from "fast-glob";
|
||||
import { bgGreen, bgMagenta, black, dim } from "kleur/colors";
|
||||
import fs from "node:fs";
|
||||
import path, { extname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as vite from "vite";
|
||||
import {
|
||||
createBuildInternals,
|
||||
eachPageData
|
||||
} from "../../core/build/internal.js";
|
||||
import { emptyDir, removeEmptyDirs } from "../../core/fs/index.js";
|
||||
import { appendForwardSlash, prependForwardSlash } from "../../core/path.js";
|
||||
import { isModeServerWithNoAdapter } from "../../core/util.js";
|
||||
import { runHookBuildSetup } from "../../integrations/index.js";
|
||||
import { isServerLikeOutput } from "../../prerender/utils.js";
|
||||
import { PAGE_SCRIPT_ID } from "../../vite-plugin-scripts/index.js";
|
||||
import { AstroError, AstroErrorData } from "../errors/index.js";
|
||||
import { info } from "../logger/core.js";
|
||||
import { routeIsRedirect } from "../redirects/index.js";
|
||||
import { getOutDirWithinCwd } from "./common.js";
|
||||
import { generatePages } from "./generate.js";
|
||||
import { trackPageData } from "./internal.js";
|
||||
import { createPluginContainer } from "./plugin.js";
|
||||
import { registerAllPlugins } from "./plugins/index.js";
|
||||
import { ASTRO_PAGE_RESOLVED_MODULE_ID } from "./plugins/plugin-pages.js";
|
||||
import { RESOLVED_RENDERERS_MODULE_ID } from "./plugins/plugin-renderers.js";
|
||||
import { RESOLVED_SPLIT_MODULE_ID, SSR_VIRTUAL_MODULE_ID } from "./plugins/plugin-ssr.js";
|
||||
import { ASTRO_PAGE_EXTENSION_POST_PATTERN } from "./plugins/util.js";
|
||||
import { getTimeStat } from "./util.js";
|
||||
async function viteBuild(opts) {
|
||||
var _a, _b, _c;
|
||||
const { allPages, settings } = opts;
|
||||
if (isModeServerWithNoAdapter(opts.settings)) {
|
||||
throw new AstroError(AstroErrorData.NoAdapterInstalled);
|
||||
}
|
||||
settings.timer.start("SSR build");
|
||||
const pageInput = /* @__PURE__ */ new Set();
|
||||
const facadeIdToPageDataMap = /* @__PURE__ */ new Map();
|
||||
const internals = createBuildInternals();
|
||||
for (const [component, pageData] of Object.entries(allPages)) {
|
||||
const astroModuleURL = new URL("./" + component, settings.config.root);
|
||||
const astroModuleId = prependForwardSlash(component);
|
||||
trackPageData(internals, component, pageData, astroModuleId, astroModuleURL);
|
||||
if (!routeIsRedirect(pageData.route)) {
|
||||
pageInput.add(astroModuleId);
|
||||
facadeIdToPageDataMap.set(fileURLToPath(astroModuleURL), pageData);
|
||||
}
|
||||
}
|
||||
if (((_c = (_b = (_a = settings.config) == null ? void 0 : _a.vite) == null ? void 0 : _b.build) == null ? void 0 : _c.emptyOutDir) !== false) {
|
||||
emptyDir(settings.config.outDir, new Set(".git"));
|
||||
}
|
||||
const container = createPluginContainer(opts, internals);
|
||||
registerAllPlugins(container);
|
||||
const ssrTime = performance.now();
|
||||
info(opts.logging, "build", `Building ${settings.config.output} entrypoints...`);
|
||||
const ssrOutput = await ssrBuild(opts, internals, pageInput, container);
|
||||
info(opts.logging, "build", dim(`Completed in ${getTimeStat(ssrTime, performance.now())}.`));
|
||||
settings.timer.end("SSR build");
|
||||
settings.timer.start("Client build");
|
||||
const rendererClientEntrypoints = settings.renderers.map((r) => r.clientEntrypoint).filter((a) => typeof a === "string");
|
||||
const clientInput = /* @__PURE__ */ new Set([
|
||||
...internals.discoveredHydratedComponents.keys(),
|
||||
...internals.discoveredClientOnlyComponents.keys(),
|
||||
...rendererClientEntrypoints,
|
||||
...internals.discoveredScripts
|
||||
]);
|
||||
if (settings.scripts.some((script) => script.stage === "page")) {
|
||||
clientInput.add(PAGE_SCRIPT_ID);
|
||||
}
|
||||
const clientOutput = await clientBuild(opts, internals, clientInput, container);
|
||||
await runPostBuildHooks(container, ssrOutput, clientOutput);
|
||||
settings.timer.end("Client build");
|
||||
internals.ssrEntryChunk = void 0;
|
||||
if (opts.teardownCompiler) {
|
||||
teardown();
|
||||
}
|
||||
return { internals };
|
||||
}
|
||||
async function staticBuild(opts, internals) {
|
||||
const { settings } = opts;
|
||||
switch (true) {
|
||||
case settings.config.output === "static": {
|
||||
settings.timer.start("Static generate");
|
||||
await generatePages(opts, internals);
|
||||
await cleanServerOutput(opts);
|
||||
settings.timer.end("Static generate");
|
||||
return;
|
||||
}
|
||||
case isServerLikeOutput(settings.config): {
|
||||
settings.timer.start("Server generate");
|
||||
await generatePages(opts, internals);
|
||||
await cleanStaticOutput(opts, internals);
|
||||
info(opts.logging, null, `
|
||||
${bgMagenta(black(" finalizing server assets "))}
|
||||
`);
|
||||
await ssrMoveAssets(opts);
|
||||
settings.timer.end("Server generate");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function ssrBuild(opts, internals, input, container) {
|
||||
var _a, _b, _c, _d, _e;
|
||||
const { allPages, settings, viteConfig } = opts;
|
||||
const ssr = isServerLikeOutput(settings.config);
|
||||
const out = ssr ? settings.config.build.server : getOutDirWithinCwd(settings.config.outDir);
|
||||
const routes = Object.values(allPages).map((pd) => pd.route);
|
||||
const { lastVitePlugins, vitePlugins } = container.runBeforeHook("ssr", input);
|
||||
const viteBuildConfig = {
|
||||
...viteConfig,
|
||||
mode: viteConfig.mode || "production",
|
||||
logLevel: opts.viteConfig.logLevel ?? "error",
|
||||
build: {
|
||||
target: "esnext",
|
||||
// Vite defaults cssMinify to false in SSR by default, but we want to minify it
|
||||
// as the CSS generated are used and served to the client.
|
||||
cssMinify: ((_a = viteConfig.build) == null ? void 0 : _a.minify) == null ? true : !!((_b = viteConfig.build) == null ? void 0 : _b.minify),
|
||||
...viteConfig.build,
|
||||
emptyOutDir: false,
|
||||
manifest: false,
|
||||
outDir: fileURLToPath(out),
|
||||
copyPublicDir: !ssr,
|
||||
rollupOptions: {
|
||||
...(_c = viteConfig.build) == null ? void 0 : _c.rollupOptions,
|
||||
input: [],
|
||||
output: {
|
||||
format: "esm",
|
||||
// Server chunks can't go in the assets (_astro) folder
|
||||
// We need to keep these separate
|
||||
chunkFileNames: `chunks/[name].[hash].mjs`,
|
||||
assetFileNames: `${settings.config.build.assets}/[name].[hash][extname]`,
|
||||
...(_e = (_d = viteConfig.build) == null ? void 0 : _d.rollupOptions) == null ? void 0 : _e.output,
|
||||
entryFileNames(chunkInfo) {
|
||||
var _a2, _b2;
|
||||
if ((_a2 = chunkInfo.facadeModuleId) == null ? void 0 : _a2.startsWith(ASTRO_PAGE_RESOLVED_MODULE_ID)) {
|
||||
return makeAstroPageEntryPointFileName(
|
||||
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
||||
chunkInfo.facadeModuleId,
|
||||
routes
|
||||
);
|
||||
} else if ((_b2 = chunkInfo.facadeModuleId) == null ? void 0 : _b2.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
|
||||
return makeSplitEntryPointFileName(chunkInfo.facadeModuleId, routes);
|
||||
} else if (chunkInfo.facadeModuleId === SSR_VIRTUAL_MODULE_ID) {
|
||||
return opts.settings.config.build.serverEntry;
|
||||
} else if (chunkInfo.facadeModuleId === RESOLVED_RENDERERS_MODULE_ID) {
|
||||
return "renderers.mjs";
|
||||
} else {
|
||||
return "[name].mjs";
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ssr: true,
|
||||
ssrEmitAssets: true,
|
||||
// improve build performance
|
||||
minify: false,
|
||||
modulePreload: { polyfill: false },
|
||||
reportCompressedSize: false
|
||||
},
|
||||
plugins: [...vitePlugins, ...viteConfig.plugins || [], ...lastVitePlugins],
|
||||
envPrefix: viteConfig.envPrefix ?? "PUBLIC_",
|
||||
base: settings.config.base
|
||||
};
|
||||
const updatedViteBuildConfig = await runHookBuildSetup({
|
||||
config: settings.config,
|
||||
pages: internals.pagesByComponent,
|
||||
vite: viteBuildConfig,
|
||||
target: "server",
|
||||
logging: opts.logging
|
||||
});
|
||||
return await vite.build(updatedViteBuildConfig);
|
||||
}
|
||||
async function clientBuild(opts, internals, input, container) {
|
||||
var _a, _b, _c;
|
||||
const { settings, viteConfig } = opts;
|
||||
const timer = performance.now();
|
||||
const ssr = isServerLikeOutput(settings.config);
|
||||
const out = ssr ? settings.config.build.client : getOutDirWithinCwd(settings.config.outDir);
|
||||
if (!input.size) {
|
||||
if (ssr) {
|
||||
await copyFiles(settings.config.publicDir, out, true);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const { lastVitePlugins, vitePlugins } = container.runBeforeHook("client", input);
|
||||
info(opts.logging, null, `
|
||||
${bgGreen(black(" building client "))}`);
|
||||
const viteBuildConfig = {
|
||||
...viteConfig,
|
||||
mode: viteConfig.mode || "production",
|
||||
logLevel: "info",
|
||||
build: {
|
||||
target: "esnext",
|
||||
...viteConfig.build,
|
||||
emptyOutDir: false,
|
||||
outDir: fileURLToPath(out),
|
||||
rollupOptions: {
|
||||
...(_a = viteConfig.build) == null ? void 0 : _a.rollupOptions,
|
||||
input: Array.from(input),
|
||||
output: {
|
||||
format: "esm",
|
||||
entryFileNames: `${settings.config.build.assets}/[name].[hash].js`,
|
||||
chunkFileNames: `${settings.config.build.assets}/[name].[hash].js`,
|
||||
assetFileNames: `${settings.config.build.assets}/[name].[hash][extname]`,
|
||||
...(_c = (_b = viteConfig.build) == null ? void 0 : _b.rollupOptions) == null ? void 0 : _c.output
|
||||
},
|
||||
preserveEntrySignatures: "exports-only"
|
||||
}
|
||||
},
|
||||
plugins: [...vitePlugins, ...viteConfig.plugins || [], ...lastVitePlugins],
|
||||
envPrefix: viteConfig.envPrefix ?? "PUBLIC_",
|
||||
base: settings.config.base
|
||||
};
|
||||
await runHookBuildSetup({
|
||||
config: settings.config,
|
||||
pages: internals.pagesByComponent,
|
||||
vite: viteBuildConfig,
|
||||
target: "client",
|
||||
logging: opts.logging
|
||||
});
|
||||
const buildResult = await vite.build(viteBuildConfig);
|
||||
info(opts.logging, null, dim(`Completed in ${getTimeStat(timer, performance.now())}.
|
||||
`));
|
||||
return buildResult;
|
||||
}
|
||||
async function runPostBuildHooks(container, ssrReturn, clientReturn) {
|
||||
const mutations = await container.runPostHook(ssrReturn, clientReturn);
|
||||
const config = container.options.settings.config;
|
||||
const build = container.options.settings.config.build;
|
||||
for (const [fileName, mutation] of mutations) {
|
||||
const root = isServerLikeOutput(config) ? mutation.build === "server" ? build.server : build.client : config.outDir;
|
||||
const fileURL = new URL(fileName, root);
|
||||
await fs.promises.mkdir(new URL("./", fileURL), { recursive: true });
|
||||
await fs.promises.writeFile(fileURL, mutation.code, "utf-8");
|
||||
}
|
||||
}
|
||||
async function cleanStaticOutput(opts, internals) {
|
||||
const allStaticFiles = /* @__PURE__ */ new Set();
|
||||
for (const pageData of eachPageData(internals)) {
|
||||
if (pageData.route.prerender)
|
||||
allStaticFiles.add(internals.pageToBundleMap.get(pageData.moduleSpecifier));
|
||||
}
|
||||
const ssr = isServerLikeOutput(opts.settings.config);
|
||||
const out = ssr ? opts.settings.config.build.server : getOutDirWithinCwd(opts.settings.config.outDir);
|
||||
const files = await glob("**/*.mjs", {
|
||||
cwd: fileURLToPath(out)
|
||||
});
|
||||
if (files.length) {
|
||||
await eslexer.init;
|
||||
await Promise.all(
|
||||
files.map(async (filename) => {
|
||||
if (!allStaticFiles.has(filename)) {
|
||||
return;
|
||||
}
|
||||
const url = new URL(filename, out);
|
||||
const text = await fs.promises.readFile(url, { encoding: "utf8" });
|
||||
const [, exports] = eslexer.parse(text);
|
||||
let value = "const noop = () => {};";
|
||||
for (const e of exports) {
|
||||
value += `
|
||||
export const ${e.n} = noop;`;
|
||||
}
|
||||
await fs.promises.writeFile(url, value, { encoding: "utf8" });
|
||||
})
|
||||
);
|
||||
removeEmptyDirs(out);
|
||||
}
|
||||
}
|
||||
async function cleanServerOutput(opts) {
|
||||
const out = getOutDirWithinCwd(opts.settings.config.outDir);
|
||||
const files = await glob("**/*.mjs", {
|
||||
cwd: fileURLToPath(out)
|
||||
});
|
||||
if (files.length) {
|
||||
await Promise.all(
|
||||
files.map(async (filename) => {
|
||||
const url = new URL(filename, out);
|
||||
await fs.promises.rm(url);
|
||||
})
|
||||
);
|
||||
removeEmptyDirs(out);
|
||||
}
|
||||
if (out.toString() !== opts.settings.config.outDir.toString()) {
|
||||
await copyFiles(out, opts.settings.config.outDir);
|
||||
await fs.promises.rm(out, { recursive: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
async function copyFiles(fromFolder, toFolder, includeDotfiles = false) {
|
||||
const files = await glob("**/*", {
|
||||
cwd: fileURLToPath(fromFolder),
|
||||
dot: includeDotfiles
|
||||
});
|
||||
await Promise.all(
|
||||
files.map(async (filename) => {
|
||||
const from = new URL(filename, fromFolder);
|
||||
const to = new URL(filename, toFolder);
|
||||
const lastFolder = new URL("./", to);
|
||||
return fs.promises.mkdir(lastFolder, { recursive: true }).then(() => fs.promises.copyFile(from, to));
|
||||
})
|
||||
);
|
||||
}
|
||||
async function ssrMoveAssets(opts) {
|
||||
info(opts.logging, "build", "Rearranging server assets...");
|
||||
const serverRoot = opts.settings.config.output === "static" ? opts.settings.config.build.client : opts.settings.config.build.server;
|
||||
const clientRoot = opts.settings.config.build.client;
|
||||
const assets = opts.settings.config.build.assets;
|
||||
const serverAssets = new URL(`./${assets}/`, appendForwardSlash(serverRoot.toString()));
|
||||
const clientAssets = new URL(`./${assets}/`, appendForwardSlash(clientRoot.toString()));
|
||||
const files = await glob(`**/*`, {
|
||||
cwd: fileURLToPath(serverAssets)
|
||||
});
|
||||
if (files.length > 0) {
|
||||
await Promise.all(
|
||||
files.map(async (filename) => {
|
||||
const currentUrl = new URL(filename, appendForwardSlash(serverAssets.toString()));
|
||||
const clientUrl = new URL(filename, appendForwardSlash(clientAssets.toString()));
|
||||
const dir = new URL(path.parse(clientUrl.href).dir);
|
||||
if (!fs.existsSync(dir))
|
||||
await fs.promises.mkdir(dir, { recursive: true });
|
||||
return fs.promises.rename(currentUrl, clientUrl);
|
||||
})
|
||||
);
|
||||
removeEmptyDirs(serverAssets);
|
||||
}
|
||||
}
|
||||
function makeAstroPageEntryPointFileName(prefix, facadeModuleId, routes) {
|
||||
const pageModuleId = facadeModuleId.replace(prefix, "").replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".");
|
||||
let route = routes.find((routeData) => {
|
||||
return routeData.route === pageModuleId;
|
||||
});
|
||||
let name = pageModuleId;
|
||||
if (route) {
|
||||
name = route.route;
|
||||
}
|
||||
if (name.endsWith("/"))
|
||||
name += "index";
|
||||
const fileName = `${name.replaceAll("[", "_").replaceAll("]", "_").replaceAll("...", "---")}.mjs`;
|
||||
if (name.startsWith("..")) {
|
||||
return `pages${fileName}`;
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
function makeSplitEntryPointFileName(facadeModuleId, routes) {
|
||||
const filePath = `${makeAstroPageEntryPointFileName(
|
||||
RESOLVED_SPLIT_MODULE_ID,
|
||||
facadeModuleId,
|
||||
routes
|
||||
)}`;
|
||||
const pathComponents = filePath.split(path.sep);
|
||||
const lastPathComponent = pathComponents.pop();
|
||||
if (lastPathComponent) {
|
||||
const extension = extname(lastPathComponent);
|
||||
if (extension.length > 0) {
|
||||
const newFileName = `entry.${lastPathComponent}`;
|
||||
return [...pathComponents, newFileName].join(path.sep);
|
||||
}
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
export {
|
||||
makeAstroPageEntryPointFileName,
|
||||
makeSplitEntryPointFileName,
|
||||
staticBuild,
|
||||
viteBuild
|
||||
};
|
61
node_modules/astro/dist/core/build/types.d.ts
generated
vendored
Normal file
61
node_modules/astro/dist/core/build/types.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,61 @@
|
|||
import type { default as vite, InlineConfig } from 'vite';
|
||||
import type { AstroConfig, AstroSettings, ComponentInstance, ManifestData, MiddlewareHandler, RouteData, RuntimeMode, SSRLoadedRenderer } from '../../@types/astro';
|
||||
import type { LogOptions } from '../logger/core';
|
||||
import type { RouteCache } from '../render/route-cache';
|
||||
export type ComponentPath = string;
|
||||
export type ViteID = string;
|
||||
export type PageOutput = AstroConfig['output'];
|
||||
export type StylesheetAsset = {
|
||||
type: 'inline';
|
||||
content: string;
|
||||
} | {
|
||||
type: 'external';
|
||||
src: string;
|
||||
};
|
||||
export interface PageBuildData {
|
||||
component: ComponentPath;
|
||||
route: RouteData;
|
||||
moduleSpecifier: string;
|
||||
propagatedStyles: Map<string, Set<StylesheetAsset>>;
|
||||
propagatedScripts: Map<string, Set<string>>;
|
||||
hoistedScript: {
|
||||
type: 'inline' | 'external';
|
||||
value: string;
|
||||
} | undefined;
|
||||
styles: Array<{
|
||||
depth: number;
|
||||
order: number;
|
||||
sheet: StylesheetAsset;
|
||||
}>;
|
||||
}
|
||||
export type AllPagesData = Record<ComponentPath, PageBuildData>;
|
||||
/** Options for the static build */
|
||||
export interface StaticBuildOptions {
|
||||
allPages: AllPagesData;
|
||||
settings: AstroSettings;
|
||||
logging: LogOptions;
|
||||
manifest: ManifestData;
|
||||
mode: RuntimeMode;
|
||||
origin: string;
|
||||
pageNames: string[];
|
||||
routeCache: RouteCache;
|
||||
viteConfig: InlineConfig;
|
||||
teardownCompiler: boolean;
|
||||
}
|
||||
type ImportComponentInstance = () => Promise<ComponentInstance>;
|
||||
export interface SinglePageBuiltModule {
|
||||
page: ImportComponentInstance;
|
||||
/**
|
||||
* The `onRequest` hook exported by the middleware
|
||||
*/
|
||||
onRequest?: MiddlewareHandler<unknown>;
|
||||
renderers: SSRLoadedRenderer[];
|
||||
}
|
||||
export type ViteBuildReturn = Awaited<ReturnType<typeof vite.build>>;
|
||||
export type RollupOutput = Extract<Extract<ViteBuildReturn, Exclude<ViteBuildReturn, Array<any>>>, {
|
||||
output: any;
|
||||
}>;
|
||||
export type OutputChunk = Extract<RollupOutput['output'][number], {
|
||||
type: 'chunk';
|
||||
}>;
|
||||
export {};
|
0
node_modules/astro/dist/core/build/types.js
generated
vendored
Normal file
0
node_modules/astro/dist/core/build/types.js
generated
vendored
Normal file
1
node_modules/astro/dist/core/build/util.d.ts
generated
vendored
Normal file
1
node_modules/astro/dist/core/build/util.d.ts
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
export declare function getTimeStat(timeStart: number, timeEnd: number): string;
|
7
node_modules/astro/dist/core/build/util.js
generated
vendored
Normal file
7
node_modules/astro/dist/core/build/util.js
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
function getTimeStat(timeStart, timeEnd) {
|
||||
const buildTime = timeEnd - timeStart;
|
||||
return buildTime < 750 ? `${Math.round(buildTime)}ms` : `${(buildTime / 1e3).toFixed(2)}s`;
|
||||
}
|
||||
export {
|
||||
getTimeStat
|
||||
};
|
4
node_modules/astro/dist/core/client-directive/build.d.ts
generated
vendored
Normal file
4
node_modules/astro/dist/core/client-directive/build.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
/**
|
||||
* Build a client directive entrypoint into code that can directly run in a `<script>` tag.
|
||||
*/
|
||||
export declare function buildClientDirectiveEntrypoint(name: string, entrypoint: string): Promise<string>;
|
28
node_modules/astro/dist/core/client-directive/build.js
generated
vendored
Normal file
28
node_modules/astro/dist/core/client-directive/build.js
generated
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
import { build } from "esbuild";
|
||||
async function buildClientDirectiveEntrypoint(name, entrypoint) {
|
||||
var _a;
|
||||
const stringifiedName = JSON.stringify(name);
|
||||
const stringifiedEntrypoint = JSON.stringify(entrypoint);
|
||||
const output = await build({
|
||||
stdin: {
|
||||
contents: `import directive from ${stringifiedEntrypoint};
|
||||
|
||||
(self.Astro || (self.Astro = {}))[${stringifiedName}] = directive;
|
||||
|
||||
window.dispatchEvent(new Event('astro:' + ${stringifiedName}));`,
|
||||
resolveDir: process.cwd()
|
||||
},
|
||||
absWorkingDir: process.cwd(),
|
||||
format: "iife",
|
||||
minify: true,
|
||||
bundle: true,
|
||||
write: false
|
||||
});
|
||||
const outputFile = (_a = output.outputFiles) == null ? void 0 : _a[0];
|
||||
if (!outputFile)
|
||||
return "";
|
||||
return outputFile.text;
|
||||
}
|
||||
export {
|
||||
buildClientDirectiveEntrypoint
|
||||
};
|
1
node_modules/astro/dist/core/client-directive/default.d.ts
generated
vendored
Normal file
1
node_modules/astro/dist/core/client-directive/default.d.ts
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
export declare function getDefaultClientDirectives(): Map<string, string>;
|
17
node_modules/astro/dist/core/client-directive/default.js
generated
vendored
Normal file
17
node_modules/astro/dist/core/client-directive/default.js
generated
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import idlePrebuilt from "../../runtime/client/idle.prebuilt.js";
|
||||
import loadPrebuilt from "../../runtime/client/load.prebuilt.js";
|
||||
import mediaPrebuilt from "../../runtime/client/media.prebuilt.js";
|
||||
import onlyPrebuilt from "../../runtime/client/only.prebuilt.js";
|
||||
import visiblePrebuilt from "../../runtime/client/visible.prebuilt.js";
|
||||
function getDefaultClientDirectives() {
|
||||
return /* @__PURE__ */ new Map([
|
||||
["idle", idlePrebuilt],
|
||||
["load", loadPrebuilt],
|
||||
["media", mediaPrebuilt],
|
||||
["only", onlyPrebuilt],
|
||||
["visible", visiblePrebuilt]
|
||||
]);
|
||||
}
|
||||
export {
|
||||
getDefaultClientDirectives
|
||||
};
|
2
node_modules/astro/dist/core/client-directive/index.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/core/client-directive/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
export { buildClientDirectiveEntrypoint } from './build.js';
|
||||
export { getDefaultClientDirectives } from './default.js';
|
6
node_modules/astro/dist/core/client-directive/index.js
generated
vendored
Normal file
6
node_modules/astro/dist/core/client-directive/index.js
generated
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
import { buildClientDirectiveEntrypoint } from "./build.js";
|
||||
import { getDefaultClientDirectives } from "./default.js";
|
||||
export {
|
||||
buildClientDirectiveEntrypoint,
|
||||
getDefaultClientDirectives
|
||||
};
|
6
node_modules/astro/dist/core/compile/cache.d.ts
generated
vendored
Normal file
6
node_modules/astro/dist/core/compile/cache.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
import type { AstroConfig } from '../../@types/astro';
|
||||
import { type CompileProps, type CompileResult } from './compile.js';
|
||||
export declare function isCached(config: AstroConfig, filename: string): boolean;
|
||||
export declare function getCachedCompileResult(config: AstroConfig, filename: string): CompileResult | null;
|
||||
export declare function invalidateCompilation(config: AstroConfig, filename: string): void;
|
||||
export declare function cachedCompilation(props: CompileProps): Promise<CompileResult>;
|
38
node_modules/astro/dist/core/compile/cache.js
generated
vendored
Normal file
38
node_modules/astro/dist/core/compile/cache.js
generated
vendored
Normal file
|
@ -0,0 +1,38 @@
|
|||
import { compile } from "./compile.js";
|
||||
const configCache = /* @__PURE__ */ new WeakMap();
|
||||
function isCached(config, filename) {
|
||||
return configCache.has(config) && configCache.get(config).has(filename);
|
||||
}
|
||||
function getCachedCompileResult(config, filename) {
|
||||
if (!isCached(config, filename))
|
||||
return null;
|
||||
return configCache.get(config).get(filename);
|
||||
}
|
||||
function invalidateCompilation(config, filename) {
|
||||
if (configCache.has(config)) {
|
||||
const cache = configCache.get(config);
|
||||
cache.delete(filename);
|
||||
}
|
||||
}
|
||||
async function cachedCompilation(props) {
|
||||
const { astroConfig, filename } = props;
|
||||
let cache;
|
||||
if (!configCache.has(astroConfig)) {
|
||||
cache = /* @__PURE__ */ new Map();
|
||||
configCache.set(astroConfig, cache);
|
||||
} else {
|
||||
cache = configCache.get(astroConfig);
|
||||
}
|
||||
if (cache.has(filename)) {
|
||||
return cache.get(filename);
|
||||
}
|
||||
const compileResult = await compile(props);
|
||||
cache.set(filename, compileResult);
|
||||
return compileResult;
|
||||
}
|
||||
export {
|
||||
cachedCompilation,
|
||||
getCachedCompileResult,
|
||||
invalidateCompilation,
|
||||
isCached
|
||||
};
|
14
node_modules/astro/dist/core/compile/compile.d.ts
generated
vendored
Normal file
14
node_modules/astro/dist/core/compile/compile.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,14 @@
|
|||
import type { TransformResult } from '@astrojs/compiler';
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
import type { AstroConfig } from '../../@types/astro';
|
||||
export interface CompileProps {
|
||||
astroConfig: AstroConfig;
|
||||
viteConfig: ResolvedConfig;
|
||||
filename: string;
|
||||
source: string;
|
||||
}
|
||||
export interface CompileResult extends TransformResult {
|
||||
cssDeps: Set<string>;
|
||||
source: string;
|
||||
}
|
||||
export declare function compile({ astroConfig, viteConfig, filename, source, }: CompileProps): Promise<CompileResult>;
|
92
node_modules/astro/dist/core/compile/compile.js
generated
vendored
Normal file
92
node_modules/astro/dist/core/compile/compile.js
generated
vendored
Normal file
|
@ -0,0 +1,92 @@
|
|||
import { transform } from "@astrojs/compiler";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { normalizePath } from "vite";
|
||||
import { AggregateError, CompilerError } from "../errors/errors.js";
|
||||
import { AstroErrorData } from "../errors/index.js";
|
||||
import { resolvePath } from "../util.js";
|
||||
import { createStylePreprocessor } from "./style.js";
|
||||
async function compile({
|
||||
astroConfig,
|
||||
viteConfig,
|
||||
filename,
|
||||
source
|
||||
}) {
|
||||
const cssDeps = /* @__PURE__ */ new Set();
|
||||
const cssTransformErrors = [];
|
||||
let transformResult;
|
||||
try {
|
||||
transformResult = await transform(source, {
|
||||
compact: astroConfig.compressHTML,
|
||||
filename,
|
||||
normalizedFilename: normalizeFilename(filename, astroConfig.root),
|
||||
sourcemap: "both",
|
||||
internalURL: "astro/server/index.js",
|
||||
astroGlobalArgs: JSON.stringify(astroConfig.site),
|
||||
scopedStyleStrategy: astroConfig.scopedStyleStrategy,
|
||||
resultScopedSlot: true,
|
||||
preprocessStyle: createStylePreprocessor({
|
||||
filename,
|
||||
viteConfig,
|
||||
cssDeps,
|
||||
cssTransformErrors
|
||||
}),
|
||||
async resolvePath(specifier) {
|
||||
return resolvePath(specifier, filename);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
throw new CompilerError({
|
||||
...AstroErrorData.UnknownCompilerError,
|
||||
message: err.message ?? "Unknown compiler error",
|
||||
stack: err.stack,
|
||||
location: {
|
||||
file: filename
|
||||
}
|
||||
});
|
||||
}
|
||||
handleCompileResultErrors(transformResult, cssTransformErrors);
|
||||
return {
|
||||
...transformResult,
|
||||
cssDeps,
|
||||
source
|
||||
};
|
||||
}
|
||||
function handleCompileResultErrors(result, cssTransformErrors) {
|
||||
const compilerError = result.diagnostics.find((diag) => diag.severity === 1);
|
||||
if (compilerError) {
|
||||
throw new CompilerError({
|
||||
message: compilerError.text,
|
||||
location: {
|
||||
line: compilerError.location.line,
|
||||
column: compilerError.location.column,
|
||||
file: compilerError.location.file
|
||||
},
|
||||
hint: compilerError.hint
|
||||
});
|
||||
}
|
||||
switch (cssTransformErrors.length) {
|
||||
case 0:
|
||||
break;
|
||||
case 1: {
|
||||
throw cssTransformErrors[0];
|
||||
}
|
||||
default: {
|
||||
throw new AggregateError({
|
||||
...cssTransformErrors[0],
|
||||
errors: cssTransformErrors
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
function normalizeFilename(filename, root) {
|
||||
const normalizedFilename = normalizePath(filename);
|
||||
const normalizedRoot = normalizePath(fileURLToPath(root));
|
||||
if (normalizedFilename.startsWith(normalizedRoot)) {
|
||||
return normalizedFilename.slice(normalizedRoot.length - 1);
|
||||
} else {
|
||||
return normalizedFilename;
|
||||
}
|
||||
}
|
||||
export {
|
||||
compile
|
||||
};
|
3
node_modules/astro/dist/core/compile/index.d.ts
generated
vendored
Normal file
3
node_modules/astro/dist/core/compile/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
export { cachedCompilation, getCachedCompileResult, invalidateCompilation, isCached, } from './cache.js';
|
||||
export type { CompileProps, CompileResult } from './compile';
|
||||
export type { TransformStyle } from './types';
|
12
node_modules/astro/dist/core/compile/index.js
generated
vendored
Normal file
12
node_modules/astro/dist/core/compile/index.js
generated
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import {
|
||||
cachedCompilation,
|
||||
getCachedCompileResult,
|
||||
invalidateCompilation,
|
||||
isCached
|
||||
} from "./cache.js";
|
||||
export {
|
||||
cachedCompilation,
|
||||
getCachedCompileResult,
|
||||
invalidateCompilation,
|
||||
isCached
|
||||
};
|
8
node_modules/astro/dist/core/compile/style.d.ts
generated
vendored
Normal file
8
node_modules/astro/dist/core/compile/style.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
import type { TransformOptions } from '@astrojs/compiler';
|
||||
import { type ResolvedConfig } from 'vite';
|
||||
export declare function createStylePreprocessor({ filename, viteConfig, cssDeps, cssTransformErrors, }: {
|
||||
filename: string;
|
||||
viteConfig: ResolvedConfig;
|
||||
cssDeps: Set<string>;
|
||||
cssTransformErrors: Error[];
|
||||
}): TransformOptions['preprocessStyle'];
|
83
node_modules/astro/dist/core/compile/style.js
generated
vendored
Normal file
83
node_modules/astro/dist/core/compile/style.js
generated
vendored
Normal file
|
@ -0,0 +1,83 @@
|
|||
import fs from "node:fs";
|
||||
import { preprocessCSS } from "vite";
|
||||
import { AstroErrorData, CSSError, positionAt } from "../errors/index.js";
|
||||
function createStylePreprocessor({
|
||||
filename,
|
||||
viteConfig,
|
||||
cssDeps,
|
||||
cssTransformErrors
|
||||
}) {
|
||||
return async (content, attrs) => {
|
||||
var _a;
|
||||
const lang = `.${(attrs == null ? void 0 : attrs.lang) || "css"}`.toLowerCase();
|
||||
const id = `${filename}?astro&type=style&lang${lang}`;
|
||||
try {
|
||||
const result = await preprocessCSS(content, id, viteConfig);
|
||||
(_a = result.deps) == null ? void 0 : _a.forEach((dep) => {
|
||||
cssDeps.add(dep);
|
||||
});
|
||||
let map;
|
||||
if (result.map) {
|
||||
if (typeof result.map === "string") {
|
||||
map = result.map;
|
||||
} else if (result.map.mappings) {
|
||||
map = result.map.toString();
|
||||
}
|
||||
}
|
||||
return { code: result.code, map };
|
||||
} catch (err) {
|
||||
try {
|
||||
err = enhanceCSSError(err, filename, content);
|
||||
} catch {
|
||||
}
|
||||
cssTransformErrors.push(err);
|
||||
return { error: err + "" };
|
||||
}
|
||||
};
|
||||
}
|
||||
function enhanceCSSError(err, filename, cssContent) {
|
||||
const fileContent = fs.readFileSync(filename).toString();
|
||||
const styleTagBeginning = fileContent.indexOf(cssContent);
|
||||
if (err.name === "CssSyntaxError") {
|
||||
const errorLine = positionAt(styleTagBeginning, fileContent).line + (err.line ?? 0);
|
||||
return new CSSError({
|
||||
...AstroErrorData.CSSSyntaxError,
|
||||
message: err.reason,
|
||||
location: {
|
||||
file: filename,
|
||||
line: errorLine,
|
||||
column: err.column
|
||||
},
|
||||
stack: err.stack
|
||||
});
|
||||
}
|
||||
if (err.line && err.column) {
|
||||
const errorLine = positionAt(styleTagBeginning, fileContent).line + (err.line ?? 0);
|
||||
return new CSSError({
|
||||
...AstroErrorData.UnknownCSSError,
|
||||
message: err.message,
|
||||
location: {
|
||||
file: filename,
|
||||
line: errorLine,
|
||||
column: err.column
|
||||
},
|
||||
frame: err.frame,
|
||||
stack: err.stack
|
||||
});
|
||||
}
|
||||
const errorPosition = positionAt(styleTagBeginning, fileContent);
|
||||
errorPosition.line += 1;
|
||||
return new CSSError({
|
||||
message: err.message,
|
||||
location: {
|
||||
file: filename,
|
||||
line: errorPosition.line,
|
||||
column: 0
|
||||
},
|
||||
frame: err.frame,
|
||||
stack: err.stack
|
||||
});
|
||||
}
|
||||
export {
|
||||
createStylePreprocessor
|
||||
};
|
7
node_modules/astro/dist/core/compile/types.d.ts
generated
vendored
Normal file
7
node_modules/astro/dist/core/compile/types.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
import type { SourceMap } from 'rollup';
|
||||
export type TransformStyleResult = null | {
|
||||
code: string;
|
||||
map: SourceMap | null;
|
||||
deps: Set<string>;
|
||||
};
|
||||
export type TransformStyle = (source: string, lang: string) => TransformStyleResult | Promise<TransformStyleResult>;
|
0
node_modules/astro/dist/core/compile/types.js
generated
vendored
Normal file
0
node_modules/astro/dist/core/compile/types.js
generated
vendored
Normal file
40
node_modules/astro/dist/core/config/config.d.ts
generated
vendored
Normal file
40
node_modules/astro/dist/core/config/config.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,40 @@
|
|||
/// <reference types="node" />
|
||||
import type { Arguments as Flags } from 'yargs-parser';
|
||||
import type { AstroConfig, AstroUserConfig, CLIFlags } from '../../@types/astro';
|
||||
import fs from 'node:fs';
|
||||
export declare const LEGACY_ASTRO_CONFIG_KEYS: Set<string>;
|
||||
/** Turn raw config values into normalized values */
|
||||
export declare function validateConfig(userConfig: any, root: string, cmd: string): Promise<AstroConfig>;
|
||||
/** Convert the generic "yargs" flag object into our own, custom TypeScript object. */
|
||||
export declare function resolveFlags(flags: Partial<Flags>): CLIFlags;
|
||||
export declare function resolveRoot(cwd?: string | URL): string;
|
||||
interface LoadConfigOptions {
|
||||
cwd?: string;
|
||||
flags?: Flags;
|
||||
cmd: string;
|
||||
validate?: boolean;
|
||||
/** Invalidate when reloading a previously loaded config */
|
||||
isRestart?: boolean;
|
||||
fsMod?: typeof fs;
|
||||
}
|
||||
interface ResolveConfigPathOptions {
|
||||
cwd?: string;
|
||||
flags?: Flags;
|
||||
fs: typeof fs;
|
||||
}
|
||||
/**
|
||||
* Resolve the file URL of the user's `astro.config.js|cjs|mjs|ts` file
|
||||
*/
|
||||
export declare function resolveConfigPath(configOptions: ResolveConfigPathOptions): Promise<string | undefined>;
|
||||
interface OpenConfigResult {
|
||||
userConfig: AstroUserConfig;
|
||||
astroConfig: AstroConfig;
|
||||
flags: CLIFlags;
|
||||
root: string;
|
||||
}
|
||||
/** Load a configuration file, returning both the userConfig and astroConfig */
|
||||
export declare function openConfig(configOptions: LoadConfigOptions): Promise<OpenConfigResult>;
|
||||
/** Attempt to resolve an Astro configuration object. Normalize, validate, and return. */
|
||||
export declare function resolveConfig(userConfig: AstroUserConfig, root: string, flags: CLIFlags | undefined, cmd: string): Promise<AstroConfig>;
|
||||
export declare function createDefaultDevConfig(userConfig?: AstroUserConfig, root?: string): Promise<AstroConfig>;
|
||||
export {};
|
178
node_modules/astro/dist/core/config/config.js
generated
vendored
Normal file
178
node_modules/astro/dist/core/config/config.js
generated
vendored
Normal file
|
@ -0,0 +1,178 @@
|
|||
import * as colors from "kleur/colors";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { AstroError, AstroErrorData } from "../errors/index.js";
|
||||
import { mergeConfig } from "./merge.js";
|
||||
import { createRelativeSchema } from "./schema.js";
|
||||
import { loadConfigWithVite } from "./vite-load.js";
|
||||
const LEGACY_ASTRO_CONFIG_KEYS = /* @__PURE__ */ new Set([
|
||||
"projectRoot",
|
||||
"src",
|
||||
"pages",
|
||||
"public",
|
||||
"dist",
|
||||
"styleOptions",
|
||||
"markdownOptions",
|
||||
"buildOptions",
|
||||
"devOptions"
|
||||
]);
|
||||
async function validateConfig(userConfig, root, cmd) {
|
||||
const fileProtocolRoot = pathToFileURL(root + path.sep);
|
||||
if (userConfig.hasOwnProperty("renderers")) {
|
||||
console.error('Astro "renderers" are now "integrations"!');
|
||||
console.error("Update your configuration and install new dependencies:");
|
||||
try {
|
||||
const rendererKeywords = userConfig.renderers.map(
|
||||
(r) => r.replace("@astrojs/renderer-", "")
|
||||
);
|
||||
const rendererImports = rendererKeywords.map((r) => ` import ${r} from '@astrojs/${r === "solid" ? "solid-js" : r}';`).join("\n");
|
||||
const rendererIntegrations = rendererKeywords.map((r) => ` ${r}(),`).join("\n");
|
||||
console.error("");
|
||||
console.error(colors.dim(" // astro.config.js"));
|
||||
if (rendererImports.length > 0) {
|
||||
console.error(colors.green(rendererImports));
|
||||
}
|
||||
console.error("");
|
||||
console.error(colors.dim(" // ..."));
|
||||
if (rendererIntegrations.length > 0) {
|
||||
console.error(colors.green(" integrations: ["));
|
||||
console.error(colors.green(rendererIntegrations));
|
||||
console.error(colors.green(" ],"));
|
||||
} else {
|
||||
console.error(colors.green(" integrations: [],"));
|
||||
}
|
||||
console.error("");
|
||||
} catch (err) {
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
let legacyConfigKey;
|
||||
for (const key of Object.keys(userConfig)) {
|
||||
if (LEGACY_ASTRO_CONFIG_KEYS.has(key)) {
|
||||
legacyConfigKey = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (legacyConfigKey) {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.ConfigLegacyKey,
|
||||
message: AstroErrorData.ConfigLegacyKey.message(legacyConfigKey)
|
||||
});
|
||||
}
|
||||
const AstroConfigRelativeSchema = createRelativeSchema(cmd, fileProtocolRoot);
|
||||
const result = await AstroConfigRelativeSchema.parseAsync(userConfig);
|
||||
return result;
|
||||
}
|
||||
function resolveFlags(flags) {
|
||||
return {
|
||||
root: typeof flags.root === "string" ? flags.root : void 0,
|
||||
site: typeof flags.site === "string" ? flags.site : void 0,
|
||||
base: typeof flags.base === "string" ? flags.base : void 0,
|
||||
port: typeof flags.port === "number" ? flags.port : void 0,
|
||||
open: typeof flags.open === "boolean" ? flags.open : void 0,
|
||||
config: typeof flags.config === "string" ? flags.config : void 0,
|
||||
host: typeof flags.host === "string" || typeof flags.host === "boolean" ? flags.host : void 0,
|
||||
drafts: typeof flags.drafts === "boolean" ? flags.drafts : void 0,
|
||||
experimentalAssets: typeof flags.experimentalAssets === "boolean" ? flags.experimentalAssets : void 0,
|
||||
experimentalRedirects: typeof flags.experimentalRedirects === "boolean" ? flags.experimentalRedirects : void 0
|
||||
};
|
||||
}
|
||||
function resolveRoot(cwd) {
|
||||
if (cwd instanceof URL) {
|
||||
cwd = fileURLToPath(cwd);
|
||||
}
|
||||
return cwd ? path.resolve(cwd) : process.cwd();
|
||||
}
|
||||
function mergeCLIFlags(astroConfig, flags) {
|
||||
return mergeConfig(astroConfig, {
|
||||
site: flags.site,
|
||||
base: flags.base,
|
||||
markdown: {
|
||||
drafts: flags.drafts
|
||||
},
|
||||
server: {
|
||||
port: flags.port,
|
||||
host: flags.host,
|
||||
open: flags.open
|
||||
}
|
||||
});
|
||||
}
|
||||
async function search(fsMod, root) {
|
||||
const paths = [
|
||||
"astro.config.mjs",
|
||||
"astro.config.js",
|
||||
"astro.config.ts",
|
||||
"astro.config.mts",
|
||||
"astro.config.cjs",
|
||||
"astro.config.cts"
|
||||
].map((p) => path.join(root, p));
|
||||
for (const file of paths) {
|
||||
if (fsMod.existsSync(file)) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function resolveConfigPath(configOptions) {
|
||||
const root = resolveRoot(configOptions.cwd);
|
||||
const flags = resolveFlags(configOptions.flags || {});
|
||||
let userConfigPath;
|
||||
if (flags == null ? void 0 : flags.config) {
|
||||
userConfigPath = /^\.*\//.test(flags.config) ? flags.config : `./${flags.config}`;
|
||||
userConfigPath = fileURLToPath(new URL(userConfigPath, `file://${root}/`));
|
||||
if (!configOptions.fs.existsSync(userConfigPath)) {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.ConfigNotFound,
|
||||
message: AstroErrorData.ConfigNotFound.message(flags.config)
|
||||
});
|
||||
}
|
||||
} else {
|
||||
userConfigPath = await search(configOptions.fs, root);
|
||||
}
|
||||
return userConfigPath;
|
||||
}
|
||||
async function openConfig(configOptions) {
|
||||
const root = resolveRoot(configOptions.cwd);
|
||||
const flags = resolveFlags(configOptions.flags || {});
|
||||
const userConfig = await loadConfig(configOptions, root);
|
||||
const astroConfig = await resolveConfig(userConfig, root, flags, configOptions.cmd);
|
||||
return {
|
||||
astroConfig,
|
||||
userConfig,
|
||||
flags,
|
||||
root
|
||||
};
|
||||
}
|
||||
async function loadConfig(configOptions, root) {
|
||||
const fsMod = configOptions.fsMod ?? fs;
|
||||
const configPath = await resolveConfigPath({
|
||||
cwd: configOptions.cwd,
|
||||
flags: configOptions.flags,
|
||||
fs: fsMod
|
||||
});
|
||||
if (!configPath)
|
||||
return {};
|
||||
return await loadConfigWithVite({
|
||||
configPath,
|
||||
fs: fsMod,
|
||||
root
|
||||
});
|
||||
}
|
||||
async function resolveConfig(userConfig, root, flags = {}, cmd) {
|
||||
const mergedConfig = mergeCLIFlags(userConfig, flags);
|
||||
const validatedConfig = await validateConfig(mergedConfig, root, cmd);
|
||||
return validatedConfig;
|
||||
}
|
||||
function createDefaultDevConfig(userConfig = {}, root = process.cwd()) {
|
||||
return resolveConfig(userConfig, root, void 0, "dev");
|
||||
}
|
||||
export {
|
||||
LEGACY_ASTRO_CONFIG_KEYS,
|
||||
createDefaultDevConfig,
|
||||
openConfig,
|
||||
resolveConfig,
|
||||
resolveConfigPath,
|
||||
resolveFlags,
|
||||
resolveRoot,
|
||||
validateConfig
|
||||
};
|
5
node_modules/astro/dist/core/config/index.d.ts
generated
vendored
Normal file
5
node_modules/astro/dist/core/config/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
export { createDefaultDevConfig, openConfig, resolveConfigPath, resolveFlags, resolveRoot, validateConfig, } from './config.js';
|
||||
export { mergeConfig } from './merge.js';
|
||||
export type { AstroConfigSchema } from './schema';
|
||||
export { createDefaultDevSettings, createSettings } from './settings.js';
|
||||
export { loadTSConfig, updateTSConfigForFramework } from './tsconfig.js';
|
24
node_modules/astro/dist/core/config/index.js
generated
vendored
Normal file
24
node_modules/astro/dist/core/config/index.js
generated
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import {
|
||||
createDefaultDevConfig,
|
||||
openConfig,
|
||||
resolveConfigPath,
|
||||
resolveFlags,
|
||||
resolveRoot,
|
||||
validateConfig
|
||||
} from "./config.js";
|
||||
import { mergeConfig } from "./merge.js";
|
||||
import { createDefaultDevSettings, createSettings } from "./settings.js";
|
||||
import { loadTSConfig, updateTSConfigForFramework } from "./tsconfig.js";
|
||||
export {
|
||||
createDefaultDevConfig,
|
||||
createDefaultDevSettings,
|
||||
createSettings,
|
||||
loadTSConfig,
|
||||
mergeConfig,
|
||||
openConfig,
|
||||
resolveConfigPath,
|
||||
resolveFlags,
|
||||
resolveRoot,
|
||||
updateTSConfigForFramework,
|
||||
validateConfig
|
||||
};
|
1
node_modules/astro/dist/core/config/merge.d.ts
generated
vendored
Normal file
1
node_modules/astro/dist/core/config/merge.d.ts
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
export declare function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>, isRoot?: boolean): Record<string, any>;
|
50
node_modules/astro/dist/core/config/merge.js
generated
vendored
Normal file
50
node_modules/astro/dist/core/config/merge.js
generated
vendored
Normal file
|
@ -0,0 +1,50 @@
|
|||
import { mergeConfig as mergeViteConfig } from "vite";
|
||||
import { arraify, isObject, isURL } from "../util.js";
|
||||
function mergeConfigRecursively(defaults, overrides, rootPath) {
|
||||
const merged = { ...defaults };
|
||||
for (const key in overrides) {
|
||||
const value = overrides[key];
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
const existing = merged[key];
|
||||
if (existing == null) {
|
||||
merged[key] = value;
|
||||
continue;
|
||||
}
|
||||
if (key === "vite" && rootPath === "") {
|
||||
merged[key] = mergeViteConfig(existing, value);
|
||||
continue;
|
||||
}
|
||||
if (key === "server" && rootPath === "") {
|
||||
if (typeof existing === "function" || typeof value === "function") {
|
||||
merged[key] = (...args) => {
|
||||
const existingConfig = typeof existing === "function" ? existing(...args) : existing;
|
||||
const valueConfig = typeof value === "function" ? value(...args) : value;
|
||||
return mergeConfigRecursively(existingConfig, valueConfig, key);
|
||||
};
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(existing) || Array.isArray(value)) {
|
||||
merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])];
|
||||
continue;
|
||||
}
|
||||
if (isURL(existing) && isURL(value)) {
|
||||
merged[key] = value;
|
||||
continue;
|
||||
}
|
||||
if (isObject(existing) && isObject(value)) {
|
||||
merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
|
||||
continue;
|
||||
}
|
||||
merged[key] = value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
function mergeConfig(defaults, overrides, isRoot = true) {
|
||||
return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
|
||||
}
|
||||
export {
|
||||
mergeConfig
|
||||
};
|
738
node_modules/astro/dist/core/config/schema.d.ts
generated
vendored
Normal file
738
node_modules/astro/dist/core/config/schema.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,738 @@
|
|||
/// <reference types="node" />
|
||||
import type { RehypePlugin, RemarkPlugin, RemarkRehype } from '@astrojs/markdown-remark';
|
||||
import type { ILanguageRegistration, IThemeRegistration, Theme } from 'shiki';
|
||||
import type { ViteUserConfig } from '../../@types/astro';
|
||||
import type { OutgoingHttpHeaders } from 'node:http';
|
||||
import { z } from 'zod';
|
||||
export declare const AstroConfigSchema: z.ZodObject<{
|
||||
root: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
srcDir: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
publicDir: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
outDir: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
cacheDir: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
site: z.ZodOptional<z.ZodString>;
|
||||
compressHTML: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
base: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
trailingSlash: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"always">, z.ZodLiteral<"never">, z.ZodLiteral<"ignore">]>>>;
|
||||
output: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"static">, z.ZodLiteral<"server">, z.ZodLiteral<"hybrid">]>>>;
|
||||
scopedStyleStrategy: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"where">, z.ZodLiteral<"class">]>>>;
|
||||
adapter: z.ZodOptional<z.ZodObject<{
|
||||
name: z.ZodString;
|
||||
hooks: z.ZodDefault<z.ZodObject<{}, "passthrough", z.ZodTypeAny, {}, {}>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}, {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
}>>;
|
||||
integrations: z.ZodEffects<z.ZodDefault<z.ZodArray<z.ZodObject<{
|
||||
name: z.ZodString;
|
||||
hooks: z.ZodDefault<z.ZodObject<{}, "passthrough", z.ZodTypeAny, {}, {}>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}, {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
}>, "many">>, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}[], unknown>;
|
||||
build: z.ZodDefault<z.ZodOptional<z.ZodObject<{
|
||||
format: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"file">, z.ZodLiteral<"directory">]>>>;
|
||||
client: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
server: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
assets: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
assetsPrefix: z.ZodOptional<z.ZodString>;
|
||||
serverEntry: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
redirects: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
inlineStylesheets: z.ZodDefault<z.ZodOptional<z.ZodEnum<["always", "auto", "never"]>>>;
|
||||
split: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
excludeMiddleware: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
assetsPrefix?: string | undefined;
|
||||
format: "file" | "directory";
|
||||
client: URL;
|
||||
server: URL;
|
||||
assets: string;
|
||||
serverEntry: string;
|
||||
redirects: boolean;
|
||||
inlineStylesheets: "always" | "never" | "auto";
|
||||
split: boolean;
|
||||
excludeMiddleware: boolean;
|
||||
}, {
|
||||
format?: "file" | "directory" | undefined;
|
||||
client?: string | undefined;
|
||||
server?: string | undefined;
|
||||
assets?: string | undefined;
|
||||
serverEntry?: string | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
inlineStylesheets?: "always" | "never" | "auto" | undefined;
|
||||
split?: boolean | undefined;
|
||||
excludeMiddleware?: boolean | undefined;
|
||||
assetsPrefix?: string | undefined;
|
||||
}>>>;
|
||||
server: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodObject<{
|
||||
open: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
host: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodBoolean]>>>;
|
||||
port: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
||||
headers: z.ZodOptional<z.ZodType<OutgoingHttpHeaders, z.ZodTypeDef, OutgoingHttpHeaders>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
}, {
|
||||
host?: string | boolean | undefined;
|
||||
port?: number | undefined;
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
open?: boolean | undefined;
|
||||
}>>>, {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
}, unknown>;
|
||||
redirects: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
|
||||
image: z.ZodDefault<z.ZodObject<{
|
||||
service: z.ZodObject<{
|
||||
entrypoint: z.ZodUnion<[z.ZodLiteral<"astro/assets/services/sharp">, z.ZodLiteral<"astro/assets/services/squoosh">, z.ZodString]>;
|
||||
config: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
}, {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
}>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
service: {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
};
|
||||
}, {
|
||||
service: {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
};
|
||||
}>>;
|
||||
markdown: z.ZodDefault<z.ZodObject<{
|
||||
drafts: z.ZodDefault<z.ZodBoolean>;
|
||||
syntaxHighlight: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"shiki">, z.ZodLiteral<"prism">, z.ZodLiteral<false>]>>;
|
||||
shikiConfig: z.ZodDefault<z.ZodObject<{
|
||||
langs: z.ZodDefault<z.ZodArray<z.ZodType<ILanguageRegistration, z.ZodTypeDef, ILanguageRegistration>, "many">>;
|
||||
theme: z.ZodDefault<z.ZodUnion<[z.ZodEnum<[Theme, ...Theme[]]>, z.ZodType<IThemeRegistration, z.ZodTypeDef, IThemeRegistration>]>>;
|
||||
wrap: z.ZodDefault<z.ZodUnion<[z.ZodBoolean, z.ZodNull]>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
}, {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
}>>;
|
||||
remarkPlugins: z.ZodDefault<z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodTuple<[z.ZodString, z.ZodAny], null>, z.ZodType<RemarkPlugin, z.ZodTypeDef, RemarkPlugin>, z.ZodTuple<[z.ZodType<RemarkPlugin, z.ZodTypeDef, RemarkPlugin>, z.ZodAny], null>]>, "many">>;
|
||||
rehypePlugins: z.ZodDefault<z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodTuple<[z.ZodString, z.ZodAny], null>, z.ZodType<RehypePlugin, z.ZodTypeDef, RehypePlugin>, z.ZodTuple<[z.ZodType<RehypePlugin, z.ZodTypeDef, RehypePlugin>, z.ZodAny], null>]>, "many">>;
|
||||
remarkRehype: z.ZodDefault<z.ZodOptional<z.ZodType<RemarkRehype, z.ZodTypeDef, RemarkRehype>>>;
|
||||
gfm: z.ZodDefault<z.ZodBoolean>;
|
||||
smartypants: z.ZodDefault<z.ZodBoolean>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
drafts: boolean;
|
||||
syntaxHighlight: false | "shiki" | "prism";
|
||||
shikiConfig: {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
};
|
||||
remarkPlugins: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
|
||||
rehypePlugins: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
|
||||
remarkRehype: RemarkRehype;
|
||||
gfm: boolean;
|
||||
smartypants: boolean;
|
||||
}, {
|
||||
drafts?: boolean | undefined;
|
||||
syntaxHighlight?: false | "shiki" | "prism" | undefined;
|
||||
shikiConfig?: {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
} | undefined;
|
||||
remarkPlugins?: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[] | undefined;
|
||||
rehypePlugins?: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[] | undefined;
|
||||
remarkRehype?: RemarkRehype | undefined;
|
||||
gfm?: boolean | undefined;
|
||||
smartypants?: boolean | undefined;
|
||||
}>>;
|
||||
vite: z.ZodDefault<z.ZodType<ViteUserConfig, z.ZodTypeDef, ViteUserConfig>>;
|
||||
experimental: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodObject<{
|
||||
assets: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
redirects: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
}, "passthrough", z.ZodTypeAny, {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
}, {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
}>, {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
}, {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
}>>>;
|
||||
legacy: z.ZodDefault<z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
site?: string | undefined;
|
||||
adapter?: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
} | undefined;
|
||||
output: "server" | "static" | "hybrid";
|
||||
server: {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
};
|
||||
redirects: Record<string, string>;
|
||||
root: URL;
|
||||
srcDir: URL;
|
||||
publicDir: URL;
|
||||
outDir: URL;
|
||||
cacheDir: URL;
|
||||
compressHTML: boolean;
|
||||
base: string;
|
||||
trailingSlash: "ignore" | "always" | "never";
|
||||
scopedStyleStrategy: "where" | "class";
|
||||
integrations: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}[];
|
||||
build: {
|
||||
assetsPrefix?: string | undefined;
|
||||
format: "file" | "directory";
|
||||
client: URL;
|
||||
server: URL;
|
||||
assets: string;
|
||||
serverEntry: string;
|
||||
redirects: boolean;
|
||||
inlineStylesheets: "always" | "never" | "auto";
|
||||
split: boolean;
|
||||
excludeMiddleware: boolean;
|
||||
};
|
||||
image: {
|
||||
service: {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
};
|
||||
};
|
||||
markdown: {
|
||||
drafts: boolean;
|
||||
syntaxHighlight: false | "shiki" | "prism";
|
||||
shikiConfig: {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
};
|
||||
remarkPlugins: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
|
||||
rehypePlugins: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
|
||||
remarkRehype: RemarkRehype;
|
||||
gfm: boolean;
|
||||
smartypants: boolean;
|
||||
};
|
||||
vite: ViteUserConfig;
|
||||
experimental: {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
};
|
||||
legacy: {};
|
||||
}, {
|
||||
output?: "server" | "static" | "hybrid" | undefined;
|
||||
server?: unknown;
|
||||
redirects?: Record<string, string> | undefined;
|
||||
root?: string | undefined;
|
||||
srcDir?: string | undefined;
|
||||
publicDir?: string | undefined;
|
||||
outDir?: string | undefined;
|
||||
cacheDir?: string | undefined;
|
||||
site?: string | undefined;
|
||||
compressHTML?: boolean | undefined;
|
||||
base?: string | undefined;
|
||||
trailingSlash?: "ignore" | "always" | "never" | undefined;
|
||||
scopedStyleStrategy?: "where" | "class" | undefined;
|
||||
adapter?: {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
} | undefined;
|
||||
integrations?: unknown;
|
||||
build?: {
|
||||
format?: "file" | "directory" | undefined;
|
||||
client?: string | undefined;
|
||||
server?: string | undefined;
|
||||
assets?: string | undefined;
|
||||
serverEntry?: string | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
inlineStylesheets?: "always" | "never" | "auto" | undefined;
|
||||
split?: boolean | undefined;
|
||||
excludeMiddleware?: boolean | undefined;
|
||||
assetsPrefix?: string | undefined;
|
||||
} | undefined;
|
||||
image?: {
|
||||
service: {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
};
|
||||
} | undefined;
|
||||
markdown?: {
|
||||
drafts?: boolean | undefined;
|
||||
syntaxHighlight?: false | "shiki" | "prism" | undefined;
|
||||
shikiConfig?: {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
} | undefined;
|
||||
remarkPlugins?: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[] | undefined;
|
||||
rehypePlugins?: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[] | undefined;
|
||||
remarkRehype?: RemarkRehype | undefined;
|
||||
gfm?: boolean | undefined;
|
||||
smartypants?: boolean | undefined;
|
||||
} | undefined;
|
||||
vite?: ViteUserConfig | undefined;
|
||||
experimental?: {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
} | undefined;
|
||||
legacy?: {} | undefined;
|
||||
}>;
|
||||
export declare function createRelativeSchema(cmd: string, fileProtocolRoot: URL): z.ZodEffects<z.ZodObject<{
|
||||
output: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"static">, z.ZodLiteral<"server">, z.ZodLiteral<"hybrid">]>>>;
|
||||
redirects: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
|
||||
site: z.ZodOptional<z.ZodString>;
|
||||
base: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
trailingSlash: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"always">, z.ZodLiteral<"never">, z.ZodLiteral<"ignore">]>>>;
|
||||
scopedStyleStrategy: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"where">, z.ZodLiteral<"class">]>>>;
|
||||
adapter: z.ZodOptional<z.ZodObject<{
|
||||
name: z.ZodString;
|
||||
hooks: z.ZodDefault<z.ZodObject<{}, "passthrough", z.ZodTypeAny, {}, {}>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}, {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
}>>;
|
||||
integrations: z.ZodEffects<z.ZodDefault<z.ZodArray<z.ZodObject<{
|
||||
name: z.ZodString;
|
||||
hooks: z.ZodDefault<z.ZodObject<{}, "passthrough", z.ZodTypeAny, {}, {}>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}, {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
}>, "many">>, {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}[], unknown>;
|
||||
image: z.ZodDefault<z.ZodObject<{
|
||||
service: z.ZodObject<{
|
||||
entrypoint: z.ZodUnion<[z.ZodLiteral<"astro/assets/services/sharp">, z.ZodLiteral<"astro/assets/services/squoosh">, z.ZodString]>;
|
||||
config: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
}, {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
}>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
service: {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
};
|
||||
}, {
|
||||
service: {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
};
|
||||
}>>;
|
||||
markdown: z.ZodDefault<z.ZodObject<{
|
||||
drafts: z.ZodDefault<z.ZodBoolean>;
|
||||
syntaxHighlight: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"shiki">, z.ZodLiteral<"prism">, z.ZodLiteral<false>]>>;
|
||||
shikiConfig: z.ZodDefault<z.ZodObject<{
|
||||
langs: z.ZodDefault<z.ZodArray<z.ZodType<ILanguageRegistration, z.ZodTypeDef, ILanguageRegistration>, "many">>;
|
||||
theme: z.ZodDefault<z.ZodUnion<[z.ZodEnum<[Theme, ...Theme[]]>, z.ZodType<IThemeRegistration, z.ZodTypeDef, IThemeRegistration>]>>;
|
||||
wrap: z.ZodDefault<z.ZodUnion<[z.ZodBoolean, z.ZodNull]>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
}, {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
}>>;
|
||||
remarkPlugins: z.ZodDefault<z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodTuple<[z.ZodString, z.ZodAny], null>, z.ZodType<RemarkPlugin, z.ZodTypeDef, RemarkPlugin>, z.ZodTuple<[z.ZodType<RemarkPlugin, z.ZodTypeDef, RemarkPlugin>, z.ZodAny], null>]>, "many">>;
|
||||
rehypePlugins: z.ZodDefault<z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodTuple<[z.ZodString, z.ZodAny], null>, z.ZodType<RehypePlugin, z.ZodTypeDef, RehypePlugin>, z.ZodTuple<[z.ZodType<RehypePlugin, z.ZodTypeDef, RehypePlugin>, z.ZodAny], null>]>, "many">>;
|
||||
remarkRehype: z.ZodDefault<z.ZodOptional<z.ZodType<RemarkRehype, z.ZodTypeDef, RemarkRehype>>>;
|
||||
gfm: z.ZodDefault<z.ZodBoolean>;
|
||||
smartypants: z.ZodDefault<z.ZodBoolean>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
drafts: boolean;
|
||||
syntaxHighlight: false | "shiki" | "prism";
|
||||
shikiConfig: {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
};
|
||||
remarkPlugins: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
|
||||
rehypePlugins: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
|
||||
remarkRehype: RemarkRehype;
|
||||
gfm: boolean;
|
||||
smartypants: boolean;
|
||||
}, {
|
||||
drafts?: boolean | undefined;
|
||||
syntaxHighlight?: false | "shiki" | "prism" | undefined;
|
||||
shikiConfig?: {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
} | undefined;
|
||||
remarkPlugins?: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[] | undefined;
|
||||
rehypePlugins?: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[] | undefined;
|
||||
remarkRehype?: RemarkRehype | undefined;
|
||||
gfm?: boolean | undefined;
|
||||
smartypants?: boolean | undefined;
|
||||
}>>;
|
||||
vite: z.ZodDefault<z.ZodType<ViteUserConfig, z.ZodTypeDef, ViteUserConfig>>;
|
||||
experimental: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodObject<{
|
||||
assets: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
redirects: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
}, "passthrough", z.ZodTypeAny, {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
}, {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
}>, {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
}, {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
}>>>;
|
||||
legacy: z.ZodDefault<z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>>>;
|
||||
root: z.ZodEffects<z.ZodDefault<z.ZodString>, URL, string | undefined>;
|
||||
srcDir: z.ZodEffects<z.ZodDefault<z.ZodString>, URL, string | undefined>;
|
||||
compressHTML: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
publicDir: z.ZodEffects<z.ZodDefault<z.ZodString>, URL, string | undefined>;
|
||||
outDir: z.ZodEffects<z.ZodDefault<z.ZodString>, URL, string | undefined>;
|
||||
cacheDir: z.ZodEffects<z.ZodDefault<z.ZodString>, URL, string | undefined>;
|
||||
build: z.ZodDefault<z.ZodOptional<z.ZodObject<{
|
||||
format: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodLiteral<"file">, z.ZodLiteral<"directory">]>>>;
|
||||
client: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
server: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodString>>, URL, string | undefined>;
|
||||
assets: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
assetsPrefix: z.ZodOptional<z.ZodString>;
|
||||
serverEntry: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
||||
redirects: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
inlineStylesheets: z.ZodDefault<z.ZodOptional<z.ZodEnum<["always", "auto", "never"]>>>;
|
||||
split: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
excludeMiddleware: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
assetsPrefix?: string | undefined;
|
||||
format: "file" | "directory";
|
||||
client: URL;
|
||||
server: URL;
|
||||
assets: string;
|
||||
serverEntry: string;
|
||||
redirects: boolean;
|
||||
inlineStylesheets: "always" | "never" | "auto";
|
||||
split: boolean;
|
||||
excludeMiddleware: boolean;
|
||||
}, {
|
||||
format?: "file" | "directory" | undefined;
|
||||
client?: string | undefined;
|
||||
server?: string | undefined;
|
||||
assets?: string | undefined;
|
||||
serverEntry?: string | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
inlineStylesheets?: "always" | "never" | "auto" | undefined;
|
||||
split?: boolean | undefined;
|
||||
excludeMiddleware?: boolean | undefined;
|
||||
assetsPrefix?: string | undefined;
|
||||
}>>>;
|
||||
server: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodObject<{
|
||||
host: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodBoolean]>>>;
|
||||
port: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
||||
open: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
headers: z.ZodOptional<z.ZodType<OutgoingHttpHeaders, z.ZodTypeDef, OutgoingHttpHeaders>>;
|
||||
streaming: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
streaming: boolean;
|
||||
}, {
|
||||
host?: string | boolean | undefined;
|
||||
port?: number | undefined;
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
open?: boolean | undefined;
|
||||
streaming?: boolean | undefined;
|
||||
}>>>, {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
streaming: boolean;
|
||||
}, unknown>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
site?: string | undefined;
|
||||
adapter?: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
} | undefined;
|
||||
output: "server" | "static" | "hybrid";
|
||||
server: {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
streaming: boolean;
|
||||
};
|
||||
redirects: Record<string, string>;
|
||||
root: URL;
|
||||
srcDir: URL;
|
||||
publicDir: URL;
|
||||
outDir: URL;
|
||||
cacheDir: URL;
|
||||
compressHTML: boolean;
|
||||
base: string;
|
||||
trailingSlash: "ignore" | "always" | "never";
|
||||
scopedStyleStrategy: "where" | "class";
|
||||
integrations: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}[];
|
||||
build: {
|
||||
assetsPrefix?: string | undefined;
|
||||
format: "file" | "directory";
|
||||
client: URL;
|
||||
server: URL;
|
||||
assets: string;
|
||||
serverEntry: string;
|
||||
redirects: boolean;
|
||||
inlineStylesheets: "always" | "never" | "auto";
|
||||
split: boolean;
|
||||
excludeMiddleware: boolean;
|
||||
};
|
||||
image: {
|
||||
service: {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
};
|
||||
};
|
||||
markdown: {
|
||||
drafts: boolean;
|
||||
syntaxHighlight: false | "shiki" | "prism";
|
||||
shikiConfig: {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
};
|
||||
remarkPlugins: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
|
||||
rehypePlugins: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
|
||||
remarkRehype: RemarkRehype;
|
||||
gfm: boolean;
|
||||
smartypants: boolean;
|
||||
};
|
||||
vite: ViteUserConfig;
|
||||
experimental: {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
};
|
||||
legacy: {};
|
||||
}, {
|
||||
output?: "server" | "static" | "hybrid" | undefined;
|
||||
server?: unknown;
|
||||
redirects?: Record<string, string> | undefined;
|
||||
root?: string | undefined;
|
||||
srcDir?: string | undefined;
|
||||
publicDir?: string | undefined;
|
||||
outDir?: string | undefined;
|
||||
cacheDir?: string | undefined;
|
||||
site?: string | undefined;
|
||||
compressHTML?: boolean | undefined;
|
||||
base?: string | undefined;
|
||||
trailingSlash?: "ignore" | "always" | "never" | undefined;
|
||||
scopedStyleStrategy?: "where" | "class" | undefined;
|
||||
adapter?: {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
} | undefined;
|
||||
integrations?: unknown;
|
||||
build?: {
|
||||
format?: "file" | "directory" | undefined;
|
||||
client?: string | undefined;
|
||||
server?: string | undefined;
|
||||
assets?: string | undefined;
|
||||
serverEntry?: string | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
inlineStylesheets?: "always" | "never" | "auto" | undefined;
|
||||
split?: boolean | undefined;
|
||||
excludeMiddleware?: boolean | undefined;
|
||||
assetsPrefix?: string | undefined;
|
||||
} | undefined;
|
||||
image?: {
|
||||
service: {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
};
|
||||
} | undefined;
|
||||
markdown?: {
|
||||
drafts?: boolean | undefined;
|
||||
syntaxHighlight?: false | "shiki" | "prism" | undefined;
|
||||
shikiConfig?: {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
} | undefined;
|
||||
remarkPlugins?: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[] | undefined;
|
||||
rehypePlugins?: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[] | undefined;
|
||||
remarkRehype?: RemarkRehype | undefined;
|
||||
gfm?: boolean | undefined;
|
||||
smartypants?: boolean | undefined;
|
||||
} | undefined;
|
||||
vite?: ViteUserConfig | undefined;
|
||||
experimental?: {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
} | undefined;
|
||||
legacy?: {} | undefined;
|
||||
}>, {
|
||||
site?: string | undefined;
|
||||
adapter?: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
} | undefined;
|
||||
output: "server" | "static" | "hybrid";
|
||||
server: {
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
host: string | boolean;
|
||||
port: number;
|
||||
open: boolean;
|
||||
streaming: boolean;
|
||||
};
|
||||
redirects: Record<string, string>;
|
||||
root: URL;
|
||||
srcDir: URL;
|
||||
publicDir: URL;
|
||||
outDir: URL;
|
||||
cacheDir: URL;
|
||||
compressHTML: boolean;
|
||||
base: string;
|
||||
trailingSlash: "ignore" | "always" | "never";
|
||||
scopedStyleStrategy: "where" | "class";
|
||||
integrations: {
|
||||
name: string;
|
||||
hooks: {};
|
||||
}[];
|
||||
build: {
|
||||
assetsPrefix?: string | undefined;
|
||||
format: "file" | "directory";
|
||||
client: URL;
|
||||
server: URL;
|
||||
assets: string;
|
||||
serverEntry: string;
|
||||
redirects: boolean;
|
||||
inlineStylesheets: "always" | "never" | "auto";
|
||||
split: boolean;
|
||||
excludeMiddleware: boolean;
|
||||
};
|
||||
image: {
|
||||
service: {
|
||||
entrypoint: string;
|
||||
config: Record<string, any>;
|
||||
};
|
||||
};
|
||||
markdown: {
|
||||
drafts: boolean;
|
||||
syntaxHighlight: false | "shiki" | "prism";
|
||||
shikiConfig: {
|
||||
langs: ILanguageRegistration[];
|
||||
theme: string | import("shiki").IShikiTheme;
|
||||
wrap: boolean | null;
|
||||
};
|
||||
remarkPlugins: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
|
||||
rehypePlugins: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
|
||||
remarkRehype: RemarkRehype;
|
||||
gfm: boolean;
|
||||
smartypants: boolean;
|
||||
};
|
||||
vite: ViteUserConfig;
|
||||
experimental: {
|
||||
assets: boolean;
|
||||
redirects: boolean;
|
||||
};
|
||||
legacy: {};
|
||||
}, {
|
||||
output?: "server" | "static" | "hybrid" | undefined;
|
||||
server?: unknown;
|
||||
redirects?: Record<string, string> | undefined;
|
||||
root?: string | undefined;
|
||||
srcDir?: string | undefined;
|
||||
publicDir?: string | undefined;
|
||||
outDir?: string | undefined;
|
||||
cacheDir?: string | undefined;
|
||||
site?: string | undefined;
|
||||
compressHTML?: boolean | undefined;
|
||||
base?: string | undefined;
|
||||
trailingSlash?: "ignore" | "always" | "never" | undefined;
|
||||
scopedStyleStrategy?: "where" | "class" | undefined;
|
||||
adapter?: {
|
||||
hooks?: {} | undefined;
|
||||
name: string;
|
||||
} | undefined;
|
||||
integrations?: unknown;
|
||||
build?: {
|
||||
format?: "file" | "directory" | undefined;
|
||||
client?: string | undefined;
|
||||
server?: string | undefined;
|
||||
assets?: string | undefined;
|
||||
serverEntry?: string | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
inlineStylesheets?: "always" | "never" | "auto" | undefined;
|
||||
split?: boolean | undefined;
|
||||
excludeMiddleware?: boolean | undefined;
|
||||
assetsPrefix?: string | undefined;
|
||||
} | undefined;
|
||||
image?: {
|
||||
service: {
|
||||
config?: Record<string, any> | undefined;
|
||||
entrypoint: string;
|
||||
};
|
||||
} | undefined;
|
||||
markdown?: {
|
||||
drafts?: boolean | undefined;
|
||||
syntaxHighlight?: false | "shiki" | "prism" | undefined;
|
||||
shikiConfig?: {
|
||||
langs?: ILanguageRegistration[] | undefined;
|
||||
theme?: string | import("shiki").IShikiTheme | undefined;
|
||||
wrap?: boolean | null | undefined;
|
||||
} | undefined;
|
||||
remarkPlugins?: (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[] | undefined;
|
||||
rehypePlugins?: (string | [string, any] | RehypePlugin | [RehypePlugin, any])[] | undefined;
|
||||
remarkRehype?: RemarkRehype | undefined;
|
||||
gfm?: boolean | undefined;
|
||||
smartypants?: boolean | undefined;
|
||||
} | undefined;
|
||||
vite?: ViteUserConfig | undefined;
|
||||
experimental?: {
|
||||
assets?: boolean | undefined;
|
||||
redirects?: boolean | undefined;
|
||||
} | undefined;
|
||||
legacy?: {} | undefined;
|
||||
}>;
|
215
node_modules/astro/dist/core/config/schema.js
generated
vendored
Normal file
215
node_modules/astro/dist/core/config/schema.js
generated
vendored
Normal file
|
@ -0,0 +1,215 @@
|
|||
import { markdownConfigDefaults } from "@astrojs/markdown-remark";
|
||||
import { BUNDLED_THEMES } from "shiki";
|
||||
import { z } from "zod";
|
||||
import { appendForwardSlash, prependForwardSlash, trimSlashes } from "../path.js";
|
||||
const ASTRO_CONFIG_DEFAULTS = {
|
||||
root: ".",
|
||||
srcDir: "./src",
|
||||
publicDir: "./public",
|
||||
outDir: "./dist",
|
||||
cacheDir: "./node_modules/.astro",
|
||||
base: "/",
|
||||
trailingSlash: "ignore",
|
||||
build: {
|
||||
format: "directory",
|
||||
client: "./dist/client/",
|
||||
server: "./dist/server/",
|
||||
assets: "_astro",
|
||||
serverEntry: "entry.mjs",
|
||||
redirects: true,
|
||||
inlineStylesheets: "never",
|
||||
split: false,
|
||||
excludeMiddleware: false
|
||||
},
|
||||
compressHTML: false,
|
||||
server: {
|
||||
host: false,
|
||||
port: 3e3,
|
||||
open: false
|
||||
},
|
||||
integrations: [],
|
||||
markdown: {
|
||||
drafts: false,
|
||||
...markdownConfigDefaults
|
||||
},
|
||||
vite: {},
|
||||
legacy: {},
|
||||
redirects: {},
|
||||
experimental: {
|
||||
assets: false,
|
||||
redirects: false
|
||||
}
|
||||
};
|
||||
const AstroConfigSchema = z.object({
|
||||
root: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.root).transform((val) => new URL(val)),
|
||||
srcDir: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.srcDir).transform((val) => new URL(val)),
|
||||
publicDir: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.publicDir).transform((val) => new URL(val)),
|
||||
outDir: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.outDir).transform((val) => new URL(val)),
|
||||
cacheDir: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.cacheDir).transform((val) => new URL(val)),
|
||||
site: z.string().url().optional(),
|
||||
compressHTML: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.compressHTML),
|
||||
base: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.base),
|
||||
trailingSlash: z.union([z.literal("always"), z.literal("never"), z.literal("ignore")]).optional().default(ASTRO_CONFIG_DEFAULTS.trailingSlash),
|
||||
output: z.union([z.literal("static"), z.literal("server"), z.literal("hybrid")]).optional().default("static"),
|
||||
scopedStyleStrategy: z.union([z.literal("where"), z.literal("class")]).optional().default("where"),
|
||||
adapter: z.object({ name: z.string(), hooks: z.object({}).passthrough().default({}) }).optional(),
|
||||
integrations: z.preprocess(
|
||||
// preprocess
|
||||
(val) => Array.isArray(val) ? val.flat(Infinity).filter(Boolean) : val,
|
||||
// validate
|
||||
z.array(z.object({ name: z.string(), hooks: z.object({}).passthrough().default({}) })).default(ASTRO_CONFIG_DEFAULTS.integrations)
|
||||
),
|
||||
build: z.object({
|
||||
format: z.union([z.literal("file"), z.literal("directory")]).optional().default(ASTRO_CONFIG_DEFAULTS.build.format),
|
||||
client: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.client).transform((val) => new URL(val)),
|
||||
server: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.server).transform((val) => new URL(val)),
|
||||
assets: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.assets),
|
||||
assetsPrefix: z.string().optional(),
|
||||
serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
|
||||
redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
|
||||
inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets),
|
||||
split: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.split),
|
||||
excludeMiddleware: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.excludeMiddleware)
|
||||
}).optional().default({}),
|
||||
server: z.preprocess(
|
||||
// preprocess
|
||||
// NOTE: Uses the "error" command here because this is overwritten by the
|
||||
// individualized schema parser with the correct command.
|
||||
(val) => typeof val === "function" ? val({ command: "error" }) : val,
|
||||
// validate
|
||||
z.object({
|
||||
open: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.server.open),
|
||||
host: z.union([z.string(), z.boolean()]).optional().default(ASTRO_CONFIG_DEFAULTS.server.host),
|
||||
port: z.number().optional().default(ASTRO_CONFIG_DEFAULTS.server.port),
|
||||
headers: z.custom().optional()
|
||||
}).optional().default({})
|
||||
),
|
||||
redirects: z.record(z.string(), z.string()).default(ASTRO_CONFIG_DEFAULTS.redirects),
|
||||
image: z.object({
|
||||
service: z.object({
|
||||
entrypoint: z.union([
|
||||
z.literal("astro/assets/services/sharp"),
|
||||
z.literal("astro/assets/services/squoosh"),
|
||||
z.string()
|
||||
]),
|
||||
config: z.record(z.any()).default({})
|
||||
})
|
||||
}).default({
|
||||
service: { entrypoint: "astro/assets/services/squoosh", config: {} }
|
||||
}),
|
||||
markdown: z.object({
|
||||
drafts: z.boolean().default(false),
|
||||
syntaxHighlight: z.union([z.literal("shiki"), z.literal("prism"), z.literal(false)]).default(ASTRO_CONFIG_DEFAULTS.markdown.syntaxHighlight),
|
||||
shikiConfig: z.object({
|
||||
langs: z.custom().array().default([]),
|
||||
theme: z.enum(BUNDLED_THEMES).or(z.custom()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.theme),
|
||||
wrap: z.boolean().or(z.null()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.wrap)
|
||||
}).default({}),
|
||||
remarkPlugins: z.union([
|
||||
z.string(),
|
||||
z.tuple([z.string(), z.any()]),
|
||||
z.custom((data) => typeof data === "function"),
|
||||
z.tuple([z.custom((data) => typeof data === "function"), z.any()])
|
||||
]).array().default(ASTRO_CONFIG_DEFAULTS.markdown.remarkPlugins),
|
||||
rehypePlugins: z.union([
|
||||
z.string(),
|
||||
z.tuple([z.string(), z.any()]),
|
||||
z.custom((data) => typeof data === "function"),
|
||||
z.tuple([z.custom((data) => typeof data === "function"), z.any()])
|
||||
]).array().default(ASTRO_CONFIG_DEFAULTS.markdown.rehypePlugins),
|
||||
remarkRehype: z.custom((data) => data instanceof Object && !Array.isArray(data)).optional().default(ASTRO_CONFIG_DEFAULTS.markdown.remarkRehype),
|
||||
gfm: z.boolean().default(ASTRO_CONFIG_DEFAULTS.markdown.gfm),
|
||||
smartypants: z.boolean().default(ASTRO_CONFIG_DEFAULTS.markdown.smartypants)
|
||||
}).default({}),
|
||||
vite: z.custom((data) => data instanceof Object && !Array.isArray(data)).default(ASTRO_CONFIG_DEFAULTS.vite),
|
||||
experimental: z.object({
|
||||
assets: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.assets),
|
||||
redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.redirects)
|
||||
}).passthrough().refine(
|
||||
(d) => {
|
||||
const validKeys = Object.keys(ASTRO_CONFIG_DEFAULTS.experimental);
|
||||
const invalidKeys = Object.keys(d).filter((key) => !validKeys.includes(key));
|
||||
if (invalidKeys.length > 0)
|
||||
return false;
|
||||
return true;
|
||||
},
|
||||
(d) => {
|
||||
const validKeys = Object.keys(ASTRO_CONFIG_DEFAULTS.experimental);
|
||||
const invalidKeys = Object.keys(d).filter((key) => !validKeys.includes(key));
|
||||
return {
|
||||
message: `Invalid experimental key: \`${invalidKeys.join(
|
||||
", "
|
||||
)}\`.
|
||||
Make sure the spelling is correct, and that your Astro version supports this experiment.
|
||||
See https://docs.astro.build/en/reference/configuration-reference/#experimental-flags for more information.`
|
||||
};
|
||||
}
|
||||
).optional().default({}),
|
||||
legacy: z.object({}).optional().default({})
|
||||
});
|
||||
function createRelativeSchema(cmd, fileProtocolRoot) {
|
||||
const AstroConfigRelativeSchema = AstroConfigSchema.extend({
|
||||
root: z.string().default(ASTRO_CONFIG_DEFAULTS.root).transform((val) => new URL(appendForwardSlash(val), fileProtocolRoot)),
|
||||
srcDir: z.string().default(ASTRO_CONFIG_DEFAULTS.srcDir).transform((val) => new URL(appendForwardSlash(val), fileProtocolRoot)),
|
||||
compressHTML: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.compressHTML),
|
||||
publicDir: z.string().default(ASTRO_CONFIG_DEFAULTS.publicDir).transform((val) => new URL(appendForwardSlash(val), fileProtocolRoot)),
|
||||
outDir: z.string().default(ASTRO_CONFIG_DEFAULTS.outDir).transform((val) => new URL(appendForwardSlash(val), fileProtocolRoot)),
|
||||
cacheDir: z.string().default(ASTRO_CONFIG_DEFAULTS.cacheDir).transform((val) => new URL(appendForwardSlash(val), fileProtocolRoot)),
|
||||
build: z.object({
|
||||
format: z.union([z.literal("file"), z.literal("directory")]).optional().default(ASTRO_CONFIG_DEFAULTS.build.format),
|
||||
client: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.client).transform((val) => new URL(val, fileProtocolRoot)),
|
||||
server: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.server).transform((val) => new URL(val, fileProtocolRoot)),
|
||||
assets: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.assets),
|
||||
assetsPrefix: z.string().optional(),
|
||||
serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
|
||||
redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
|
||||
inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets),
|
||||
split: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.split),
|
||||
excludeMiddleware: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.excludeMiddleware)
|
||||
}).optional().default({}),
|
||||
server: z.preprocess(
|
||||
// preprocess
|
||||
(val) => {
|
||||
if (typeof val === "function") {
|
||||
return val({ command: cmd === "dev" ? "dev" : "preview" });
|
||||
} else {
|
||||
return val;
|
||||
}
|
||||
},
|
||||
// validate
|
||||
z.object({
|
||||
host: z.union([z.string(), z.boolean()]).optional().default(ASTRO_CONFIG_DEFAULTS.server.host),
|
||||
port: z.number().optional().default(ASTRO_CONFIG_DEFAULTS.server.port),
|
||||
open: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.server.open),
|
||||
headers: z.custom().optional(),
|
||||
streaming: z.boolean().optional().default(true)
|
||||
}).optional().default({})
|
||||
)
|
||||
}).transform((config) => {
|
||||
if (!config.build.server.toString().startsWith(config.outDir.toString()) && config.build.server.toString().endsWith("dist/server/")) {
|
||||
config.build.server = new URL("./dist/server/", config.outDir);
|
||||
}
|
||||
if (!config.build.client.toString().startsWith(config.outDir.toString()) && config.build.client.toString().endsWith("dist/client/")) {
|
||||
config.build.client = new URL("./dist/client/", config.outDir);
|
||||
}
|
||||
const trimmedBase = trimSlashes(config.base);
|
||||
const sitePathname = config.site && new URL(config.site).pathname;
|
||||
if (!trimmedBase.length && sitePathname && sitePathname !== "/") {
|
||||
config.base = sitePathname;
|
||||
console.warn(`The site configuration value includes a pathname of ${sitePathname} but there is no base configuration.
|
||||
|
||||
A future version of Astro will stop using the site pathname when producing <link> and <script> tags. Set your site's base with the base configuration.`);
|
||||
}
|
||||
if (trimmedBase.length && config.trailingSlash === "never") {
|
||||
config.base = prependForwardSlash(trimmedBase);
|
||||
} else {
|
||||
config.base = prependForwardSlash(appendForwardSlash(trimmedBase));
|
||||
}
|
||||
return config;
|
||||
});
|
||||
return AstroConfigRelativeSchema;
|
||||
}
|
||||
export {
|
||||
AstroConfigSchema,
|
||||
createRelativeSchema
|
||||
};
|
4
node_modules/astro/dist/core/config/settings.d.ts
generated
vendored
Normal file
4
node_modules/astro/dist/core/config/settings.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
import type { AstroConfig, AstroSettings, AstroUserConfig } from '../../@types/astro';
|
||||
export declare function createBaseSettings(config: AstroConfig): AstroSettings;
|
||||
export declare function createSettings(config: AstroConfig, cwd?: string): AstroSettings;
|
||||
export declare function createDefaultDevSettings(userConfig?: AstroUserConfig, root?: string | URL): Promise<AstroSettings>;
|
118
node_modules/astro/dist/core/config/settings.js
generated
vendored
Normal file
118
node_modules/astro/dist/core/config/settings.js
generated
vendored
Normal file
|
@ -0,0 +1,118 @@
|
|||
import yaml from "js-yaml";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { getContentPaths } from "../../content/index.js";
|
||||
import jsxRenderer from "../../jsx/renderer.js";
|
||||
import { isServerLikeOutput } from "../../prerender/utils.js";
|
||||
import { markdownContentEntryType } from "../../vite-plugin-markdown/content-entry-type.js";
|
||||
import { getDefaultClientDirectives } from "../client-directive/index.js";
|
||||
import { AstroError, AstroErrorData } from "../errors/index.js";
|
||||
import { formatYAMLException, isYAMLException } from "../errors/utils.js";
|
||||
import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from "./../constants.js";
|
||||
import { createDefaultDevConfig } from "./config.js";
|
||||
import { AstroTimer } from "./timer.js";
|
||||
import { loadTSConfig } from "./tsconfig.js";
|
||||
function createBaseSettings(config) {
|
||||
const { contentDir } = getContentPaths(config);
|
||||
return {
|
||||
config,
|
||||
tsConfig: void 0,
|
||||
tsConfigPath: void 0,
|
||||
adapter: void 0,
|
||||
injectedRoutes: config.experimental.assets && isServerLikeOutput(config) ? [{ pattern: "/_image", entryPoint: "astro/assets/image-endpoint", prerender: false }] : [],
|
||||
pageExtensions: [".astro", ".html", ...SUPPORTED_MARKDOWN_FILE_EXTENSIONS],
|
||||
contentEntryTypes: [markdownContentEntryType],
|
||||
dataEntryTypes: [
|
||||
{
|
||||
extensions: [".json"],
|
||||
getEntryInfo({ contents, fileUrl }) {
|
||||
if (contents === void 0 || contents === "")
|
||||
return { data: {} };
|
||||
const pathRelToContentDir = path.relative(
|
||||
fileURLToPath(contentDir),
|
||||
fileURLToPath(fileUrl)
|
||||
);
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(contents);
|
||||
} catch (e) {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.DataCollectionEntryParseError,
|
||||
message: AstroErrorData.DataCollectionEntryParseError.message(
|
||||
pathRelToContentDir,
|
||||
e instanceof Error ? e.message : "contains invalid JSON."
|
||||
),
|
||||
location: { file: fileUrl.pathname },
|
||||
stack: e instanceof Error ? e.stack : void 0
|
||||
});
|
||||
}
|
||||
if (data == null || typeof data !== "object") {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.DataCollectionEntryParseError,
|
||||
message: AstroErrorData.DataCollectionEntryParseError.message(
|
||||
pathRelToContentDir,
|
||||
"data is not an object."
|
||||
),
|
||||
location: { file: fileUrl.pathname }
|
||||
});
|
||||
}
|
||||
return { data };
|
||||
}
|
||||
},
|
||||
{
|
||||
extensions: [".yaml", ".yml"],
|
||||
getEntryInfo({ contents, fileUrl }) {
|
||||
try {
|
||||
const data = yaml.load(contents, { filename: fileURLToPath(fileUrl) });
|
||||
const rawData = contents;
|
||||
return { data, rawData };
|
||||
} catch (e) {
|
||||
const pathRelToContentDir = path.relative(
|
||||
fileURLToPath(contentDir),
|
||||
fileURLToPath(fileUrl)
|
||||
);
|
||||
const formattedError = isYAMLException(e) ? formatYAMLException(e) : new Error("contains invalid YAML.");
|
||||
throw new AstroError({
|
||||
...AstroErrorData.DataCollectionEntryParseError,
|
||||
message: AstroErrorData.DataCollectionEntryParseError.message(
|
||||
pathRelToContentDir,
|
||||
formattedError.message
|
||||
),
|
||||
stack: formattedError.stack,
|
||||
location: "loc" in formattedError ? { file: fileUrl.pathname, ...formattedError.loc } : { file: fileUrl.pathname }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
renderers: [jsxRenderer],
|
||||
scripts: [],
|
||||
clientDirectives: getDefaultClientDirectives(),
|
||||
watchFiles: [],
|
||||
timer: new AstroTimer()
|
||||
};
|
||||
}
|
||||
function createSettings(config, cwd) {
|
||||
const tsconfig = loadTSConfig(cwd);
|
||||
const settings = createBaseSettings(config);
|
||||
const watchFiles = (tsconfig == null ? void 0 : tsconfig.exists) ? [tsconfig.path, ...tsconfig.extendedPaths] : [];
|
||||
if (cwd) {
|
||||
watchFiles.push(fileURLToPath(new URL("./package.json", pathToFileURL(cwd))));
|
||||
}
|
||||
settings.tsConfig = tsconfig == null ? void 0 : tsconfig.config;
|
||||
settings.tsConfigPath = tsconfig == null ? void 0 : tsconfig.path;
|
||||
settings.watchFiles = watchFiles;
|
||||
return settings;
|
||||
}
|
||||
async function createDefaultDevSettings(userConfig = {}, root) {
|
||||
if (root && typeof root !== "string") {
|
||||
root = fileURLToPath(root);
|
||||
}
|
||||
const config = await createDefaultDevConfig(userConfig, root);
|
||||
return createBaseSettings(config);
|
||||
}
|
||||
export {
|
||||
createBaseSettings,
|
||||
createDefaultDevSettings,
|
||||
createSettings
|
||||
};
|
27
node_modules/astro/dist/core/config/timer.d.ts
generated
vendored
Normal file
27
node_modules/astro/dist/core/config/timer.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,27 @@
|
|||
export interface Stat {
|
||||
elapsedTime: number;
|
||||
heapUsedChange: number;
|
||||
heapUsedTotal: number;
|
||||
}
|
||||
/**
|
||||
* Timer to track certain operations' performance. Used by Astro's scripts only.
|
||||
* Set `process.env.ASTRO_TIMER_PATH` truthy to enable.
|
||||
*/
|
||||
export declare class AstroTimer {
|
||||
private enabled;
|
||||
private ongoingTimers;
|
||||
private stats;
|
||||
constructor();
|
||||
/**
|
||||
* Start a timer for a scope with a given name.
|
||||
*/
|
||||
start(name: string): void;
|
||||
/**
|
||||
* End a timer for a scope with a given name.
|
||||
*/
|
||||
end(name: string): void;
|
||||
/**
|
||||
* Write stats to `process.env.ASTRO_TIMER_PATH`
|
||||
*/
|
||||
writeStats(): void;
|
||||
}
|
51
node_modules/astro/dist/core/config/timer.js
generated
vendored
Normal file
51
node_modules/astro/dist/core/config/timer.js
generated
vendored
Normal file
|
@ -0,0 +1,51 @@
|
|||
import fs from "node:fs";
|
||||
class AstroTimer {
|
||||
constructor() {
|
||||
this.ongoingTimers = /* @__PURE__ */ new Map();
|
||||
this.stats = {};
|
||||
this.enabled = !!process.env.ASTRO_TIMER_PATH;
|
||||
}
|
||||
/**
|
||||
* Start a timer for a scope with a given name.
|
||||
*/
|
||||
start(name) {
|
||||
var _a;
|
||||
if (!this.enabled)
|
||||
return;
|
||||
(_a = globalThis.gc) == null ? void 0 : _a.call(globalThis);
|
||||
this.ongoingTimers.set(name, {
|
||||
startTime: performance.now(),
|
||||
startHeap: process.memoryUsage().heapUsed
|
||||
});
|
||||
}
|
||||
/**
|
||||
* End a timer for a scope with a given name.
|
||||
*/
|
||||
end(name) {
|
||||
var _a;
|
||||
if (!this.enabled)
|
||||
return;
|
||||
const stat = this.ongoingTimers.get(name);
|
||||
if (!stat)
|
||||
return;
|
||||
(_a = globalThis.gc) == null ? void 0 : _a.call(globalThis);
|
||||
const endHeap = process.memoryUsage().heapUsed;
|
||||
this.stats[name] = {
|
||||
elapsedTime: performance.now() - stat.startTime,
|
||||
heapUsedChange: endHeap - stat.startHeap,
|
||||
heapUsedTotal: endHeap
|
||||
};
|
||||
this.ongoingTimers.delete(name);
|
||||
}
|
||||
/**
|
||||
* Write stats to `process.env.ASTRO_TIMER_PATH`
|
||||
*/
|
||||
writeStats() {
|
||||
if (!this.enabled)
|
||||
return;
|
||||
fs.writeFileSync(process.env.ASTRO_TIMER_PATH, JSON.stringify(this.stats, null, 2));
|
||||
}
|
||||
}
|
||||
export {
|
||||
AstroTimer
|
||||
};
|
11
node_modules/astro/dist/core/config/tsconfig.d.ts
generated
vendored
Normal file
11
node_modules/astro/dist/core/config/tsconfig.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,11 @@
|
|||
import * as tsr from 'tsconfig-resolver';
|
||||
export declare const defaultTSConfig: tsr.TsConfigJson;
|
||||
export type frameworkWithTSSettings = 'vue' | 'react' | 'preact' | 'solid-js';
|
||||
export declare const presets: Map<frameworkWithTSSettings, tsr.TsConfigJson>;
|
||||
/**
|
||||
* Load a tsconfig.json or jsconfig.json is the former is not found
|
||||
* @param cwd Directory to start from
|
||||
* @param resolve Determine if the function should go up directories like TypeScript would
|
||||
*/
|
||||
export declare function loadTSConfig(cwd: string | undefined, resolve?: boolean): tsr.TsConfigResult;
|
||||
export declare function updateTSConfigForFramework(target: tsr.TsConfigJson, framework: frameworkWithTSSettings): tsr.TsConfigJson;
|
82
node_modules/astro/dist/core/config/tsconfig.js
generated
vendored
Normal file
82
node_modules/astro/dist/core/config/tsconfig.js
generated
vendored
Normal file
|
@ -0,0 +1,82 @@
|
|||
import { deepmerge } from "deepmerge-ts";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import * as tsr from "tsconfig-resolver";
|
||||
const defaultTSConfig = { extends: "astro/tsconfigs/base" };
|
||||
const presets = /* @__PURE__ */ new Map([
|
||||
[
|
||||
"vue",
|
||||
// Settings needed for template intellisense when using Volar
|
||||
{
|
||||
compilerOptions: {
|
||||
jsx: "preserve"
|
||||
}
|
||||
}
|
||||
],
|
||||
[
|
||||
"react",
|
||||
// Default TypeScript settings, but we need to redefine them in case the users changed them previously
|
||||
{
|
||||
compilerOptions: {
|
||||
jsx: "react-jsx",
|
||||
jsxImportSource: "react"
|
||||
}
|
||||
}
|
||||
],
|
||||
[
|
||||
"preact",
|
||||
// https://preactjs.com/guide/v10/typescript/#typescript-configuration
|
||||
{
|
||||
compilerOptions: {
|
||||
jsx: "react-jsx",
|
||||
jsxImportSource: "preact"
|
||||
}
|
||||
}
|
||||
],
|
||||
[
|
||||
"solid-js",
|
||||
// https://www.solidjs.com/guides/typescript#configuring-typescript
|
||||
{
|
||||
compilerOptions: {
|
||||
jsx: "preserve",
|
||||
jsxImportSource: "solid-js"
|
||||
}
|
||||
}
|
||||
]
|
||||
]);
|
||||
function loadTSConfig(cwd, resolve = true) {
|
||||
cwd = cwd ?? process.cwd();
|
||||
let config = tsr.tsconfigResolverSync({
|
||||
cwd,
|
||||
filePath: resolve ? void 0 : cwd,
|
||||
ignoreExtends: !resolve
|
||||
});
|
||||
if (!resolve && config.reason === "invalid-config" && !existsSync(join(cwd, "tsconfig.json"))) {
|
||||
config = { reason: "not-found", path: void 0, exists: false };
|
||||
}
|
||||
if (config.reason === "not-found") {
|
||||
const jsconfig = tsr.tsconfigResolverSync({
|
||||
cwd,
|
||||
filePath: resolve ? void 0 : cwd,
|
||||
searchName: "jsconfig.json",
|
||||
ignoreExtends: !resolve
|
||||
});
|
||||
if (!resolve && jsconfig.reason === "invalid-config" && !existsSync(join(cwd, "jsconfig.json"))) {
|
||||
return { reason: "not-found", path: void 0, exists: false };
|
||||
}
|
||||
return jsconfig;
|
||||
}
|
||||
return config;
|
||||
}
|
||||
function updateTSConfigForFramework(target, framework) {
|
||||
if (!presets.has(framework)) {
|
||||
return target;
|
||||
}
|
||||
return deepmerge(target, presets.get(framework));
|
||||
}
|
||||
export {
|
||||
defaultTSConfig,
|
||||
loadTSConfig,
|
||||
presets,
|
||||
updateTSConfigForFramework
|
||||
};
|
9
node_modules/astro/dist/core/config/vite-load.d.ts
generated
vendored
Normal file
9
node_modules/astro/dist/core/config/vite-load.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
/// <reference types="node" />
|
||||
import type fsType from 'node:fs';
|
||||
interface LoadConfigWithViteOptions {
|
||||
root: string;
|
||||
configPath: string;
|
||||
fs: typeof fsType;
|
||||
}
|
||||
export declare function loadConfigWithVite({ configPath, fs, root, }: LoadConfigWithViteOptions): Promise<Record<string, any>>;
|
||||
export {};
|
54
node_modules/astro/dist/core/config/vite-load.js
generated
vendored
Normal file
54
node_modules/astro/dist/core/config/vite-load.js
generated
vendored
Normal file
|
@ -0,0 +1,54 @@
|
|||
import { pathToFileURL } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import loadFallbackPlugin from "../../vite-plugin-load-fallback/index.js";
|
||||
import { debug } from "../logger/core.js";
|
||||
async function createViteServer(root, fs) {
|
||||
const viteServer = await createServer({
|
||||
server: { middlewareMode: true, hmr: false, watch: { ignored: ["**"] } },
|
||||
optimizeDeps: { disabled: true },
|
||||
clearScreen: false,
|
||||
appType: "custom",
|
||||
ssr: {
|
||||
// NOTE: Vite doesn't externalize linked packages by default. During testing locally,
|
||||
// these dependencies trip up Vite's dev SSR transform. Awaiting upstream feature:
|
||||
// https://github.com/vitejs/vite/pull/10939
|
||||
external: [
|
||||
"@astrojs/tailwind",
|
||||
"@astrojs/mdx",
|
||||
"@astrojs/react",
|
||||
"@astrojs/preact",
|
||||
"@astrojs/sitemap",
|
||||
"@astrojs/markdoc"
|
||||
]
|
||||
},
|
||||
plugins: [loadFallbackPlugin({ fs, root: pathToFileURL(root) })]
|
||||
});
|
||||
return viteServer;
|
||||
}
|
||||
async function loadConfigWithVite({
|
||||
configPath,
|
||||
fs,
|
||||
root
|
||||
}) {
|
||||
if (/\.[cm]?js$/.test(configPath)) {
|
||||
try {
|
||||
const config = await import(pathToFileURL(configPath).toString() + "?t=" + Date.now());
|
||||
return config.default ?? {};
|
||||
} catch (e) {
|
||||
debug("Failed to load config with Node", e);
|
||||
}
|
||||
}
|
||||
let server;
|
||||
try {
|
||||
server = await createViteServer(root, fs);
|
||||
const mod = await server.ssrLoadModule(configPath, { fixStacktrace: true });
|
||||
return mod.default ?? {};
|
||||
} finally {
|
||||
if (server) {
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
loadConfigWithVite
|
||||
};
|
3
node_modules/astro/dist/core/constants.d.ts
generated
vendored
Normal file
3
node_modules/astro/dist/core/constants.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
export declare const ASTRO_VERSION: string;
|
||||
export declare const SUPPORTED_MARKDOWN_FILE_EXTENSIONS: readonly [".markdown", ".mdown", ".mkdn", ".mkd", ".mdwn", ".md"];
|
||||
export declare const MIDDLEWARE_PATH_SEGMENT_NAME = "middleware";
|
15
node_modules/astro/dist/core/constants.js
generated
vendored
Normal file
15
node_modules/astro/dist/core/constants.js
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
const ASTRO_VERSION = "2.8.5";
|
||||
const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
|
||||
".markdown",
|
||||
".mdown",
|
||||
".mkdn",
|
||||
".mkd",
|
||||
".mdwn",
|
||||
".md"
|
||||
];
|
||||
const MIDDLEWARE_PATH_SEGMENT_NAME = "middleware";
|
||||
export {
|
||||
ASTRO_VERSION,
|
||||
MIDDLEWARE_PATH_SEGMENT_NAME,
|
||||
SUPPORTED_MARKDOWN_FILE_EXTENSIONS
|
||||
};
|
73
node_modules/astro/dist/core/cookies/cookies.d.ts
generated
vendored
Normal file
73
node_modules/astro/dist/core/cookies/cookies.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,73 @@
|
|||
interface AstroCookieSetOptions {
|
||||
domain?: string;
|
||||
expires?: Date;
|
||||
httpOnly?: boolean;
|
||||
maxAge?: number;
|
||||
path?: string;
|
||||
sameSite?: boolean | 'lax' | 'none' | 'strict';
|
||||
secure?: boolean;
|
||||
}
|
||||
type AstroCookieDeleteOptions = Pick<AstroCookieSetOptions, 'domain' | 'path'>;
|
||||
interface AstroCookieInterface {
|
||||
value: string | undefined;
|
||||
json(): Record<string, any>;
|
||||
number(): number;
|
||||
boolean(): boolean;
|
||||
}
|
||||
interface AstroCookiesInterface {
|
||||
get(key: string): AstroCookieInterface;
|
||||
has(key: string): boolean;
|
||||
set(key: string, value: string | number | boolean | Record<string, any>, options?: AstroCookieSetOptions): void;
|
||||
delete(key: string, options?: AstroCookieDeleteOptions): void;
|
||||
}
|
||||
declare class AstroCookie implements AstroCookieInterface {
|
||||
value: string | undefined;
|
||||
constructor(value: string | undefined);
|
||||
json(): any;
|
||||
number(): number;
|
||||
boolean(): boolean;
|
||||
}
|
||||
declare class AstroCookies implements AstroCookiesInterface {
|
||||
#private;
|
||||
constructor(request: Request);
|
||||
/**
|
||||
* Astro.cookies.delete(key) is used to delete a cookie. Using this method will result
|
||||
* in a Set-Cookie header added to the response.
|
||||
* @param key The cookie to delete
|
||||
* @param options Options related to this deletion, such as the path of the cookie.
|
||||
*/
|
||||
delete(key: string, options?: AstroCookieDeleteOptions): void;
|
||||
/**
|
||||
* Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the
|
||||
* request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken
|
||||
* from that set call, overriding any values already part of the request.
|
||||
* @param key The cookie to get.
|
||||
* @returns An object containing the cookie value as well as convenience methods for converting its value.
|
||||
*/
|
||||
get(key: string): AstroCookie;
|
||||
/**
|
||||
* Astro.cookies.has(key) returns a boolean indicating whether this cookie is either
|
||||
* part of the initial request or set via Astro.cookies.set(key)
|
||||
* @param key The cookie to check for.
|
||||
* @returns
|
||||
*/
|
||||
has(key: string): boolean;
|
||||
/**
|
||||
* Astro.cookies.set(key, value) is used to set a cookie's value. If provided
|
||||
* an object it will be stringified via JSON.stringify(value). Additionally you
|
||||
* can provide options customizing how this cookie will be set, such as setting httpOnly
|
||||
* in order to prevent the cookie from being read in client-side JavaScript.
|
||||
* @param key The name of the cookie to set.
|
||||
* @param value A value, either a string or other primitive or an object.
|
||||
* @param options Options for the cookie, such as the path and security settings.
|
||||
*/
|
||||
set(key: string, value: string | Record<string, any>, options?: AstroCookieSetOptions): void;
|
||||
/**
|
||||
* Astro.cookies.header() returns an iterator for the cookies that have previously
|
||||
* been set by either Astro.cookies.set() or Astro.cookies.delete().
|
||||
* This method is primarily used by adapters to set the header on outgoing responses.
|
||||
* @returns
|
||||
*/
|
||||
headers(): Generator<string, void, unknown>;
|
||||
}
|
||||
export { AstroCookies };
|
168
node_modules/astro/dist/core/cookies/cookies.js
generated
vendored
Normal file
168
node_modules/astro/dist/core/cookies/cookies.js
generated
vendored
Normal file
|
@ -0,0 +1,168 @@
|
|||
import { parse, serialize } from "cookie";
|
||||
import { AstroError, AstroErrorData } from "../errors/index.js";
|
||||
const DELETED_EXPIRATION = /* @__PURE__ */ new Date(0);
|
||||
const DELETED_VALUE = "deleted";
|
||||
const responseSentSymbol = Symbol.for("astro.responseSent");
|
||||
class AstroCookie {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
}
|
||||
json() {
|
||||
if (this.value === void 0) {
|
||||
throw new Error(`Cannot convert undefined to an object.`);
|
||||
}
|
||||
return JSON.parse(this.value);
|
||||
}
|
||||
number() {
|
||||
return Number(this.value);
|
||||
}
|
||||
boolean() {
|
||||
if (this.value === "false")
|
||||
return false;
|
||||
if (this.value === "0")
|
||||
return false;
|
||||
return Boolean(this.value);
|
||||
}
|
||||
}
|
||||
class AstroCookies {
|
||||
#request;
|
||||
#requestValues;
|
||||
#outgoing;
|
||||
constructor(request) {
|
||||
this.#request = request;
|
||||
this.#requestValues = null;
|
||||
this.#outgoing = null;
|
||||
}
|
||||
/**
|
||||
* Astro.cookies.delete(key) is used to delete a cookie. Using this method will result
|
||||
* in a Set-Cookie header added to the response.
|
||||
* @param key The cookie to delete
|
||||
* @param options Options related to this deletion, such as the path of the cookie.
|
||||
*/
|
||||
delete(key, options) {
|
||||
const serializeOptions = {
|
||||
expires: DELETED_EXPIRATION
|
||||
};
|
||||
if (options == null ? void 0 : options.domain) {
|
||||
serializeOptions.domain = options.domain;
|
||||
}
|
||||
if (options == null ? void 0 : options.path) {
|
||||
serializeOptions.path = options.path;
|
||||
}
|
||||
this.#ensureOutgoingMap().set(key, [
|
||||
DELETED_VALUE,
|
||||
serialize(key, DELETED_VALUE, serializeOptions),
|
||||
false
|
||||
]);
|
||||
}
|
||||
/**
|
||||
* Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the
|
||||
* request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken
|
||||
* from that set call, overriding any values already part of the request.
|
||||
* @param key The cookie to get.
|
||||
* @returns An object containing the cookie value as well as convenience methods for converting its value.
|
||||
*/
|
||||
get(key) {
|
||||
var _a;
|
||||
if ((_a = this.#outgoing) == null ? void 0 : _a.has(key)) {
|
||||
let [serializedValue, , isSetValue] = this.#outgoing.get(key);
|
||||
if (isSetValue) {
|
||||
return new AstroCookie(serializedValue);
|
||||
} else {
|
||||
return new AstroCookie(void 0);
|
||||
}
|
||||
}
|
||||
const values = this.#ensureParsed();
|
||||
const value = values[key];
|
||||
return new AstroCookie(value);
|
||||
}
|
||||
/**
|
||||
* Astro.cookies.has(key) returns a boolean indicating whether this cookie is either
|
||||
* part of the initial request or set via Astro.cookies.set(key)
|
||||
* @param key The cookie to check for.
|
||||
* @returns
|
||||
*/
|
||||
has(key) {
|
||||
var _a;
|
||||
if ((_a = this.#outgoing) == null ? void 0 : _a.has(key)) {
|
||||
let [, , isSetValue] = this.#outgoing.get(key);
|
||||
return isSetValue;
|
||||
}
|
||||
const values = this.#ensureParsed();
|
||||
return !!values[key];
|
||||
}
|
||||
/**
|
||||
* Astro.cookies.set(key, value) is used to set a cookie's value. If provided
|
||||
* an object it will be stringified via JSON.stringify(value). Additionally you
|
||||
* can provide options customizing how this cookie will be set, such as setting httpOnly
|
||||
* in order to prevent the cookie from being read in client-side JavaScript.
|
||||
* @param key The name of the cookie to set.
|
||||
* @param value A value, either a string or other primitive or an object.
|
||||
* @param options Options for the cookie, such as the path and security settings.
|
||||
*/
|
||||
set(key, value, options) {
|
||||
let serializedValue;
|
||||
if (typeof value === "string") {
|
||||
serializedValue = value;
|
||||
} else {
|
||||
let toStringValue = value.toString();
|
||||
if (toStringValue === Object.prototype.toString.call(value)) {
|
||||
serializedValue = JSON.stringify(value);
|
||||
} else {
|
||||
serializedValue = toStringValue;
|
||||
}
|
||||
}
|
||||
const serializeOptions = {};
|
||||
if (options) {
|
||||
Object.assign(serializeOptions, options);
|
||||
}
|
||||
this.#ensureOutgoingMap().set(key, [
|
||||
serializedValue,
|
||||
serialize(key, serializedValue, serializeOptions),
|
||||
true
|
||||
]);
|
||||
if (this.#request[responseSentSymbol]) {
|
||||
throw new AstroError({
|
||||
...AstroErrorData.ResponseSentError
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Astro.cookies.header() returns an iterator for the cookies that have previously
|
||||
* been set by either Astro.cookies.set() or Astro.cookies.delete().
|
||||
* This method is primarily used by adapters to set the header on outgoing responses.
|
||||
* @returns
|
||||
*/
|
||||
*headers() {
|
||||
if (this.#outgoing == null)
|
||||
return;
|
||||
for (const [, value] of this.#outgoing) {
|
||||
yield value[1];
|
||||
}
|
||||
}
|
||||
#ensureParsed() {
|
||||
if (!this.#requestValues) {
|
||||
this.#parse();
|
||||
}
|
||||
if (!this.#requestValues) {
|
||||
this.#requestValues = {};
|
||||
}
|
||||
return this.#requestValues;
|
||||
}
|
||||
#ensureOutgoingMap() {
|
||||
if (!this.#outgoing) {
|
||||
this.#outgoing = /* @__PURE__ */ new Map();
|
||||
}
|
||||
return this.#outgoing;
|
||||
}
|
||||
#parse() {
|
||||
const raw = this.#request.headers.get("cookie");
|
||||
if (!raw) {
|
||||
return;
|
||||
}
|
||||
this.#requestValues = parse(raw);
|
||||
}
|
||||
}
|
||||
export {
|
||||
AstroCookies
|
||||
};
|
2
node_modules/astro/dist/core/cookies/index.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/core/cookies/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
export { AstroCookies } from './cookies.js';
|
||||
export { attachToResponse, getSetCookiesFromResponse } from './response.js';
|
7
node_modules/astro/dist/core/cookies/index.js
generated
vendored
Normal file
7
node_modules/astro/dist/core/cookies/index.js
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
import { AstroCookies } from "./cookies.js";
|
||||
import { attachToResponse, getSetCookiesFromResponse } from "./response.js";
|
||||
export {
|
||||
AstroCookies,
|
||||
attachToResponse,
|
||||
getSetCookiesFromResponse
|
||||
};
|
3
node_modules/astro/dist/core/cookies/response.d.ts
generated
vendored
Normal file
3
node_modules/astro/dist/core/cookies/response.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
import type { AstroCookies } from './cookies';
|
||||
export declare function attachToResponse(response: Response, cookies: AstroCookies): void;
|
||||
export declare function getSetCookiesFromResponse(response: Response): Generator<string, string[]>;
|
26
node_modules/astro/dist/core/cookies/response.js
generated
vendored
Normal file
26
node_modules/astro/dist/core/cookies/response.js
generated
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
const astroCookiesSymbol = Symbol.for("astro.cookies");
|
||||
function attachToResponse(response, cookies) {
|
||||
Reflect.set(response, astroCookiesSymbol, cookies);
|
||||
}
|
||||
function getFromResponse(response) {
|
||||
let cookies = Reflect.get(response, astroCookiesSymbol);
|
||||
if (cookies != null) {
|
||||
return cookies;
|
||||
} else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
function* getSetCookiesFromResponse(response) {
|
||||
const cookies = getFromResponse(response);
|
||||
if (!cookies) {
|
||||
return [];
|
||||
}
|
||||
for (const headerValue of cookies.headers()) {
|
||||
yield headerValue;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
export {
|
||||
attachToResponse,
|
||||
getSetCookiesFromResponse
|
||||
};
|
15
node_modules/astro/dist/core/create-vite.d.ts
generated
vendored
Normal file
15
node_modules/astro/dist/core/create-vite.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
/// <reference types="node" />
|
||||
import type { AstroSettings } from '../@types/astro';
|
||||
import type { LogOptions } from './logger/core';
|
||||
import nodeFs from 'node:fs';
|
||||
import * as vite from 'vite';
|
||||
interface CreateViteOptions {
|
||||
settings: AstroSettings;
|
||||
logging: LogOptions;
|
||||
mode: 'dev' | 'build' | string;
|
||||
command?: 'dev' | 'build';
|
||||
fs?: typeof nodeFs;
|
||||
}
|
||||
/** Return a common starting point for all Vite actions */
|
||||
export declare function createVite(commandConfig: vite.InlineConfig, { settings, logging, mode, command, fs }: CreateViteOptions): Promise<vite.InlineConfig>;
|
||||
export {};
|
253
node_modules/astro/dist/core/create-vite.js
generated
vendored
Normal file
253
node_modules/astro/dist/core/create-vite.js
generated
vendored
Normal file
|
@ -0,0 +1,253 @@
|
|||
import nodeFs from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as vite from "vite";
|
||||
import { crawlFrameworkPkgs } from "vitefu";
|
||||
import astroAssetsPlugin from "../assets/vite-plugin-assets.js";
|
||||
import {
|
||||
astroContentAssetPropagationPlugin,
|
||||
astroContentImportPlugin,
|
||||
astroContentVirtualModPlugin
|
||||
} from "../content/index.js";
|
||||
import astroPostprocessVitePlugin from "../vite-plugin-astro-postprocess/index.js";
|
||||
import { vitePluginAstroServer } from "../vite-plugin-astro-server/index.js";
|
||||
import astroVitePlugin from "../vite-plugin-astro/index.js";
|
||||
import configAliasVitePlugin from "../vite-plugin-config-alias/index.js";
|
||||
import envVitePlugin from "../vite-plugin-env/index.js";
|
||||
import astroHeadPlugin from "../vite-plugin-head/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";
|
||||
import markdownVitePlugin from "../vite-plugin-markdown/index.js";
|
||||
import astroScannerPlugin from "../vite-plugin-scanner/index.js";
|
||||
import astroScriptsPlugin from "../vite-plugin-scripts/index.js";
|
||||
import astroScriptsPageSSRPlugin from "../vite-plugin-scripts/page-ssr.js";
|
||||
import { vitePluginSSRManifest } from "../vite-plugin-ssr-manifest/index.js";
|
||||
import { joinPaths } from "./path.js";
|
||||
const ALWAYS_NOEXTERNAL = [
|
||||
// This is only because Vite's native ESM doesn't resolve "exports" correctly.
|
||||
"astro",
|
||||
// Vite fails on nested `.astro` imports without bundling
|
||||
"astro/components",
|
||||
// Handle recommended nanostores. Only @nanostores/preact is required from our testing!
|
||||
// Full explanation and related bug report: https://github.com/withastro/astro/pull/3667
|
||||
"@nanostores/preact",
|
||||
// fontsource packages are CSS that need to be processed
|
||||
"@fontsource/*"
|
||||
];
|
||||
const ONLY_DEV_EXTERNAL = [
|
||||
// Imported by `<Code/>` which is processed by Vite
|
||||
"shiki",
|
||||
// Imported by `@astrojs/prism` which exposes `<Prism/>` that is processed by Vite
|
||||
"prismjs/components/index.js",
|
||||
// Imported by `astro/assets` -> `packages/astro/src/core/logger/core.ts`
|
||||
"string-width"
|
||||
];
|
||||
async function createVite(commandConfig, { settings, logging, mode, command, fs = nodeFs }) {
|
||||
var _a, _b;
|
||||
const astroPkgsConfig = await crawlFrameworkPkgs({
|
||||
root: fileURLToPath(settings.config.root),
|
||||
isBuild: mode === "build",
|
||||
viteUserConfig: settings.config.vite,
|
||||
isFrameworkPkgByJson(pkgJson) {
|
||||
var _a2, _b2, _c, _d, _e;
|
||||
if (((_a2 = pkgJson == null ? void 0 : pkgJson.astro) == null ? void 0 : _a2.external) === true) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
// Attempt: package relies on `astro`. ✅ Definitely an Astro package
|
||||
((_b2 = pkgJson.peerDependencies) == null ? void 0 : _b2.astro) || ((_c = pkgJson.dependencies) == null ? void 0 : _c.astro) || // Attempt: package is tagged with `astro` or `astro-component`. ✅ Likely a community package
|
||||
((_d = pkgJson.keywords) == null ? void 0 : _d.includes("astro")) || ((_e = pkgJson.keywords) == null ? void 0 : _e.includes("astro-component")) || // Attempt: package is named `astro-something` or `@scope/astro-something`. ✅ Likely a community package
|
||||
/^(@[^\/]+\/)?astro\-/.test(pkgJson.name)
|
||||
);
|
||||
},
|
||||
isFrameworkPkgByName(pkgName) {
|
||||
const isNotAstroPkg = isCommonNotAstro(pkgName);
|
||||
if (isNotAstroPkg) {
|
||||
return false;
|
||||
} else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
});
|
||||
const commonConfig = {
|
||||
cacheDir: fileURLToPath(new URL("./node_modules/.vite/", settings.config.root)),
|
||||
// using local caches allows Astro to be used in monorepos, etc.
|
||||
clearScreen: false,
|
||||
// we want to control the output, not Vite
|
||||
logLevel: "warn",
|
||||
// log warnings and errors only
|
||||
appType: "custom",
|
||||
optimizeDeps: {
|
||||
entries: ["src/**/*"],
|
||||
exclude: ["astro", "node-fetch"]
|
||||
},
|
||||
plugins: [
|
||||
configAliasVitePlugin({ settings }),
|
||||
astroLoadFallbackPlugin({ fs, root: settings.config.root }),
|
||||
astroVitePlugin({ settings, logging }),
|
||||
astroScriptsPlugin({ settings }),
|
||||
// The server plugin is for dev only and having it run during the build causes
|
||||
// the build to run very slow as the filewatcher is triggered often.
|
||||
mode !== "build" && vitePluginAstroServer({ settings, logging, fs }),
|
||||
envVitePlugin({ settings }),
|
||||
markdownVitePlugin({ settings, logging }),
|
||||
htmlVitePlugin(),
|
||||
jsxVitePlugin({ settings, logging }),
|
||||
astroPostprocessVitePlugin(),
|
||||
mode === "dev" && astroIntegrationsContainerPlugin({ settings, logging }),
|
||||
astroScriptsPageSSRPlugin({ settings }),
|
||||
astroHeadPlugin(),
|
||||
astroScannerPlugin({ settings }),
|
||||
astroInjectEnvTsPlugin({ settings, logging, fs }),
|
||||
astroContentVirtualModPlugin({ settings }),
|
||||
astroContentImportPlugin({ fs, settings }),
|
||||
astroContentAssetPropagationPlugin({ mode, settings }),
|
||||
vitePluginSSRManifest(),
|
||||
settings.config.experimental.assets ? [astroAssetsPlugin({ settings, logging, mode })] : []
|
||||
],
|
||||
publicDir: fileURLToPath(settings.config.publicDir),
|
||||
root: fileURLToPath(settings.config.root),
|
||||
envPrefix: ((_a = settings.config.vite) == null ? void 0 : _a.envPrefix) ?? "PUBLIC_",
|
||||
define: {
|
||||
"import.meta.env.SITE": settings.config.site ? JSON.stringify(settings.config.site) : "undefined"
|
||||
},
|
||||
server: {
|
||||
hmr: process.env.NODE_ENV === "test" || process.env.NODE_ENV === "production" ? false : void 0,
|
||||
// disable HMR for test
|
||||
// handle Vite URLs
|
||||
proxy: {
|
||||
// add proxies here
|
||||
},
|
||||
watch: {
|
||||
// Prevent watching during the build to speed it up
|
||||
ignored: mode === "build" ? ["**"] : void 0
|
||||
}
|
||||
},
|
||||
resolve: {
|
||||
alias: [
|
||||
{
|
||||
// This is needed for Deno compatibility, as the non-browser version
|
||||
// of this module depends on Node `crypto`
|
||||
find: "randombytes",
|
||||
replacement: "randombytes/browser"
|
||||
},
|
||||
{
|
||||
// Typings are imported from 'astro' (e.g. import { Type } from 'astro')
|
||||
find: /^astro$/,
|
||||
replacement: fileURLToPath(new URL("../@types/astro", import.meta.url))
|
||||
}
|
||||
],
|
||||
conditions: ["astro"],
|
||||
// Astro imports in third-party packages should use the same version as root
|
||||
dedupe: ["astro"]
|
||||
},
|
||||
ssr: {
|
||||
noExternal: [...ALWAYS_NOEXTERNAL, ...astroPkgsConfig.ssr.noExternal],
|
||||
external: [...mode === "dev" ? ONLY_DEV_EXTERNAL : [], ...astroPkgsConfig.ssr.external]
|
||||
}
|
||||
};
|
||||
const assetsPrefix = settings.config.build.assetsPrefix;
|
||||
if (assetsPrefix) {
|
||||
commonConfig.experimental = {
|
||||
renderBuiltUrl(filename, { type }) {
|
||||
if (type === "asset") {
|
||||
return joinPaths(assetsPrefix, filename);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
let result = commonConfig;
|
||||
if (command && ((_b = settings.config.vite) == null ? void 0 : _b.plugins)) {
|
||||
let { plugins, ...rest } = settings.config.vite;
|
||||
const applyToFilter = command === "build" ? "serve" : "build";
|
||||
const applyArgs = [
|
||||
{ ...settings.config.vite, mode },
|
||||
{ command: command === "dev" ? "serve" : command, mode }
|
||||
];
|
||||
plugins = plugins.flat(Infinity).filter((p) => {
|
||||
if (!p || (p == null ? void 0 : p.apply) === applyToFilter) {
|
||||
return false;
|
||||
}
|
||||
if (typeof p.apply === "function") {
|
||||
return p.apply(applyArgs[0], applyArgs[1]);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
result = vite.mergeConfig(result, { ...rest, plugins });
|
||||
} else {
|
||||
result = vite.mergeConfig(result, settings.config.vite || {});
|
||||
}
|
||||
result = vite.mergeConfig(result, commandConfig);
|
||||
if (result.plugins) {
|
||||
sortPlugins(result.plugins);
|
||||
}
|
||||
result.customLogger = vite.createLogger(result.logLevel ?? "warn");
|
||||
return result;
|
||||
}
|
||||
function isVitePlugin(plugin) {
|
||||
return Boolean(plugin == null ? void 0 : plugin.hasOwnProperty("name"));
|
||||
}
|
||||
function findPluginIndexByName(pluginOptions, name) {
|
||||
return pluginOptions.findIndex(function(pluginOption) {
|
||||
return isVitePlugin(pluginOption) && pluginOption.name === name;
|
||||
});
|
||||
}
|
||||
function sortPlugins(pluginOptions) {
|
||||
const mdxPluginIndex = findPluginIndexByName(pluginOptions, "@mdx-js/rollup");
|
||||
if (mdxPluginIndex === -1)
|
||||
return;
|
||||
const jsxPluginIndex = findPluginIndexByName(pluginOptions, "astro:jsx");
|
||||
const mdxPlugin = pluginOptions[mdxPluginIndex];
|
||||
pluginOptions.splice(mdxPluginIndex, 1);
|
||||
pluginOptions.splice(jsxPluginIndex, 0, mdxPlugin);
|
||||
}
|
||||
const COMMON_DEPENDENCIES_NOT_ASTRO = [
|
||||
"autoprefixer",
|
||||
"react",
|
||||
"react-dom",
|
||||
"preact",
|
||||
"preact-render-to-string",
|
||||
"vue",
|
||||
"svelte",
|
||||
"solid-js",
|
||||
"lit",
|
||||
"cookie",
|
||||
"dotenv",
|
||||
"esbuild",
|
||||
"eslint",
|
||||
"jest",
|
||||
"postcss",
|
||||
"prettier",
|
||||
"astro",
|
||||
"tslib",
|
||||
"typescript",
|
||||
"vite"
|
||||
];
|
||||
const COMMON_PREFIXES_NOT_ASTRO = [
|
||||
"@webcomponents/",
|
||||
"@fontsource/",
|
||||
"@postcss-plugins/",
|
||||
"@rollup/",
|
||||
"@astrojs/renderer-",
|
||||
"@types/",
|
||||
"@typescript-eslint/",
|
||||
"eslint-",
|
||||
"jest-",
|
||||
"postcss-plugin-",
|
||||
"prettier-plugin-",
|
||||
"remark-",
|
||||
"rehype-",
|
||||
"rollup-plugin-",
|
||||
"vite-plugin-"
|
||||
];
|
||||
function isCommonNotAstro(dep) {
|
||||
return COMMON_DEPENDENCIES_NOT_ASTRO.includes(dep) || COMMON_PREFIXES_NOT_ASTRO.some(
|
||||
(prefix) => prefix.startsWith("@") ? dep.startsWith(prefix) : dep.substring(dep.lastIndexOf("/") + 1).startsWith(prefix)
|
||||
// check prefix omitting @scope/
|
||||
);
|
||||
}
|
||||
export {
|
||||
createVite
|
||||
};
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue