astro 3.6.2 → 4.0.0-beta.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 (135) hide show
  1. package/client.d.ts +19 -20
  2. package/components/Code.astro +0 -20
  3. package/components/ViewTransitions.astro +2 -2
  4. package/dist/@types/astro.d.ts +19 -81
  5. package/dist/assets/build/generate.js +2 -2
  6. package/dist/assets/internal.js +1 -1
  7. package/dist/assets/services/vendor/squoosh/avif/avif_node_dec.js +3 -3
  8. package/dist/assets/services/vendor/squoosh/avif/avif_node_enc.js +3 -3
  9. package/dist/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.js +3 -3
  10. package/dist/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.js +3 -3
  11. package/dist/assets/services/vendor/squoosh/webp/webp_node_dec.js +3 -3
  12. package/dist/assets/services/vendor/squoosh/webp/webp_node_enc.js +3 -3
  13. package/dist/cli/add/babel.d.ts +1 -1
  14. package/dist/cli/build/index.js +0 -1
  15. package/dist/cli/flags.js +0 -3
  16. package/dist/cli/info/index.d.ts +5 -0
  17. package/dist/cli/info/index.js +16 -7
  18. package/dist/cli/install-package.js +1 -1
  19. package/dist/cli/telemetry/index.js +6 -6
  20. package/dist/content/server-listeners.js +7 -7
  21. package/dist/content/types-generator.d.ts +1 -4
  22. package/dist/content/types-generator.js +31 -51
  23. package/dist/core/app/index.js +2 -4
  24. package/dist/core/build/buildPipeline.js +3 -3
  25. package/dist/core/build/generate.js +18 -39
  26. package/dist/core/build/index.js +10 -32
  27. package/dist/core/build/internal.js +3 -3
  28. package/dist/core/build/plugin.d.ts +2 -2
  29. package/dist/core/build/plugins/plugin-manifest.js +1 -4
  30. package/dist/core/build/plugins/plugin-pages.js +0 -3
  31. package/dist/core/build/plugins/plugin-renderers.d.ts +1 -1
  32. package/dist/core/build/plugins/plugin-ssr.js +5 -6
  33. package/dist/core/build/static-build.js +4 -7
  34. package/dist/core/build/types.d.ts +1 -1
  35. package/dist/core/build/util.js +1 -1
  36. package/dist/core/config/config.js +1 -2
  37. package/dist/core/config/schema.d.ts +209 -277
  38. package/dist/core/config/schema.js +5 -38
  39. package/dist/core/constants.js +1 -1
  40. package/dist/core/create-vite.d.ts +2 -2
  41. package/dist/core/create-vite.js +12 -1
  42. package/dist/core/dev/dev.js +6 -4
  43. package/dist/core/dev/restart.js +7 -7
  44. package/dist/core/endpoint/index.d.ts +2 -7
  45. package/dist/core/endpoint/index.js +3 -87
  46. package/dist/core/errors/dev/vite.js +0 -1
  47. package/dist/core/logger/console.d.ts +2 -4
  48. package/dist/core/logger/console.js +4 -28
  49. package/dist/core/logger/core.d.ts +17 -5
  50. package/dist/core/logger/core.js +27 -2
  51. package/dist/core/logger/node.d.ts +2 -32
  52. package/dist/core/logger/node.js +8 -69
  53. package/dist/core/messages.d.ts +4 -11
  54. package/dist/core/messages.js +43 -59
  55. package/dist/core/middleware/callMiddleware.d.ts +1 -2
  56. package/dist/core/middleware/callMiddleware.js +1 -12
  57. package/dist/core/middleware/index.d.ts +2 -2
  58. package/dist/core/middleware/sequence.d.ts +2 -2
  59. package/dist/core/pipeline.d.ts +2 -2
  60. package/dist/core/pipeline.js +8 -13
  61. package/dist/core/preview/static-preview-server.js +2 -4
  62. package/dist/core/preview/vite-plugin-astro-preview.js +31 -21
  63. package/dist/core/render/core.js +0 -6
  64. package/dist/core/render/index.d.ts +1 -1
  65. package/dist/core/render/result.js +1 -1
  66. package/dist/core/render/route-cache.js +2 -5
  67. package/dist/core/request.js +3 -3
  68. package/dist/core/routing/manifest/create.js +14 -12
  69. package/dist/core/routing/validation.js +4 -4
  70. package/dist/core/sync/index.js +2 -2
  71. package/dist/i18n/middleware.d.ts +2 -2
  72. package/dist/i18n/vite-plugin-i18n.js +1 -1
  73. package/dist/integrations/astroFeaturesValidation.d.ts +1 -1
  74. package/dist/integrations/astroFeaturesValidation.js +12 -18
  75. package/dist/integrations/index.js +28 -6
  76. package/dist/prefetch/vite-plugin-prefetch.js +3 -3
  77. package/dist/runtime/client/dev-overlay/entrypoint.js +14 -10
  78. package/dist/runtime/client/dev-overlay/overlay.js +1 -1
  79. package/dist/runtime/client/dev-overlay/plugins/astro.d.ts +14 -1
  80. package/dist/runtime/client/dev-overlay/plugins/astro.js +326 -15
  81. package/dist/runtime/client/dev-overlay/plugins/settings.js +26 -2
  82. package/dist/runtime/client/dev-overlay/plugins/utils/icons.d.ts +3 -0
  83. package/dist/runtime/client/dev-overlay/plugins/utils/icons.js +37 -0
  84. package/dist/runtime/client/dev-overlay/plugins/utils/window.d.ts +1 -2
  85. package/dist/runtime/client/dev-overlay/plugins/utils/window.js +25 -29
  86. package/dist/runtime/client/dev-overlay/ui-library/badge.d.ts +9 -0
  87. package/dist/runtime/client/dev-overlay/ui-library/badge.js +67 -0
  88. package/dist/runtime/client/dev-overlay/ui-library/button.d.ts +9 -0
  89. package/dist/runtime/client/dev-overlay/ui-library/button.js +83 -0
  90. package/dist/runtime/client/dev-overlay/ui-library/card.d.ts +1 -3
  91. package/dist/runtime/client/dev-overlay/ui-library/card.js +17 -25
  92. package/dist/runtime/client/dev-overlay/ui-library/highlight.js +1 -0
  93. package/dist/runtime/client/dev-overlay/ui-library/icon.d.ts +10 -0
  94. package/dist/runtime/client/dev-overlay/ui-library/icon.js +36 -0
  95. package/dist/runtime/client/dev-overlay/ui-library/icons.d.ts +21 -6
  96. package/dist/runtime/client/dev-overlay/ui-library/icons.js +22 -7
  97. package/dist/runtime/client/dev-overlay/ui-library/index.d.ts +8 -0
  98. package/dist/runtime/client/dev-overlay/ui-library/index.js +18 -0
  99. package/dist/runtime/client/dev-overlay/ui-library/window.d.ts +0 -4
  100. package/dist/runtime/client/dev-overlay/ui-library/window.js +0 -33
  101. package/dist/runtime/server/endpoint.d.ts +1 -1
  102. package/dist/runtime/server/endpoint.js +11 -22
  103. package/dist/transitions/vite-plugin-transitions.js +4 -4
  104. package/dist/virtual-modules/i18n.d.ts +1 -0
  105. package/dist/virtual-modules/i18n.js +1 -0
  106. package/dist/virtual-modules/middleware.d.ts +1 -0
  107. package/dist/virtual-modules/middleware.js +5 -0
  108. package/dist/virtual-modules/prefetch.d.ts +1 -0
  109. package/dist/virtual-modules/prefetch.js +1 -0
  110. package/dist/virtual-modules/transitions-events.d.ts +1 -0
  111. package/dist/virtual-modules/transitions-events.js +1 -0
  112. package/dist/virtual-modules/transitions-router.d.ts +1 -0
  113. package/dist/virtual-modules/transitions-router.js +1 -0
  114. package/dist/virtual-modules/transitions-types.d.ts +1 -0
  115. package/dist/virtual-modules/transitions-types.js +1 -0
  116. package/dist/virtual-modules/transitions.d.ts +1 -0
  117. package/dist/virtual-modules/transitions.js +1 -0
  118. package/dist/vite-plugin-astro/hmr.js +8 -14
  119. package/dist/vite-plugin-astro/index.js +28 -6
  120. package/dist/vite-plugin-astro-server/base.js +5 -5
  121. package/dist/vite-plugin-astro-server/response.js +1 -1
  122. package/dist/vite-plugin-astro-server/route.js +30 -6
  123. package/dist/vite-plugin-inject-env-ts/index.js +3 -3
  124. package/dist/vite-plugin-integrations-container/index.js +1 -1
  125. package/dist/vite-plugin-load-fallback/index.js +1 -3
  126. package/dist/vite-plugin-scanner/index.js +3 -6
  127. package/dist/vite-plugin-scripts/index.js +1 -1
  128. package/dist/vite-plugin-utils/index.d.ts +1 -0
  129. package/dist/vite-plugin-utils/index.js +5 -0
  130. package/package.json +56 -68
  131. package/dist/core/middleware/namespace.d.ts +0 -1
  132. package/dist/core/middleware/namespace.js +0 -5
  133. package/dist/vite-plugin-astro-server/common.d.ts +0 -2
  134. package/dist/vite-plugin-astro-server/common.js +0 -7
  135. package/import-meta.d.ts +0 -30
@@ -1,8 +1,7 @@
1
1
  import { markdownConfigDefaults } from "@astrojs/markdown-remark";
2
2
  import { bundledThemes } from "shikiji";
3
- import fs from "node:fs";
4
3
  import path from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { pathToFileURL } from "node:url";
6
5
  import { z } from "zod";
7
6
  import { appendForwardSlash, prependForwardSlash, removeTrailingForwardSlash } from "../path.js";
8
7
  import "mdast-util-to-hast";
@@ -21,9 +20,7 @@ const ASTRO_CONFIG_DEFAULTS = {
21
20
  assets: "_astro",
22
21
  serverEntry: "entry.mjs",
23
22
  redirects: true,
24
- inlineStylesheets: "auto",
25
- split: false,
26
- excludeMiddleware: false
23
+ inlineStylesheets: "auto"
27
24
  },
28
25
  image: {
29
26
  service: { entrypoint: "astro/assets/services/sharp", config: {} }
@@ -35,10 +32,7 @@ const ASTRO_CONFIG_DEFAULTS = {
35
32
  open: false
36
33
  },
37
34
  integrations: [],
38
- markdown: {
39
- drafts: false,
40
- ...markdownConfigDefaults
41
- },
35
+ markdown: markdownConfigDefaults,
42
36
  vite: {},
43
37
  legacy: {},
44
38
  redirects: {},
@@ -75,17 +69,7 @@ const AstroConfigSchema = z.object({
75
69
  assetsPrefix: z.string().optional(),
76
70
  serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
77
71
  redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
78
- inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets),
79
- /**
80
- * @deprecated
81
- * Use the adapter feature instead
82
- */
83
- split: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.split),
84
- /**
85
- * @deprecated
86
- * Use the adapter feature instead
87
- */
88
- excludeMiddleware: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.excludeMiddleware)
72
+ inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets)
89
73
  }).default({}),
90
74
  server: z.preprocess(
91
75
  // preprocess
@@ -153,26 +137,11 @@ const AstroConfigSchema = z.object({
153
137
  ).default([])
154
138
  }).default(ASTRO_CONFIG_DEFAULTS.image),
155
139
  markdown: z.object({
156
- drafts: z.boolean().default(false),
157
140
  syntaxHighlight: z.union([z.literal("shiki"), z.literal("prism"), z.literal(false)]).default(ASTRO_CONFIG_DEFAULTS.markdown.syntaxHighlight),
158
141
  shikiConfig: z.object({
159
142
  langs: z.custom().array().transform((langs) => {
160
143
  for (const lang of langs) {
161
144
  if (typeof lang === "object") {
162
- const langPath = lang.path;
163
- if (langPath) {
164
- const astroRoot = fileURLToPath(new URL("../../../", import.meta.url));
165
- const normalizedPath = path.isAbsolute(langPath) ? langPath : path.resolve(astroRoot, langPath);
166
- try {
167
- const content = fs.readFileSync(normalizedPath, "utf-8");
168
- const parsed = JSON.parse(content);
169
- Object.assign(lang, parsed);
170
- } catch (e) {
171
- throw new Error(`Unable to find language file at ${normalizedPath}`, {
172
- cause: e
173
- });
174
- }
175
- }
176
145
  if (lang.id) {
177
146
  lang.name = lang.id;
178
147
  }
@@ -274,9 +243,7 @@ function createRelativeSchema(cmd, fileProtocolRoot) {
274
243
  assetsPrefix: z.string().optional(),
275
244
  serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry),
276
245
  redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects),
277
- inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets),
278
- split: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.split),
279
- excludeMiddleware: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.excludeMiddleware)
246
+ inlineStylesheets: z.enum(["always", "auto", "never"]).optional().default(ASTRO_CONFIG_DEFAULTS.build.inlineStylesheets)
280
247
  }).optional().default({}),
281
248
  server: z.preprocess(
282
249
  // preprocess
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "3.6.2";
1
+ const ASTRO_VERSION = "4.0.0-beta.1";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
- import type { AstroSettings } from '../@types/astro.js';
3
- import type { Logger } from './logger/core.js';
4
2
  import nodeFs from 'node:fs';
5
3
  import * as vite from 'vite';
4
+ import type { AstroSettings } from '../@types/astro.js';
5
+ import type { Logger } from './logger/core.js';
6
6
  interface CreateViteOptions {
7
7
  settings: AstroSettings;
8
8
  logger: Logger;
@@ -72,6 +72,16 @@ async function createVite(commandConfig, { settings, logger, mode, command, fs =
72
72
  }
73
73
  }
74
74
  });
75
+ const viteCustomLogger = {
76
+ ...vite.createLogger("warn"),
77
+ // All error log messages are also thrown as real errors,
78
+ // so we can safely ignore them here and let the error handler
79
+ // log them for the user instead.
80
+ error: (msg) => logger.debug("vite", "ERROR " + msg),
81
+ // Warnings are usually otherwise ignored by Vite, so it's
82
+ // important that we catch and log them here.
83
+ warn: (msg) => logger.warn("vite", msg)
84
+ };
75
85
  const commonConfig = {
76
86
  // Tell Vite not to combine config from vite.config.js with our provided inline config
77
87
  configFile: false,
@@ -81,6 +91,7 @@ async function createVite(commandConfig, { settings, logger, mode, command, fs =
81
91
  // we want to control the output, not Vite
82
92
  logLevel: "warn",
83
93
  // log warnings and errors only
94
+ customLogger: viteCustomLogger,
84
95
  appType: "custom",
85
96
  optimizeDeps: {
86
97
  entries: ["src/**/*"],
@@ -148,7 +159,7 @@ async function createVite(commandConfig, { settings, logger, mode, command, fs =
148
159
  },
149
160
  {
150
161
  find: "astro:middleware",
151
- replacement: "astro/middleware/namespace"
162
+ replacement: "astro/virtual-modules/middleware.js"
152
163
  },
153
164
  {
154
165
  find: "astro:components",
@@ -5,6 +5,7 @@ import { telemetry } from "../../events/index.js";
5
5
  import * as msg from "../messages.js";
6
6
  import { startContainer } from "./container.js";
7
7
  import { createContainerWithAutomaticRestart } from "./restart.js";
8
+ import { green } from "kleur/colors";
8
9
  async function dev(inlineConfig) {
9
10
  const devStart = performance.now();
10
11
  await telemetry.record([]);
@@ -12,7 +13,7 @@ async function dev(inlineConfig) {
12
13
  const logger = restart.container.logger;
13
14
  const devServerAddressInfo = await startContainer(restart.container);
14
15
  logger.info(
15
- null,
16
+ "SKIP_FORMAT",
16
17
  msg.serverStart({
17
18
  startupTime: performance.now() - devStart,
18
19
  resolvedUrls: restart.container.viteServer.resolvedUrls || { local: [], network: [] },
@@ -20,14 +21,15 @@ async function dev(inlineConfig) {
20
21
  base: restart.container.settings.config.base
21
22
  })
22
23
  );
23
- const currentVersion = "3.6.2";
24
+ const currentVersion = "4.0.0-beta.1";
24
25
  if (currentVersion.includes("-")) {
25
- logger.warn(null, msg.prerelease({ currentVersion }));
26
+ logger.warn("SKIP_FORMAT", msg.prerelease({ currentVersion }));
26
27
  }
27
28
  if (restart.container.viteServer.config.server?.fs?.strict === false) {
28
- logger.warn(null, msg.fsStrictWarning());
29
+ logger.warn("SKIP_FORMAT", msg.fsStrictWarning());
29
30
  }
30
31
  await attachContentServerListeners(restart.container);
32
+ logger.info(null, green("watching for file changes..."));
31
33
  return {
32
34
  address: devServerAddressInfo,
33
35
  get watcher() {
@@ -59,7 +59,7 @@ async function restartContainer(container) {
59
59
  }
60
60
  });
61
61
  container.restartInFlight = false;
62
- logger.error("astro", "Continuing with previous valid configuration\n");
62
+ logger.error(null, "Continuing with previous valid configuration\n");
63
63
  return error;
64
64
  }
65
65
  }
@@ -82,8 +82,8 @@ async function createContainerWithAutomaticRestart({
82
82
  return restartComplete;
83
83
  }
84
84
  };
85
- async function handleServerRestart(logMsg) {
86
- logger.info("astro", logMsg + "\n");
85
+ async function handleServerRestart(logMsg = "") {
86
+ logger.info(null, (logMsg + " Restarting...").trim());
87
87
  const container = restart.container;
88
88
  const result = await restartContainer(container);
89
89
  if (result instanceof Error) {
@@ -106,10 +106,10 @@ async function createContainerWithAutomaticRestart({
106
106
  }
107
107
  function addWatches() {
108
108
  const watcher = restart.container.viteServer.watcher;
109
- watcher.on("change", handleChangeRestart("Configuration updated. Restarting..."));
110
- watcher.on("unlink", handleChangeRestart("Configuration removed. Restarting..."));
111
- watcher.on("add", handleChangeRestart("Configuration added. Restarting..."));
112
- restart.container.viteServer.restart = () => handleServerRestart("Restarting...");
109
+ watcher.on("change", handleChangeRestart("Configuration file updated."));
110
+ watcher.on("unlink", handleChangeRestart("Configuration file removed."));
111
+ watcher.on("add", handleChangeRestart("Configuration file added."));
112
+ restart.container.viteServer.restart = () => handleServerRestart();
113
113
  }
114
114
  addWatches();
115
115
  return restart;
@@ -1,5 +1,4 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type { APIContext, EndpointHandler, EndpointOutput, MiddlewareHandler, Params } from '../../@types/astro.js';
1
+ import type { APIContext, EndpointHandler, MiddlewareHandler, Params } from '../../@types/astro.js';
3
2
  import { type Environment, type RenderContext } from '../render/index.js';
4
3
  type CreateAPIContext = {
5
4
  request: Request;
@@ -17,9 +16,5 @@ type CreateAPIContext = {
17
16
  * @param {CreateAPIContext} payload
18
17
  */
19
18
  export declare function createAPIContext({ request, params, site, props, adapterName, locales, routingStrategy, defaultLocale, }: CreateAPIContext): APIContext;
20
- type ResponseParameters = ConstructorParameters<typeof Response>;
21
- export declare class ResponseWithEncoding extends Response {
22
- constructor(body: ResponseParameters[0], init: ResponseParameters[1], encoding?: BufferEncoding);
23
- }
24
- export declare function callEndpoint<MiddlewareResult = Response | EndpointOutput>(mod: EndpointHandler, env: Environment, ctx: RenderContext, onRequest: MiddlewareHandler<MiddlewareResult> | undefined): Promise<Response>;
19
+ export declare function callEndpoint(mod: EndpointHandler, env: Environment, ctx: RenderContext, onRequest: MiddlewareHandler | undefined): Promise<Response>;
25
20
  export {};
@@ -1,4 +1,3 @@
1
- import mime from "mime";
2
1
  import { renderEndpoint } from "../../runtime/server/index.js";
3
2
  import { ASTRO_VERSION } from "../constants.js";
4
3
  import { AstroCookies, attachCookiesToResponse } from "../cookies/index.js";
@@ -10,7 +9,6 @@ import {
10
9
  computePreferredLocaleList
11
10
  } from "../render/context.js";
12
11
  import {} from "../render/index.js";
13
- const encoder = new TextEncoder();
14
12
  const clientAddressSymbol = Symbol.for("astro.clientAddress");
15
13
  const clientLocalsSymbol = Symbol.for("astro.locals");
16
14
  function createAPIContext({
@@ -41,7 +39,6 @@ function createAPIContext({
41
39
  }
42
40
  });
43
41
  },
44
- ResponseWithEncoding,
45
42
  get preferredLocale() {
46
43
  if (preferredLocale) {
47
44
  return preferredLocale;
@@ -107,21 +104,6 @@ function createAPIContext({
107
104
  };
108
105
  return context;
109
106
  }
110
- class ResponseWithEncoding extends Response {
111
- constructor(body, init, encoding) {
112
- if (typeof body === "string") {
113
- if (typeof Buffer !== "undefined" && Buffer.from) {
114
- body = Buffer.from(body, encoding);
115
- } else if (encoding == null || encoding === "utf8" || encoding === "utf-8") {
116
- body = encoder.encode(body);
117
- }
118
- }
119
- super(body, init);
120
- if (encoding) {
121
- this.headers.set("X-Astro-Encoding", encoding);
122
- }
123
- }
124
- }
125
107
  async function callEndpoint(mod, env, ctx, onRequest) {
126
108
  const context = createAPIContext({
127
109
  request: ctx.request,
@@ -135,82 +117,16 @@ async function callEndpoint(mod, env, ctx, onRequest) {
135
117
  });
136
118
  let response;
137
119
  if (onRequest) {
138
- response = await callMiddleware(
139
- env.logger,
140
- onRequest,
141
- context,
142
- async () => {
143
- return await renderEndpoint(mod, context, env.ssr, env.logger);
144
- }
145
- );
120
+ response = await callMiddleware(onRequest, context, async () => {
121
+ return await renderEndpoint(mod, context, env.ssr, env.logger);
122
+ });
146
123
  } else {
147
124
  response = await renderEndpoint(mod, context, env.ssr, env.logger);
148
125
  }
149
- const isEndpointSSR = env.ssr && !ctx.route?.prerender;
150
- if (response instanceof Response) {
151
- if (isEndpointSSR && response.headers.get("X-Astro-Encoding")) {
152
- env.logger.warn(
153
- "ssr",
154
- "`ResponseWithEncoding` is ignored in SSR. Please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information."
155
- );
156
- }
157
- attachCookiesToResponse(response, context.cookies);
158
- return response;
159
- }
160
- env.logger.warn(
161
- "astro",
162
- `${ctx.route.component} returns a simple object which is deprecated. Please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information.`
163
- );
164
- if (isEndpointSSR) {
165
- if (response.hasOwnProperty("headers")) {
166
- env.logger.warn(
167
- "ssr",
168
- "Setting headers is not supported when returning an object. Please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information."
169
- );
170
- }
171
- if (response.encoding) {
172
- env.logger.warn(
173
- "ssr",
174
- "`encoding` is ignored in SSR. To return a charset other than UTF-8, please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information."
175
- );
176
- }
177
- }
178
- let body;
179
- const headers = new Headers();
180
- const pathname = ctx.route ? (
181
- // Try the static route `pathname`
182
- ctx.route.pathname ?? // Dynamic routes don't include `pathname`, so synthesize a path for these (e.g. 'src/pages/[slug].svg')
183
- ctx.route.segments.map((s) => s.map((p) => p.content).join("")).join("/")
184
- ) : (
185
- // Fallback to pathname of the request
186
- ctx.pathname
187
- );
188
- const mimeType = mime.getType(pathname) || "text/plain";
189
- headers.set("Content-Type", `${mimeType};charset=utf-8`);
190
- if (response.encoding) {
191
- headers.set("X-Astro-Encoding", response.encoding);
192
- }
193
- if (response.body instanceof Uint8Array) {
194
- body = response.body;
195
- headers.set("Content-Length", body.byteLength.toString());
196
- } else if (typeof Buffer !== "undefined" && Buffer.from) {
197
- body = Buffer.from(response.body, response.encoding);
198
- headers.set("Content-Length", body.byteLength.toString());
199
- } else if (response.encoding == null || response.encoding === "utf8" || response.encoding === "utf-8") {
200
- body = encoder.encode(response.body);
201
- headers.set("Content-Length", body.byteLength.toString());
202
- } else {
203
- body = response.body;
204
- }
205
- response = new Response(body, {
206
- status: 200,
207
- headers
208
- });
209
126
  attachCookiesToResponse(response, context.cookies);
210
127
  return response;
211
128
  }
212
129
  export {
213
- ResponseWithEncoding,
214
130
  callEndpoint,
215
131
  createAPIContext
216
132
  };
@@ -53,7 +53,6 @@ function enhanceViteSSRError({
53
53
  if (globPattern) {
54
54
  safeError.message = InvalidGlob.message(globPattern);
55
55
  safeError.name = "InvalidGlob";
56
- safeError.hint = InvalidGlob.hint;
57
56
  safeError.title = InvalidGlob.title;
58
57
  const line = lns.findIndex((ln) => ln.includes(globPattern));
59
58
  if (line !== -1) {
@@ -1,4 +1,2 @@
1
- import type { LogMessage } from './core.js';
2
- export declare const consoleLogDestination: {
3
- write(event: LogMessage): boolean;
4
- };
1
+ import { type LogMessage, type LogWritable } from './core.js';
2
+ export declare const consoleLogDestination: LogWritable<LogMessage>;
@@ -1,39 +1,15 @@
1
- import { bold, cyan, dim, red, reset, yellow } from "kleur/colors";
2
- import { dateTimeFormat, levels } from "./core.js";
3
- let lastMessage;
4
- let lastMessageCount = 1;
1
+ import { getEventPrefix, levels } from "./core.js";
5
2
  const consoleLogDestination = {
6
3
  write(event) {
7
4
  let dest = console.error;
8
5
  if (levels[event.level] < levels["error"]) {
9
6
  dest = console.log;
10
7
  }
11
- function getPrefix() {
12
- let prefix = "";
13
- let type = event.label;
14
- if (type) {
15
- prefix += dim(dateTimeFormat.format(/* @__PURE__ */ new Date()) + " ");
16
- if (event.level === "info") {
17
- type = bold(cyan(`[${type}]`));
18
- } else if (event.level === "warn") {
19
- type = bold(yellow(`[${type}]`));
20
- } else if (event.level === "error") {
21
- type = bold(red(`[${type}]`));
22
- }
23
- prefix += `${type} `;
24
- }
25
- return reset(prefix);
26
- }
27
- let message = event.message;
28
- if (message === lastMessage) {
29
- lastMessageCount++;
30
- message = `${message} ${yellow(`(x${lastMessageCount})`)}`;
8
+ if (event.label === "SKIP_FORMAT") {
9
+ dest(event.message);
31
10
  } else {
32
- lastMessage = message;
33
- lastMessageCount = 1;
11
+ dest(getEventPrefix(event) + " " + event.message);
34
12
  }
35
- const outMessage = getPrefix() + message;
36
- dest(outMessage);
37
13
  return true;
38
14
  }
39
15
  };
@@ -1,7 +1,13 @@
1
- interface LogWritable<T> {
1
+ export interface LogWritable<T> {
2
2
  write: (chunk: T) => boolean;
3
3
  }
4
4
  export type LoggerLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
5
+ /**
6
+ * Defined logger labels. Add more as needed, but keep them high-level & reusable,
7
+ * rather than specific to a single command, function, use, etc. The label will be
8
+ * shown in the log message to the user, so it should be relevant.
9
+ */
10
+ export type LoggerLabel = 'add' | 'build' | 'check' | 'config' | 'content' | 'deprecated' | 'markdown' | 'router' | 'types' | 'vite' | 'watch' | 'middleware' | 'SKIP_FORMAT';
5
11
  export interface LogOptions {
6
12
  dest: LogWritable<LogMessage>;
7
13
  level: LoggerLevel;
@@ -24,16 +30,22 @@ export declare function error(opts: LogOptions, label: string | null, message: s
24
30
  type LogFn = typeof info | typeof warn | typeof error;
25
31
  export declare function table(opts: LogOptions, columns: number[]): (logFn: LogFn, ...input: Array<any>) => void;
26
32
  export declare function debug(...args: any[]): void;
33
+ /**
34
+ * Get the prefix for a log message.
35
+ * This includes the timestamp, log level, and label all properly formatted
36
+ * with colors. This is shared across different loggers, so it's defined here.
37
+ */
38
+ export declare function getEventPrefix({ level, label }: LogMessage): string;
27
39
  export declare let defaultLogLevel: LoggerLevel;
28
40
  /** Print out a timer message for debug() */
29
41
  export declare function timerMessage(message: string, startTime?: number): string;
30
42
  export declare class Logger {
31
43
  options: LogOptions;
32
44
  constructor(options: LogOptions);
33
- info(label: string | null, message: string): void;
34
- warn(label: string | null, message: string): void;
35
- error(label: string | null, message: string): void;
36
- debug(label: string | null, ...messages: any[]): void;
45
+ info(label: LoggerLabel | null, message: string): void;
46
+ warn(label: LoggerLabel | null, message: string): void;
47
+ error(label: LoggerLabel | null, message: string): void;
48
+ debug(label: LoggerLabel, ...messages: any[]): void;
37
49
  level(): LoggerLevel;
38
50
  forkIntegrationLogger(label: string): AstroIntegrationLogger;
39
51
  }
@@ -1,9 +1,10 @@
1
- import { dim } from "kleur/colors";
1
+ import { blue, bold, dim, red, yellow } from "kleur/colors";
2
2
  import stringWidth from "string-width";
3
3
  const dateTimeFormat = new Intl.DateTimeFormat([], {
4
4
  hour: "2-digit",
5
5
  minute: "2-digit",
6
- second: "2-digit"
6
+ second: "2-digit",
7
+ hour12: false
7
8
  });
8
9
  const levels = {
9
10
  debug: 20,
@@ -53,6 +54,29 @@ function padStr(str, len) {
53
54
  const spaces = Array.from({ length: len - strLen }, () => " ").join("");
54
55
  return str + spaces;
55
56
  }
57
+ function getEventPrefix({ level, label }) {
58
+ const timestamp = `${dateTimeFormat.format(/* @__PURE__ */ new Date())}`;
59
+ const prefix = [];
60
+ if (level === "error" || level === "warn") {
61
+ prefix.push(bold(timestamp));
62
+ prefix.push(`[${level.toUpperCase()}]`);
63
+ } else {
64
+ prefix.push(timestamp);
65
+ }
66
+ if (label) {
67
+ prefix.push(`[${label}]`);
68
+ }
69
+ if (level === "error") {
70
+ return red(prefix.join(" "));
71
+ }
72
+ if (level === "warn") {
73
+ return yellow(prefix.join(" "));
74
+ }
75
+ if (prefix.length === 1) {
76
+ return dim(prefix[0]);
77
+ }
78
+ return dim(prefix[0]) + " " + blue(prefix.splice(1).join(" "));
79
+ }
56
80
  let defaultLogLevel;
57
81
  if (typeof process !== "undefined") {
58
82
  let proc = process;
@@ -132,6 +156,7 @@ export {
132
156
  debug,
133
157
  defaultLogLevel,
134
158
  error,
159
+ getEventPrefix,
135
160
  info,
136
161
  levels,
137
162
  log,
@@ -1,33 +1,3 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import { Writable } from 'node:stream';
3
- export declare const nodeLogDestination: Writable;
4
- interface LogWritable<T> {
5
- write: (chunk: T) => boolean;
6
- }
7
- export type LoggerLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
8
- export type LoggerEvent = 'info' | 'warn' | 'error';
9
- export interface LogOptions {
10
- dest?: LogWritable<LogMessage>;
11
- level?: LoggerLevel;
12
- }
13
- export declare const nodeLogOptions: Required<LogOptions>;
14
- export interface LogMessage {
15
- label: string | null;
16
- level: LoggerLevel;
17
- message: string;
18
- }
19
- export declare const levels: Record<LoggerLevel, number>;
20
- /**
21
- * Emit a message only shown in debug mode.
22
- * Astro (along with many of its dependencies) uses the `debug` package for debug logging.
23
- * You can enable these logs with the `DEBUG=astro:*` environment variable.
24
- * More info https://github.com/debug-js/debug#environment-variables
25
- */
26
- export declare function debug(type: string, ...messages: Array<any>): any;
27
- export declare const logger: {
28
- info: (label: string | null, message: string) => void;
29
- warn: (label: string | null, message: string) => void;
30
- error: (label: string | null, message: string) => void;
31
- };
1
+ import { type LogMessage, type LogWritable } from './core.js';
2
+ export declare const nodeLogDestination: LogWritable<LogMessage>;
32
3
  export declare function enableVerboseLogging(): void;
33
- export {};
@@ -1,71 +1,19 @@
1
1
  import debugPackage from "debug";
2
- import { bold, cyan, dim, red, reset, yellow } from "kleur/colors";
3
- import * as readline from "node:readline";
4
2
  import { Writable } from "node:stream";
5
- import stringWidth from "string-width";
6
- import { dateTimeFormat, error, info, warn } from "./core.js";
7
- let lastMessage;
8
- let lastMessageCount = 1;
9
- const nodeLogDestination = new Writable({
10
- objectMode: true,
11
- write(event, _, callback) {
3
+ import { getEventPrefix, levels } from "./core.js";
4
+ const nodeLogDestination = {
5
+ write(event) {
12
6
  let dest = process.stderr;
13
7
  if (levels[event.level] < levels["error"]) {
14
8
  dest = process.stdout;
15
9
  }
16
- function getPrefix() {
17
- let prefix = "";
18
- let label = event.label;
19
- if (label) {
20
- prefix += dim(dateTimeFormat.format(/* @__PURE__ */ new Date()) + " ");
21
- if (event.level === "info") {
22
- label = bold(cyan(`[${label}]`));
23
- } else if (event.level === "warn") {
24
- label = bold(yellow(`[${label}]`));
25
- } else if (event.level === "error") {
26
- label = bold(red(`[${label}]`));
27
- }
28
- prefix += `${label} `;
29
- }
30
- return reset(prefix);
31
- }
32
- let message = event.message;
33
- if (message === lastMessage) {
34
- lastMessageCount++;
35
- if (levels[event.level] < levels["error"]) {
36
- let lines = 1;
37
- let len = stringWidth(`${getPrefix()}${message}`);
38
- let cols = dest.columns;
39
- if (len > cols) {
40
- lines = Math.ceil(len / cols);
41
- }
42
- for (let i = 0; i < lines; i++) {
43
- readline.clearLine(dest, 0);
44
- readline.cursorTo(dest, 0);
45
- readline.moveCursor(dest, 0, -1);
46
- }
47
- }
48
- message = `${message} ${yellow(`(x${lastMessageCount})`)}`;
10
+ if (event.label === "SKIP_FORMAT") {
11
+ dest.write(event.message + "\n");
49
12
  } else {
50
- lastMessage = message;
51
- lastMessageCount = 1;
13
+ dest.write(getEventPrefix(event) + " " + event.message + "\n");
52
14
  }
53
- dest.write(getPrefix());
54
- dest.write(message);
55
- dest.write("\n");
56
- callback();
15
+ return true;
57
16
  }
58
- });
59
- const nodeLogOptions = {
60
- dest: nodeLogDestination,
61
- level: "info"
62
- };
63
- const levels = {
64
- debug: 20,
65
- info: 30,
66
- warn: 40,
67
- error: 50,
68
- silent: 90
69
17
  };
70
18
  const debuggers = {};
71
19
  function debug(type, ...messages) {
@@ -74,11 +22,6 @@ function debug(type, ...messages) {
74
22
  return debuggers[namespace](...messages);
75
23
  }
76
24
  globalThis._astroGlobalDebug = debug;
77
- const logger = {
78
- info: info.bind(null, nodeLogOptions),
79
- warn: warn.bind(null, nodeLogOptions),
80
- error: error.bind(null, nodeLogOptions)
81
- };
82
25
  function enableVerboseLogging() {
83
26
  debugPackage.enable("*,-babel");
84
27
  debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"');
@@ -88,10 +31,6 @@ function enableVerboseLogging() {
88
31
  );
89
32
  }
90
33
  export {
91
- debug,
92
34
  enableVerboseLogging,
93
- levels,
94
- logger,
95
- nodeLogDestination,
96
- nodeLogOptions
35
+ nodeLogDestination
97
36
  };