astro 2.5.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,14 +49,22 @@ async function createContentTypesGenerator({
49
49
  fs: {
50
50
  readdir: fs.readdir.bind(fs),
51
51
  readdirSync: fs.readdirSync.bind(fs)
52
- }
52
+ },
53
+ onlyFiles: false,
54
+ objectMode: true
53
55
  });
54
- const entries = globResult.map((e) => new URL(e, contentPaths.contentDir)).filter(
55
- // Config loading handled first. Avoid running twice.
56
- (e) => !e.href.startsWith(contentPaths.config.url.href)
57
- );
58
- for (const entry of entries) {
59
- events.push({ type: { name: "add", entry }, opts: { logLevel: "warn" } });
56
+ for (const entry of globResult) {
57
+ const entryURL = new URL(entry.path, contentPaths.contentDir);
58
+ if (entryURL.href.startsWith(contentPaths.config.url.href))
59
+ continue;
60
+ if (entry.dirent.isFile()) {
61
+ events.push({
62
+ type: { name: "add", entry: entryURL },
63
+ opts: { logLevel: "warn" }
64
+ });
65
+ } else if (entry.dirent.isDirectory()) {
66
+ events.push({ type: { name: "addDir", entry: entryURL }, opts: { logLevel: "warn" } });
67
+ }
60
68
  }
61
69
  await runEvents();
62
70
  return { typesGenerated: true };
@@ -416,9 +424,9 @@ function warnNonexistentCollections({
416
424
  warn(
417
425
  logging,
418
426
  "content",
419
- `${JSON.stringify(
427
+ `The ${JSON.stringify(
420
428
  configuredCollection
421
- )} is not a collection. Check your content config for typos.`
429
+ )} collection does not have an associated folder in your \`content\` directory. Make sure the folder exists, or check your content config for typos.`
422
430
  );
423
431
  }
424
432
  }
@@ -115,13 +115,13 @@ class App {
115
115
  if (routeData.route === "/404") {
116
116
  defaultStatus = 404;
117
117
  }
118
- let mod = this.#manifest.pageMap.get(routeData.component);
118
+ let mod = await this.#manifest.pageMap.get(routeData.component)();
119
119
  if (routeData.type === "page") {
120
120
  let response = await this.#renderPage(request, routeData, mod, defaultStatus);
121
121
  if (response.status === 500) {
122
122
  const fiveHundredRouteData = matchRoute("/500", this.#manifestData);
123
123
  if (fiveHundredRouteData) {
124
- mod = this.#manifest.pageMap.get(fiveHundredRouteData.component);
124
+ mod = await this.#manifest.pageMap.get(fiveHundredRouteData.component)();
125
125
  try {
126
126
  let fiveHundredResponse = await this.#renderPage(
127
127
  request,
@@ -24,6 +24,7 @@ export interface RouteInfo {
24
24
  export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
25
25
  routeData: SerializedRouteData;
26
26
  };
27
+ type ImportComponentInstance = () => Promise<ComponentInstance>;
27
28
  export interface SSRManifest {
28
29
  adapterName: string;
29
30
  routes: RouteInfo[];
@@ -31,7 +32,7 @@ export interface SSRManifest {
31
32
  base?: string;
32
33
  assetsPrefix?: string;
33
34
  markdown: MarkdownRenderingOptions;
34
- pageMap: Map<ComponentPath, ComponentInstance>;
35
+ pageMap: Map<ComponentPath, ImportComponentInstance>;
35
36
  renderers: SSRLoadedRenderer[];
36
37
  /**
37
38
  * Map of directive name (e.g. `load`) to the directive script code
@@ -49,3 +50,4 @@ export type SerializedSSRManifest = Omit<SSRManifest, 'routes' | 'assets' | 'com
49
50
  clientDirectives: [string, string][];
50
51
  };
51
52
  export type AdapterCreateExports<T = any> = (manifest: SSRManifest, args?: T) => Record<string, any>;
53
+ export {};
@@ -115,13 +115,14 @@ async function generatePage(opts, internals, pageData, ssrEntry, builtPaths) {
115
115
  const linkIds = [];
116
116
  const scripts = (pageInfo == null ? void 0 : pageInfo.hoistedScript) ?? null;
117
117
  const styles = pageData.styles.sort(cssOrder).map(({ sheet }) => sheet).reduce(mergeInlineCss, []);
118
- const pageModule = (_a = ssrEntry.pageMap) == null ? void 0 : _a.get(pageData.component);
118
+ const pageModulePromise = (_a = ssrEntry.pageMap) == null ? void 0 : _a.get(pageData.component);
119
119
  const middleware = ssrEntry.middleware;
120
- if (!pageModule) {
120
+ if (!pageModulePromise) {
121
121
  throw new Error(
122
122
  `Unable to find the module for ${pageData.component}. This is unexpected and likely a bug in Astro, please report.`
123
123
  );
124
124
  }
125
+ const pageModule = await pageModulePromise();
125
126
  if (shouldSkipDraft(pageModule, opts.settings)) {
126
127
  info(opts.logging, null, `${magenta("\u26A0\uFE0F")} Skipping draft ${pageData.route.component}`);
127
128
  return;
@@ -25,7 +25,7 @@ function* walkParentInfos(id, ctx, until, depth = 0, order = 0, seen = /* @__PUR
25
25
  }
26
26
  }
27
27
  function moduleIsTopLevelPage(info) {
28
- return info.importers[0] === resolvedPagesVirtualModuleId;
28
+ return info.importers[0] === resolvedPagesVirtualModuleId || info.dynamicImporters[0] == resolvedPagesVirtualModuleId;
29
29
  }
30
30
  function* getTopLevelPages(id, ctx) {
31
31
  for (const res of walkParentInfos(id, ctx)) {
@@ -6,6 +6,7 @@ import { pluginComponentEntry } from "./plugin-component-entry.js";
6
6
  import { pluginCSS } from "./plugin-css.js";
7
7
  import { pluginHoistedScripts } from "./plugin-hoisted-scripts.js";
8
8
  import { pluginInternals } from "./plugin-internals.js";
9
+ import { pluginMiddleware } from "./plugin-middleware.js";
9
10
  import { pluginPages } from "./plugin-pages.js";
10
11
  import { pluginPrerender } from "./plugin-prerender.js";
11
12
  import { pluginSSR } from "./plugin-ssr.js";
@@ -14,6 +15,7 @@ function registerAllPlugins({ internals, options, register }) {
14
15
  register(pluginAliasResolve(internals));
15
16
  register(pluginAnalyzer(internals));
16
17
  register(pluginInternals(internals));
18
+ register(pluginMiddleware(options, internals));
17
19
  register(pluginPages(options, internals));
18
20
  register(pluginCSS(options, internals));
19
21
  register(astroHeadBuildPlugin(options, internals));
@@ -0,0 +1,8 @@
1
+ import type { Plugin as VitePlugin } from 'vite';
2
+ import type { BuildInternals } from '../internal.js';
3
+ import type { AstroBuildPlugin } from '../plugin';
4
+ import type { StaticBuildOptions } from '../types';
5
+ export declare const MIDDLEWARE_MODULE_ID = "@astro-middleware";
6
+ export declare const RESOLVED_MIDDLEWARE_MODULE_ID = "\0@astro-middleware";
7
+ export declare function vitePluginMiddleware(opts: StaticBuildOptions, _internals: BuildInternals): VitePlugin;
8
+ export declare function pluginMiddleware(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
@@ -0,0 +1,53 @@
1
+ import { MIDDLEWARE_PATH_SEGMENT_NAME } from "../../constants.js";
2
+ import { addRollupInput } from "../add-rollup-input.js";
3
+ const MIDDLEWARE_MODULE_ID = "@astro-middleware";
4
+ const RESOLVED_MIDDLEWARE_MODULE_ID = "\0@astro-middleware";
5
+ let inputs = /* @__PURE__ */ new Set();
6
+ function vitePluginMiddleware(opts, _internals) {
7
+ return {
8
+ name: "@astro/plugin-middleware",
9
+ options(options) {
10
+ if (opts.settings.config.experimental.middleware) {
11
+ return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
12
+ }
13
+ },
14
+ resolveId(id) {
15
+ if (id === MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
16
+ return RESOLVED_MIDDLEWARE_MODULE_ID;
17
+ }
18
+ },
19
+ async load(id) {
20
+ if (id === RESOLVED_MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
21
+ const imports = [];
22
+ const exports = [];
23
+ let middlewareId = await this.resolve(
24
+ `${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
25
+ );
26
+ if (middlewareId) {
27
+ imports.push(`import { onRequest } from "${middlewareId.id}"`);
28
+ exports.push(`export { onRequest }`);
29
+ }
30
+ const result = [imports.join("\n"), exports.join("\n")];
31
+ return result.join("\n");
32
+ }
33
+ }
34
+ };
35
+ }
36
+ function pluginMiddleware(opts, internals) {
37
+ return {
38
+ build: "ssr",
39
+ hooks: {
40
+ "build:before": () => {
41
+ return {
42
+ vitePlugin: vitePluginMiddleware(opts, internals)
43
+ };
44
+ }
45
+ }
46
+ };
47
+ }
48
+ export {
49
+ MIDDLEWARE_MODULE_ID,
50
+ RESOLVED_MIDDLEWARE_MODULE_ID,
51
+ pluginMiddleware,
52
+ vitePluginMiddleware
53
+ };
@@ -1,7 +1,7 @@
1
1
  import { pagesVirtualModuleId, resolvedPagesVirtualModuleId } from "../../app/index.js";
2
- import { MIDDLEWARE_PATH_SEGMENT_NAME } from "../../constants.js";
3
2
  import { addRollupInput } from "../add-rollup-input.js";
4
3
  import { eachPageData } from "../internal.js";
4
+ import { MIDDLEWARE_MODULE_ID } from "./plugin-middleware.js";
5
5
  function vitePluginPages(opts, internals) {
6
6
  return {
7
7
  name: "@astro/plugin-build-pages",
@@ -17,18 +17,14 @@ function vitePluginPages(opts, internals) {
17
17
  },
18
18
  async load(id) {
19
19
  if (id === resolvedPagesVirtualModuleId) {
20
- let middlewareId = null;
21
- if (opts.settings.config.experimental.middleware) {
22
- middlewareId = await this.resolve(
23
- `${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
24
- );
25
- }
26
20
  let importMap = "";
27
21
  let imports = [];
28
22
  let i = 0;
29
23
  for (const pageData of eachPageData(internals)) {
30
24
  const variable = `_page${i}`;
31
- imports.push(`import * as ${variable} from ${JSON.stringify(pageData.moduleSpecifier)};`);
25
+ imports.push(
26
+ `const ${variable} = () => import(${JSON.stringify(pageData.moduleSpecifier)});`
27
+ );
32
28
  importMap += `[${JSON.stringify(pageData.component)}, ${variable}],`;
33
29
  i++;
34
30
  }
@@ -42,11 +38,11 @@ function vitePluginPages(opts, internals) {
42
38
  }
43
39
  const def = `${imports.join("\n")}
44
40
 
45
- ${middlewareId ? `import * as _middleware from "${middlewareId.id}";` : ""}
41
+ ${opts.settings.config.experimental.middleware ? `import * as _middleware from "${MIDDLEWARE_MODULE_ID}";` : ""}
46
42
 
47
43
  export const pageMap = new Map([${importMap}]);
48
44
  export const renderers = [${rendererItems}];
49
- ${middlewareId ? `export const middleware = _middleware;` : ""}
45
+ ${opts.settings.config.experimental.middleware ? `export const middleware = _middleware;` : ""}
50
46
  `;
51
47
  return def;
52
48
  }
@@ -1,3 +1,4 @@
1
+ import path from "node:path";
1
2
  import { extendManualChunks } from "./util.js";
2
3
  function vitePluginPrerender(opts, internals) {
3
4
  return {
@@ -16,7 +17,7 @@ function vitePluginPrerender(opts, internals) {
16
17
  return "prerender";
17
18
  }
18
19
  pageInfo.route.prerender = false;
19
- return `pages/all`;
20
+ return `pages/${path.basename(pageInfo.component)}`;
20
21
  }
21
22
  }
22
23
  });
@@ -8,7 +8,7 @@ import { joinPaths, prependForwardSlash } from "../../path.js";
8
8
  import { serializeRouteData } from "../../routing/index.js";
9
9
  import { addRollupInput } from "../add-rollup-input.js";
10
10
  import { getOutFile, getOutFolder } from "../common.js";
11
- import { cssOrder, eachPageData, mergeInlineCss } from "../internal.js";
11
+ import { cssOrder, mergeInlineCss } from "../internal.js";
12
12
  const virtualModuleId = "@astrojs-ssr-virtual-entry";
13
13
  const resolvedVirtualModuleId = "\0" + virtualModuleId;
14
14
  const manifestReplace = "@@ASTRO_MANIFEST_REPLACE@@";
@@ -118,34 +118,26 @@ function buildManifest(opts, internals, staticFiles) {
118
118
  return prependForwardSlash(joinPaths(settings.config.base, pth));
119
119
  }
120
120
  };
121
- for (const pageData of eachPageData(internals)) {
122
- if (!pageData.route.prerender)
121
+ for (const route of opts.manifest.routes) {
122
+ if (!route.prerender)
123
123
  continue;
124
- if (!pageData.route.pathname)
124
+ if (!route.pathname)
125
125
  continue;
126
- const outFolder = getOutFolder(
127
- opts.settings.config,
128
- pageData.route.pathname,
129
- pageData.route.type
130
- );
131
- const outFile = getOutFile(
132
- opts.settings.config,
133
- outFolder,
134
- pageData.route.pathname,
135
- pageData.route.type
136
- );
126
+ const outFolder = getOutFolder(opts.settings.config, route.pathname, route.type);
127
+ const outFile = getOutFile(opts.settings.config, outFolder, route.pathname, route.type);
137
128
  const file = outFile.toString().replace(opts.settings.config.build.client.toString(), "");
138
129
  routes.push({
139
130
  file,
140
131
  links: [],
141
132
  scripts: [],
142
133
  styles: [],
143
- routeData: serializeRouteData(pageData.route, settings.config.trailingSlash)
134
+ routeData: serializeRouteData(route, settings.config.trailingSlash)
144
135
  });
145
136
  staticFiles.push(file);
146
137
  }
147
- for (const pageData of eachPageData(internals)) {
148
- if (pageData.route.prerender)
138
+ for (const route of opts.manifest.routes) {
139
+ const pageData = internals.pagesByComponent.get(route.component);
140
+ if (route.prerender || !pageData)
149
141
  continue;
150
142
  const scripts = [];
151
143
  if (pageData.hoistedScript) {
@@ -174,7 +166,7 @@ function buildManifest(opts, internals, staticFiles) {
174
166
  ...settings.scripts.filter((script) => script.stage === "head-inline").map(({ stage, content }) => ({ stage, children: content }))
175
167
  ],
176
168
  styles,
177
- routeData: serializeRouteData(pageData.route, settings.config.trailingSlash)
169
+ routeData: serializeRouteData(route, settings.config.trailingSlash)
178
170
  });
179
171
  }
180
172
  if (!(BEFORE_HYDRATION_SCRIPT_ID in entryModules)) {
@@ -24,6 +24,7 @@ import { generatePages } from "./generate.js";
24
24
  import { trackPageData } from "./internal.js";
25
25
  import { createPluginContainer } from "./plugin.js";
26
26
  import { registerAllPlugins } from "./plugins/index.js";
27
+ import { RESOLVED_MIDDLEWARE_MODULE_ID } from "./plugins/plugin-middleware.js";
27
28
  import { getTimeStat } from "./util.js";
28
29
  async function viteBuild(opts) {
29
30
  var _a, _b, _c;
@@ -129,6 +130,8 @@ async function ssrBuild(opts, internals, input, container) {
129
130
  entryFileNames(chunkInfo) {
130
131
  if (chunkInfo.facadeModuleId === resolvedPagesVirtualModuleId) {
131
132
  return opts.buildConfig.serverEntry;
133
+ } else if (chunkInfo.facadeModuleId === RESOLVED_MIDDLEWARE_MODULE_ID) {
134
+ return "middleware.mjs";
132
135
  } else {
133
136
  return "[name].mjs";
134
137
  }
@@ -43,8 +43,9 @@ export interface StaticBuildOptions {
43
43
  viteConfig: InlineConfig;
44
44
  teardownCompiler: boolean;
45
45
  }
46
+ type ImportComponentInstance = () => Promise<ComponentInstance>;
46
47
  export interface SingleFileBuiltModule {
47
- pageMap: Map<ComponentPath, ComponentInstance>;
48
+ pageMap: Map<ComponentPath, ImportComponentInstance>;
48
49
  middleware: AstroMiddlewareInstance<unknown>;
49
50
  renderers: SSRLoadedRenderer[];
50
51
  }
@@ -55,3 +56,4 @@ export type RollupOutput = Extract<Extract<ViteBuildReturn, Exclude<ViteBuildRet
55
56
  export type OutputChunk = Extract<RollupOutput['output'][number], {
56
57
  type: 'chunk';
57
58
  }>;
59
+ export {};
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "2.5.0";
1
+ const ASTRO_VERSION = "2.5.1";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -53,7 +53,7 @@ async function dev(settings, options) {
53
53
  isRestart: options.isRestart
54
54
  })
55
55
  );
56
- const currentVersion = "2.5.0";
56
+ const currentVersion = "2.5.1";
57
57
  if (currentVersion.includes("-")) {
58
58
  warn(options.logging, null, msg.prerelease({ currentVersion }));
59
59
  }
@@ -47,7 +47,7 @@ function serverStart({
47
47
  base,
48
48
  isRestart = false
49
49
  }) {
50
- const version = "2.5.0";
50
+ const version = "2.5.1";
51
51
  const localPrefix = `${dim("\u2503")} Local `;
52
52
  const networkPrefix = `${dim("\u2503")} Network `;
53
53
  const emptyPrefix = " ".repeat(11);
@@ -233,7 +233,7 @@ function printHelp({
233
233
  message.push(
234
234
  linebreak(),
235
235
  ` ${bgGreen(black(` ${commandName} `))} ${green(
236
- `v${"2.5.0"}`
236
+ `v${"2.5.1"}`
237
237
  )} ${headline}`
238
238
  );
239
239
  }
@@ -1,3 +1,4 @@
1
+ import { bold } from "kleur/colors";
1
2
  import { AstroError, AstroErrorData } from "../errors/index.js";
2
3
  import { warn } from "../logger/core.js";
3
4
  const VALID_PARAM_TYPES = ["string", "number", "undefined"];
@@ -18,7 +19,11 @@ function validateDynamicRouteModule(mod, {
18
19
  route
19
20
  }) {
20
21
  if (ssr && mod.getStaticPaths && !mod.prerender) {
21
- warn(logging, "getStaticPaths", 'getStaticPaths() is ignored when "output: server" is set.');
22
+ warn(
23
+ logging,
24
+ "getStaticPaths",
25
+ `getStaticPaths() in ${bold(route.component)} is ignored when "output: server" is set.`
26
+ );
22
27
  }
23
28
  if ((!ssr || mod.prerender) && !mod.getStaticPaths) {
24
29
  throw new AstroError({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "2.5.0",
3
+ "version": "2.5.1",
4
4
  "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.",
5
5
  "type": "module",
6
6
  "author": "withastro",