astro 0.25.3 → 0.26.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.
Files changed (111) hide show
  1. package/astro.js +12 -4
  2. package/dist/cli/check.js +4 -4
  3. package/dist/cli/index.js +21 -32
  4. package/dist/core/add/index.js +36 -20
  5. package/dist/core/app/index.js +17 -11
  6. package/dist/core/build/common.js +4 -5
  7. package/dist/core/build/generate.js +69 -73
  8. package/dist/core/build/index.js +90 -77
  9. package/dist/core/build/page-data.js +10 -9
  10. package/dist/core/build/static-build.js +41 -24
  11. package/dist/core/build/vite-plugin-hoisted-scripts.js +1 -1
  12. package/dist/core/build/vite-plugin-ssr.js +5 -2
  13. package/dist/core/config.js +89 -79
  14. package/dist/core/create-vite.js +17 -8
  15. package/dist/core/dev/index.js +22 -9
  16. package/dist/core/endpoint/dev/index.js +5 -10
  17. package/dist/core/endpoint/index.js +1 -3
  18. package/dist/core/errors.js +45 -0
  19. package/dist/core/logger/console.js +43 -0
  20. package/dist/core/logger/core.js +103 -0
  21. package/dist/core/logger/node.js +94 -0
  22. package/dist/core/messages.js +79 -28
  23. package/dist/core/preview/index.js +15 -9
  24. package/dist/core/preview/util.js +3 -6
  25. package/dist/core/render/core.js +21 -6
  26. package/dist/core/render/dev/css.js +5 -6
  27. package/dist/core/render/dev/index.js +43 -38
  28. package/dist/core/render/paginate.js +3 -1
  29. package/dist/core/render/pretty-feed.js +103 -0
  30. package/dist/core/render/result.js +33 -15
  31. package/dist/core/render/route-cache.js +12 -3
  32. package/dist/core/render/rss.js +5 -4
  33. package/dist/core/render/ssr-element.js +1 -1
  34. package/dist/core/render/util.js +35 -0
  35. package/dist/core/request.js +33 -0
  36. package/dist/core/routing/manifest/create.js +8 -6
  37. package/dist/core/routing/validation.js +1 -1
  38. package/dist/core/util.js +57 -125
  39. package/dist/integrations/index.js +38 -6
  40. package/dist/runtime/server/index.js +51 -41
  41. package/dist/template/4xx.js +8 -2
  42. package/dist/template/5xx.js +8 -1
  43. package/dist/types/@types/astro.d.ts +290 -232
  44. package/dist/types/cli/index.d.ts +1 -1
  45. package/dist/types/core/add/index.d.ts +1 -1
  46. package/dist/types/core/build/common.d.ts +0 -1
  47. package/dist/types/core/build/generate.d.ts +1 -1
  48. package/dist/types/core/build/index.d.ts +1 -1
  49. package/dist/types/core/build/page-data.d.ts +1 -1
  50. package/dist/types/core/config.d.ts +125 -116
  51. package/dist/types/core/create-vite.d.ts +1 -1
  52. package/dist/types/core/dev/index.d.ts +1 -1
  53. package/dist/types/core/endpoint/index.d.ts +1 -1
  54. package/dist/types/core/errors.d.ts +23 -0
  55. package/dist/types/core/logger/console.d.ts +4 -0
  56. package/dist/types/core/{logger.d.ts → logger/core.d.ts} +7 -22
  57. package/dist/types/core/logger/node.d.ts +34 -0
  58. package/dist/types/core/messages.d.ts +5 -3
  59. package/dist/types/core/preview/index.d.ts +1 -1
  60. package/dist/types/core/preview/util.d.ts +1 -2
  61. package/dist/types/core/render/core.d.ts +2 -3
  62. package/dist/types/core/render/dev/css.d.ts +0 -2
  63. package/dist/types/core/render/dev/index.d.ts +5 -7
  64. package/dist/types/core/render/pretty-feed.d.ts +2 -0
  65. package/dist/types/core/render/result.d.ts +2 -3
  66. package/dist/types/core/render/route-cache.d.ts +2 -2
  67. package/dist/types/core/render/util.d.ts +6 -0
  68. package/dist/types/core/request.d.ts +14 -0
  69. package/dist/types/core/routing/manifest/create.d.ts +1 -1
  70. package/dist/types/core/routing/validation.d.ts +1 -1
  71. package/dist/types/core/util.d.ts +11 -7
  72. package/dist/types/integrations/index.d.ts +11 -5
  73. package/dist/types/runtime/server/index.d.ts +1 -2
  74. package/dist/types/template/4xx.d.ts +1 -1
  75. package/dist/types/template/5xx.d.ts +1 -1
  76. package/dist/types/vite-plugin-astro/hmr.d.ts +1 -1
  77. package/dist/types/vite-plugin-astro/index.d.ts +1 -1
  78. package/dist/types/vite-plugin-astro/styles.d.ts +1 -1
  79. package/dist/types/vite-plugin-astro-server/index.d.ts +1 -1
  80. package/dist/types/vite-plugin-build-html/extract-assets.d.ts +1 -1
  81. package/dist/types/vite-plugin-build-html/index.d.ts +3 -3
  82. package/dist/types/vite-plugin-config-alias/index.d.ts +1 -1
  83. package/dist/types/vite-plugin-env/index.d.ts +1 -1
  84. package/dist/types/vite-plugin-integrations-container/index.d.ts +1 -1
  85. package/dist/types/vite-plugin-jsx/index.d.ts +1 -1
  86. package/dist/vite-plugin-astro/compile.js +12 -14
  87. package/dist/vite-plugin-astro/hmr.js +2 -2
  88. package/dist/vite-plugin-astro/index.js +41 -13
  89. package/dist/vite-plugin-astro/styles.js +8 -2
  90. package/dist/vite-plugin-astro-postprocess/index.js +35 -34
  91. package/dist/vite-plugin-astro-server/index.js +66 -25
  92. package/dist/vite-plugin-build-css/index.js +6 -2
  93. package/dist/vite-plugin-build-html/index.js +43 -23
  94. package/dist/vite-plugin-config-alias/index.js +4 -2
  95. package/dist/vite-plugin-env/index.js +8 -3
  96. package/dist/vite-plugin-integrations-container/index.js +3 -1
  97. package/dist/vite-plugin-jsx/index.js +22 -4
  98. package/dist/vite-plugin-markdown/index.js +93 -18
  99. package/env.d.ts +1 -1
  100. package/package.json +13 -9
  101. package/dist/core/build/scan-based-build.js +0 -62
  102. package/dist/core/dev/util.js +0 -44
  103. package/dist/core/logger.js +0 -174
  104. package/dist/core/render/dev/error.js +0 -34
  105. package/dist/core/render/request.js +0 -23
  106. package/dist/core/render/sitemap.js +0 -18
  107. package/dist/types/core/build/scan-based-build.d.ts +0 -18
  108. package/dist/types/core/dev/util.d.ts +0 -9
  109. package/dist/types/core/render/dev/error.d.ts +0 -7
  110. package/dist/types/core/render/request.d.ts +0 -15
  111. package/dist/types/core/render/sitemap.d.ts +0 -2
@@ -1,8 +1,8 @@
1
+ import type { Plugin as VitePlugin, ViteDevServer } from 'vite';
1
2
  import type { AstroConfig } from '../@types/astro';
2
- import type { LogOptions } from '../core/logger.js';
3
- import type { ViteDevServer, Plugin as VitePlugin } from 'vite';
4
- import type { AllPagesData } from '../core/build/types';
5
3
  import type { BuildInternals } from '../core/build/internal';
4
+ import type { AllPagesData } from '../core/build/types';
5
+ import type { LogOptions } from '../core/logger/core.js';
6
6
  import { RouteCache } from '../core/render/route-cache.js';
7
7
  interface PluginOptions {
8
8
  astroConfig: AstroConfig;
@@ -6,6 +6,6 @@ export declare interface Alias {
6
6
  }
7
7
  /** Returns a Vite plugin used to alias pathes from tsconfig.json and jsconfig.json. */
8
8
  export default function configAliasVitePlugin(astroConfig: {
9
- projectRoot?: URL;
9
+ root?: URL;
10
10
  [key: string]: unknown;
11
11
  }): vite.PluginOption;
@@ -3,5 +3,5 @@ import type { AstroConfig } from '../@types/astro';
3
3
  interface EnvPluginOptions {
4
4
  config: AstroConfig;
5
5
  }
6
- export default function envVitePlugin({ config: astroConfig }: EnvPluginOptions): vite.PluginOption;
6
+ export default function envVitePlugin({ config: astroConfig, }: EnvPluginOptions): vite.PluginOption;
7
7
  export {};
@@ -1,6 +1,6 @@
1
1
  import { Plugin as VitePlugin } from 'vite';
2
2
  import { AstroConfig } from '../@types/astro.js';
3
3
  /** Connect Astro integrations into Vite, as needed. */
4
- export default function astroIntegrationsContainerPlugin({ config }: {
4
+ export default function astroIntegrationsContainerPlugin({ config, }: {
5
5
  config: AstroConfig;
6
6
  }): VitePlugin;
@@ -1,6 +1,6 @@
1
1
  import type { Plugin } from 'vite';
2
2
  import type { AstroConfig } from '../@types/astro';
3
- import type { LogOptions } from '../core/logger.js';
3
+ import type { LogOptions } from '../core/logger/core.js';
4
4
  interface AstroPluginJSXOptions {
5
5
  config: AstroConfig;
6
6
  logging: LogOptions;
@@ -13,30 +13,28 @@ const configCache = /* @__PURE__ */ new WeakMap();
13
13
  async function compile(config, filename, source, viteTransform, opts) {
14
14
  const filenameURL = new URL(`file://${filename}`);
15
15
  const normalizedID = fileURLToPath(filenameURL);
16
- const pathname = filenameURL.pathname.substr(config.projectRoot.pathname.length - 1);
16
+ const pathname = filenameURL.pathname.substr(config.root.pathname.length - 1);
17
17
  let rawCSSDeps = /* @__PURE__ */ new Set();
18
18
  let cssTransformError;
19
19
  const transformResult = await transform(source, {
20
20
  pathname,
21
- projectRoot: config.projectRoot.toString(),
22
- site: config.buildOptions.site,
21
+ projectRoot: config.root.toString(),
22
+ site: config.site ? new URL(config.base, config.site).toString() : void 0,
23
23
  sourcefile: filename,
24
24
  sourcemap: "both",
25
25
  internalURL: `/@fs${prependForwardSlash(viteID(new URL("../runtime/server/index.js", import.meta.url)))}`,
26
- experimentalStaticExtraction: !config.buildOptions.legacyBuild,
26
+ experimentalStaticExtraction: true,
27
27
  preprocessStyle: async (value, attrs) => {
28
28
  const lang = `.${(attrs == null ? void 0 : attrs.lang) || "css"}`.toLowerCase();
29
29
  try {
30
- if (!config.buildOptions.legacyBuild) {
31
- value.replace(/(?:@import)\s(?:url\()?\s?["\'](.*?)["\']\s?\)?(?:[^;]*);?/gi, (match, spec) => {
32
- rawCSSDeps.add(spec);
33
- if (lang === ".css") {
34
- return createImportPlaceholder(spec);
35
- } else {
36
- return match;
37
- }
38
- });
39
- }
30
+ value.replace(/(?:@import)\s(?:url\()?\s?["\'](.*?)["\']\s?\)?(?:[^;]*);?/gi, (match, spec) => {
31
+ rawCSSDeps.add(spec);
32
+ if (lang === ".css") {
33
+ return createImportPlaceholder(spec);
34
+ } else {
35
+ return match;
36
+ }
37
+ });
40
38
  const result = await transformWithVite({
41
39
  value,
42
40
  lang,
@@ -1,5 +1,5 @@
1
1
  import { invalidateCompilation, isCached } from "./compile.js";
2
- import { info } from "../core/logger.js";
2
+ import { info } from "../core/logger/core.js";
3
3
  import * as msg from "../core/messages.js";
4
4
  async function trackCSSDependencies(opts) {
5
5
  const { viteDevServer, filename, deps, id } = opts;
@@ -46,7 +46,7 @@ async function handleHotUpdate(ctx, config, logging) {
46
46
  invalidateCompilation(config, file2);
47
47
  }
48
48
  const mod = ctx.modules.find((m) => m.file === ctx.file);
49
- const file = ctx.file.replace(config.projectRoot.pathname, "/");
49
+ const file = ctx.file.replace(config.root.pathname, "/");
50
50
  if (ctx.file.endsWith(".astro")) {
51
51
  ctx.server.ws.send({ type: "custom", event: "astro:update", data: { file } });
52
52
  }
@@ -9,25 +9,26 @@ import ancestor from "common-ancestor-path";
9
9
  import { trackCSSDependencies, handleHotUpdate } from "./hmr.js";
10
10
  import { isRelativePath, startsWithForwardSlash } from "../core/path.js";
11
11
  import { PAGE_SCRIPT_ID, PAGE_SSR_SCRIPT_ID } from "../vite-plugin-scripts/index.js";
12
+ import { resolvePages } from "../core/util.js";
12
13
  const FRONTMATTER_PARSE_REGEXP = /^\-\-\-(.*)^\-\-\-/ms;
13
14
  function astro({ config, logging }) {
14
15
  function normalizeFilename(filename) {
15
16
  if (filename.startsWith("/@fs")) {
16
17
  filename = filename.slice("/@fs".length);
17
- } else if (filename.startsWith("/") && !ancestor(filename, config.projectRoot.pathname)) {
18
- filename = new URL("." + filename, config.projectRoot).pathname;
18
+ } else if (filename.startsWith("/") && !ancestor(filename, config.root.pathname)) {
19
+ filename = new URL("." + filename, config.root).pathname;
19
20
  }
20
21
  return filename;
21
22
  }
22
23
  function relativeToRoot(pathname) {
23
24
  const arg = startsWithForwardSlash(pathname) ? "." + pathname : pathname;
24
- const url = new URL(arg, config.projectRoot);
25
+ const url = new URL(arg, config.root);
25
26
  return slash(fileURLToPath(url)) + url.search;
26
27
  }
27
28
  let resolvedConfig;
28
29
  let viteTransform;
29
30
  let viteDevServer = null;
30
- const srcRootWeb = config.src.pathname.slice(config.projectRoot.pathname.length - 1);
31
+ const srcRootWeb = config.srcDir.pathname.slice(config.root.pathname.length - 1);
31
32
  const isBrowserPath = (path) => path.startsWith(srcRootWeb);
32
33
  return {
33
34
  name: "astro:build",
@@ -60,6 +61,7 @@ function astro({ config, logging }) {
60
61
  }
61
62
  },
62
63
  async load(id, opts) {
64
+ var _a;
63
65
  const parsedId = parseAstroRequest(id);
64
66
  const query = parsedId.query;
65
67
  if (!id.endsWith(".astro") && !query.astro) {
@@ -68,18 +70,25 @@ function astro({ config, logging }) {
68
70
  const filename = normalizeFilename(parsedId.filename);
69
71
  const fileUrl = new URL(`file://${filename}`);
70
72
  let source = await fs.promises.readFile(fileUrl, "utf-8");
71
- const isPage = fileUrl.pathname.startsWith(config.pages.pathname);
73
+ const isPage = fileUrl.pathname.startsWith(resolvePages(config).pathname);
72
74
  if (isPage && config._ctx.scripts.some((s) => s.stage === "page")) {
73
75
  source += `
74
- <script hoist src="${PAGE_SCRIPT_ID}" />`;
76
+ <script src="${PAGE_SCRIPT_ID}" />`;
75
77
  }
76
78
  if (query.astro) {
77
79
  if (query.type === "style") {
78
80
  if (typeof query.index === "undefined") {
79
81
  throw new Error(`Requests for Astro CSS must include an index.`);
80
82
  }
81
- const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts == null ? void 0 : opts.ssr) });
82
- await trackCSSDependencies.call(this, { viteDevServer, id, filename, deps: transformResult.rawCSSDeps });
83
+ const transformResult = await cachedCompilation(config, filename, source, viteTransform, {
84
+ ssr: Boolean(opts == null ? void 0 : opts.ssr)
85
+ });
86
+ await trackCSSDependencies.call(this, {
87
+ viteDevServer,
88
+ id,
89
+ filename,
90
+ deps: transformResult.rawCSSDeps
91
+ });
83
92
  const csses = transformResult.css;
84
93
  const code = csses[query.index];
85
94
  return {
@@ -89,24 +98,39 @@ function astro({ config, logging }) {
89
98
  if (typeof query.index === "undefined") {
90
99
  throw new Error(`Requests for hoisted scripts must include an index`);
91
100
  }
92
- const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts == null ? void 0 : opts.ssr) });
101
+ const transformResult = await cachedCompilation(config, filename, source, viteTransform, {
102
+ ssr: Boolean(opts == null ? void 0 : opts.ssr)
103
+ });
93
104
  const scripts = transformResult.scripts;
94
105
  const hoistedScript = scripts[query.index];
95
106
  if (!hoistedScript) {
96
107
  throw new Error(`No hoisted script at index ${query.index}`);
97
108
  }
109
+ if (hoistedScript.type === "external") {
110
+ const src = hoistedScript.src;
111
+ if (src.startsWith("/") && !isBrowserPath(src)) {
112
+ const publicDir = config.publicDir.pathname.replace(/\/$/, "").split("/").pop() + "/";
113
+ throw new Error(`
114
+
115
+ <script src="${src}"> references an asset in the "${publicDir}" directory. Please add the "is:inline" directive to keep this asset from being bundled.
116
+
117
+ File: ${filename}`);
118
+ }
119
+ }
98
120
  return {
99
121
  code: hoistedScript.type === "inline" ? hoistedScript.code : `import "${hoistedScript.src}";`
100
122
  };
101
123
  }
102
124
  }
103
125
  try {
104
- const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts == null ? void 0 : opts.ssr) });
126
+ const transformResult = await cachedCompilation(config, filename, source, viteTransform, {
127
+ ssr: Boolean(opts == null ? void 0 : opts.ssr)
128
+ });
105
129
  const { code, map } = await esbuild.transform(transformResult.code, {
106
130
  loader: "ts",
107
131
  sourcemap: "external",
108
132
  sourcefile: id,
109
- define: config.vite.define
133
+ define: (_a = config.vite) == null ? void 0 : _a.define
110
134
  });
111
135
  let SUFFIX = "";
112
136
  if (!resolvedConfig.isProduction) {
@@ -125,7 +149,11 @@ import "${PAGE_SSR_SCRIPT_ID}";`;
125
149
  const scannedFrontmatter = FRONTMATTER_PARSE_REGEXP.exec(source);
126
150
  if (scannedFrontmatter) {
127
151
  try {
128
- await esbuild.transform(scannedFrontmatter[1], { loader: "ts", sourcemap: false, sourcefile: id });
152
+ await esbuild.transform(scannedFrontmatter[1], {
153
+ loader: "ts",
154
+ sourcemap: false,
155
+ sourcefile: id
156
+ });
129
157
  } catch (frontmatterErr) {
130
158
  if (frontmatterErr && frontmatterErr.message) {
131
159
  frontmatterErr.message = frontmatterErr.message.replace("end of file", "end of frontmatter");
@@ -141,7 +169,7 @@ import "${PAGE_SSR_SCRIPT_ID}";`;
141
169
 
142
170
  \`@astrojs/compiler\` encountered an unrecoverable error when compiling the following file.
143
171
 
144
- **${id.replace(fileURLToPath(config.projectRoot), "")}**
172
+ **${id.replace(fileURLToPath(config.root), "")}**
145
173
  \`\`\`astro
146
174
  ${source}
147
175
  \`\`\`
@@ -1,4 +1,4 @@
1
- import { STYLE_EXTENSIONS } from "../core/render/dev/css.js";
1
+ import { STYLE_EXTENSIONS } from "../core/render/util.js";
2
2
  function getViteTransform(viteConfig) {
3
3
  const viteCSSPlugin = viteConfig.plugins.find(({ name }) => name === "vite:css");
4
4
  if (!viteCSSPlugin)
@@ -7,7 +7,13 @@ function getViteTransform(viteConfig) {
7
7
  throw new Error(`vite:css has no transform() hook`);
8
8
  return viteCSSPlugin.transform.bind(null);
9
9
  }
10
- async function transformWithVite({ value, lang, transformHook, id, ssr }) {
10
+ async function transformWithVite({
11
+ value,
12
+ lang,
13
+ transformHook,
14
+ id,
15
+ ssr
16
+ }) {
11
17
  if (!STYLE_EXTENSIONS.has(lang)) {
12
18
  return null;
13
19
  }
@@ -1,4 +1,6 @@
1
- import * as babel from "@babel/core";
1
+ import { parse as babelParser } from "@babel/parser";
2
+ import { parse, print, types, visit } from "recast";
3
+ const ASTRO_GLOB_REGEX = /Astro2?\s*\.\s*glob\s*\(/;
2
4
  const validAstroGlobalNames = /* @__PURE__ */ new Set(["Astro", "Astro2"]);
3
5
  function astro({ config }) {
4
6
  return {
@@ -7,43 +9,42 @@ function astro({ config }) {
7
9
  if (!id.endsWith(".astro") && !id.endsWith(".md")) {
8
10
  return null;
9
11
  }
10
- if (!code.includes("fetchContent")) {
12
+ if (!ASTRO_GLOB_REGEX.test(code)) {
11
13
  return null;
12
14
  }
13
- const result = await babel.transformAsync(code, {
14
- sourceType: "module",
15
- sourceMaps: true,
16
- plugins: [
17
- () => {
18
- return {
19
- visitor: {
20
- StringLiteral(path) {
21
- if (path.parent.type !== "CallExpression" || path.parent.callee.type !== "MemberExpression" || !validAstroGlobalNames.has(path.parent.callee.object.name) || path.parent.callee.property.name !== "fetchContent") {
22
- return;
23
- }
24
- const { value } = path.node;
25
- if (/[a-z]\:\/\//.test(value)) {
26
- return;
27
- }
28
- path.replaceWith({
29
- type: "CallExpression",
30
- callee: {
31
- type: "MemberExpression",
32
- object: { type: "MetaProperty", meta: { type: "Identifier", name: "import" }, property: { type: "Identifier", name: "meta" } },
33
- property: { type: "Identifier", name: "globEager" },
34
- computed: false
35
- },
36
- arguments: [path.node]
37
- });
38
- }
39
- }
40
- };
15
+ const ast = parse(code, {
16
+ parser: { parse: babelParser }
17
+ });
18
+ visit(ast, {
19
+ visitCallExpression: function(path) {
20
+ if (!types.namedTypes.MemberExpression.check(path.node.callee) || !types.namedTypes.Identifier.check(path.node.callee.property) || !(path.node.callee.property.name === "glob") || !types.namedTypes.Identifier.check(path.node.callee.object) || !(path.node.callee.object.name === "Astro" || path.node.callee.object.name === "Astro2")) {
21
+ this.traverse(path);
22
+ return;
41
23
  }
42
- ]
24
+ const argsPath = path.get("arguments", 0);
25
+ const args = argsPath.value;
26
+ argsPath.replace({
27
+ type: "CallExpression",
28
+ callee: {
29
+ type: "MemberExpression",
30
+ object: {
31
+ type: "MetaProperty",
32
+ meta: { type: "Identifier", name: "import" },
33
+ property: { type: "Identifier", name: "meta" }
34
+ },
35
+ property: { type: "Identifier", name: "glob" },
36
+ computed: false
37
+ },
38
+ arguments: [args]
39
+ }, {
40
+ type: "ArrowFunctionExpression",
41
+ body: args,
42
+ params: []
43
+ });
44
+ return false;
45
+ }
43
46
  });
44
- if (!result || !result.code) {
45
- return null;
46
- }
47
+ const result = print(ast);
47
48
  return { code: result.code, map: result.map };
48
49
  }
49
50
  };
@@ -1,15 +1,22 @@
1
- import { info, warn, error } from "../core/logger.js";
1
+ import { info, warn, error } from "../core/logger/core.js";
2
2
  import { getParamsAndProps, GetParamsAndPropsError } from "../core/render/core.js";
3
3
  import { createRouteManifest, matchRoute } from "../core/routing/index.js";
4
4
  import stripAnsi from "strip-ansi";
5
- import { createSafeError } from "../core/util.js";
5
+ import { createSafeError, resolvePages, isBuildingToSSR } from "../core/util.js";
6
6
  import { ssr, preload } from "../core/render/dev/index.js";
7
7
  import { call as callEndpoint } from "../core/endpoint/dev/index.js";
8
8
  import * as msg from "../core/messages.js";
9
9
  import notFoundTemplate, { subpathNotUsedTemplate } from "../template/4xx.js";
10
10
  import serverErrorTemplate from "../template/5xx.js";
11
11
  import { RouteCache } from "../core/render/route-cache.js";
12
- const BAD_VITE_MIDDLEWARE = ["viteIndexHtmlMiddleware", "vite404Middleware", "viteSpaFallbackMiddleware"];
12
+ import { fixViteErrorMessage } from "../core/errors.js";
13
+ import { createRequest } from "../core/request.js";
14
+ import { Readable } from "stream";
15
+ const BAD_VITE_MIDDLEWARE = [
16
+ "viteIndexHtmlMiddleware",
17
+ "vite404Middleware",
18
+ "viteSpaFallbackMiddleware"
19
+ ];
13
20
  function removeViteHttpMiddleware(server) {
14
21
  for (let i = server.stack.length - 1; i > 0; i--) {
15
22
  if (BAD_VITE_MIDDLEWARE.includes(server.stack[i].handle.name)) {
@@ -29,13 +36,18 @@ async function writeWebResponse(res, webResponse) {
29
36
  const { status, headers, body } = webResponse;
30
37
  res.writeHead(status, Object.fromEntries(headers.entries()));
31
38
  if (body) {
32
- const reader = body.getReader();
33
- while (true) {
34
- const { done, value } = await reader.read();
35
- if (done)
36
- break;
37
- if (value) {
38
- res.write(value);
39
+ if (body instanceof Readable) {
40
+ body.pipe(res);
41
+ return;
42
+ } else {
43
+ const reader = body.getReader();
44
+ while (true) {
45
+ const { done, value } = await reader.read();
46
+ if (done)
47
+ break;
48
+ if (value) {
49
+ res.write(value);
50
+ }
39
51
  }
40
52
  }
41
53
  }
@@ -51,14 +63,19 @@ async function writeSSRResult(result, res, statusCode) {
51
63
  writeHtmlResponse(res, statusCode, html);
52
64
  }
53
65
  async function handle404Response(origin, config, req, res) {
54
- const site = config.buildOptions.site ? new URL(config.buildOptions.site) : void 0;
66
+ const site = config.site ? new URL(config.base, config.site) : void 0;
55
67
  const devRoot = site ? site.pathname : "/";
56
68
  const pathname = decodeURI(new URL(origin + req.url).pathname);
57
69
  let html = "";
58
70
  if (pathname === "/" && !pathname.startsWith(devRoot)) {
59
71
  html = subpathNotUsedTemplate(devRoot, pathname);
60
72
  } else {
61
- html = notFoundTemplate({ statusCode: 404, title: "Not found", tabTitle: "404: Not Found", pathname });
73
+ html = notFoundTemplate({
74
+ statusCode: 404,
75
+ title: "Not found",
76
+ tabTitle: "404: Not Found",
77
+ pathname
78
+ });
62
79
  }
63
80
  writeHtmlResponse(res, 404, html);
64
81
  }
@@ -76,7 +93,7 @@ async function handle500Response(viteServer, origin, req, res, err) {
76
93
  writeHtmlResponse(res, 500, transformedHtml);
77
94
  }
78
95
  function getCustom404Route(config, manifest) {
79
- const relPages = config.pages.href.replace(config.projectRoot.href, "");
96
+ const relPages = resolvePages(config).href.replace(config.root.href, "");
80
97
  return manifest.routes.find((r) => r.component === relPages + "404.astro");
81
98
  }
82
99
  function log404(logging, pathname) {
@@ -84,12 +101,35 @@ function log404(logging, pathname) {
84
101
  }
85
102
  async function handleRequest(routeCache, viteServer, logging, manifest, config, req, res) {
86
103
  const reqStart = performance.now();
87
- const site = config.buildOptions.site ? new URL(config.buildOptions.site) : void 0;
104
+ const site = config.site ? new URL(config.base, config.site) : void 0;
88
105
  const devRoot = site ? site.pathname : "/";
89
106
  const origin = `${viteServer.config.server.https ? "https" : "http"}://${req.headers.host}`;
107
+ const buildingToSSR = isBuildingToSSR(config);
90
108
  const url = new URL(origin + req.url);
91
109
  const pathname = decodeURI(url.pathname);
92
110
  const rootRelativeUrl = pathname.substring(devRoot.length - 1);
111
+ if (!buildingToSSR) {
112
+ for (const [key] of url.searchParams) {
113
+ url.searchParams.delete(key);
114
+ }
115
+ }
116
+ let body = void 0;
117
+ if (!(req.method === "GET" || req.method === "HEAD")) {
118
+ let bytes = [];
119
+ await new Promise((resolve) => {
120
+ req.setEncoding("utf-8");
121
+ req.on("data", (bts) => bytes.push(bts));
122
+ req.on("end", resolve);
123
+ });
124
+ body = new TextEncoder().encode(bytes.join("")).buffer;
125
+ }
126
+ const request = createRequest({
127
+ url,
128
+ headers: buildingToSSR ? req.headers : new Headers(),
129
+ method: req.method,
130
+ body,
131
+ logging
132
+ });
93
133
  try {
94
134
  if (!pathname.startsWith(devRoot)) {
95
135
  log404(logging, pathname);
@@ -106,7 +146,7 @@ async function handleRequest(routeCache, viteServer, logging, manifest, config,
106
146
  return handle404Response(origin, config, req, res);
107
147
  }
108
148
  }
109
- const filePath = new URL(`./${route.component}`, config.projectRoot);
149
+ const filePath = new URL(`./${route.component}`, config.root);
110
150
  const preloadedComponent = await preload({ astroConfig: config, filePath, viteServer });
111
151
  const [, mod] = preloadedComponent;
112
152
  const paramsAndPropsRes = await getParamsAndProps({
@@ -115,24 +155,27 @@ async function handleRequest(routeCache, viteServer, logging, manifest, config,
115
155
  routeCache,
116
156
  pathname: rootRelativeUrl,
117
157
  logging,
118
- ssr: config.buildOptions.experimentalSsr
158
+ ssr: isBuildingToSSR(config)
119
159
  });
120
160
  if (paramsAndPropsRes === GetParamsAndPropsError.NoMatchingStaticPath) {
121
161
  warn(logging, "getStaticPaths", `Route pattern matched, but no matching static path found. (${pathname})`);
122
162
  log404(logging, pathname);
123
163
  const routeCustom404 = getCustom404Route(config, manifest);
124
164
  if (routeCustom404) {
125
- const filePathCustom404 = new URL(`./${routeCustom404.component}`, config.projectRoot);
126
- const preloadedCompCustom404 = await preload({ astroConfig: config, filePath: filePathCustom404, viteServer });
165
+ const filePathCustom404 = new URL(`./${routeCustom404.component}`, config.root);
166
+ const preloadedCompCustom404 = await preload({
167
+ astroConfig: config,
168
+ filePath: filePathCustom404,
169
+ viteServer
170
+ });
127
171
  const result = await ssr(preloadedCompCustom404, {
128
172
  astroConfig: config,
129
173
  filePath: filePathCustom404,
130
174
  logging,
131
175
  mode: "development",
132
- method: "GET",
133
- headers: new Headers(Object.entries(req.headers)),
134
176
  origin,
135
177
  pathname: rootRelativeUrl,
178
+ request,
136
179
  route: routeCustom404,
137
180
  routeCache,
138
181
  viteServer
@@ -152,8 +195,7 @@ async function handleRequest(routeCache, viteServer, logging, manifest, config,
152
195
  route,
153
196
  routeCache,
154
197
  viteServer,
155
- method: req.method || "GET",
156
- headers: new Headers(Object.entries(req.headers))
198
+ request
157
199
  };
158
200
  if (route.type === "endpoint") {
159
201
  const result = await callEndpoint(options);
@@ -169,9 +211,8 @@ async function handleRequest(routeCache, viteServer, logging, manifest, config,
169
211
  }
170
212
  } catch (_err) {
171
213
  debugger;
172
- info(logging, "serve", msg.req({ url: pathname, statusCode: 500 }));
173
- const err = createSafeError(_err);
174
- error(logging, "error", msg.err(err));
214
+ const err = fixViteErrorMessage(createSafeError(_err), viteServer);
215
+ error(logging, null, msg.formatErrorMessage(err));
175
216
  handle500Response(viteServer, origin, req, res, err);
176
217
  }
177
218
  }
@@ -1,7 +1,11 @@
1
1
  import * as path from "path";
2
2
  import esbuild from "esbuild";
3
- import { isCSSRequest } from "../core/render/dev/css.js";
4
- import { getPageDatasByChunk, getPageDataByViteID, hasPageDataByViteID } from "../core/build/internal.js";
3
+ import { isCSSRequest } from "../core/render/util.js";
4
+ import {
5
+ getPageDatasByChunk,
6
+ getPageDataByViteID,
7
+ hasPageDataByViteID
8
+ } from "../core/build/internal.js";
5
9
  const PLUGIN_NAME = "@astrojs/rollup-plugin-build-css";
6
10
  const ASTRO_STYLE_PREFIX = "@astro-inline-style";
7
11
  const ASTRO_PAGE_STYLE_PREFIX = "@astro-page-all-styles";