astro 2.9.4 → 2.9.5

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.
@@ -13,14 +13,20 @@ const { fallback = 'animate' } = Astro.props as Props;
13
13
  <script>
14
14
  type Fallback = 'none' | 'animate' | 'swap';
15
15
  type Direction = 'forward' | 'back';
16
+ type State = {
17
+ index: number;
18
+ scrollY: number;
19
+ };
16
20
  type Events = 'astro:load' | 'astro:beforeload';
17
21
 
22
+ const persistState = (state: State) => history.replaceState(state, '');
23
+
18
24
  // The History API does not tell you if navigation is forward or back, so
19
25
  // you can figure it using an index. On pushState the index is incremented so you
20
26
  // can use that to determine popstate if going forward or back.
21
27
  let currentHistoryIndex = history.state?.index || 0;
22
28
  if (!history.state) {
23
- history.replaceState({ index: currentHistoryIndex }, document.title);
29
+ persistState({ index: currentHistoryIndex, scrollY: 0 });
24
30
  }
25
31
 
26
32
  const supportsViewTransitions = !!document.startViewTransition;
@@ -29,6 +35,19 @@ const { fallback = 'animate' } = Astro.props as Props;
29
35
  const triggerEvent = (name: Events) => document.dispatchEvent(new Event(name));
30
36
  const onload = () => triggerEvent('astro:load');
31
37
 
38
+ const throttle = (cb: (...args: any[]) => any, delay: number) => {
39
+ let wait = false;
40
+ return (...args: any[]) => {
41
+ if (wait) return;
42
+
43
+ cb(...args);
44
+ wait = true;
45
+ setTimeout(() => {
46
+ wait = false;
47
+ }, delay);
48
+ };
49
+ };
50
+
32
51
  async function getHTML(href: string) {
33
52
  const res = await fetch(href);
34
53
  const html = await res.text();
@@ -64,11 +83,16 @@ const { fallback = 'animate' } = Astro.props as Props;
64
83
 
65
84
  const parser = new DOMParser();
66
85
 
67
- async function updateDOM(dir: Direction, html: string, fallback?: Fallback) {
86
+ async function updateDOM(dir: Direction, html: string, state?: State, fallback?: Fallback) {
68
87
  const doc = parser.parseFromString(html, 'text/html');
69
88
  doc.documentElement.dataset.astroTransition = dir;
70
89
  const swap = () => {
71
90
  document.documentElement.replaceWith(doc.documentElement);
91
+
92
+ if (state?.scrollY != null) {
93
+ scrollTo(0, state.scrollY);
94
+ }
95
+
72
96
  triggerEvent('astro:beforeload');
73
97
  };
74
98
 
@@ -103,7 +127,7 @@ const { fallback = 'animate' } = Astro.props as Props;
103
127
  }
104
128
  }
105
129
 
106
- async function navigate(dir: Direction, href: string) {
130
+ async function navigate(dir: Direction, href: string, state?: State) {
107
131
  let finished: Promise<void>;
108
132
  const { html, ok } = await getHTML(href);
109
133
  // If there is a problem fetching the new page, just do an MPA navigation to it.
@@ -112,9 +136,9 @@ const { fallback = 'animate' } = Astro.props as Props;
112
136
  return;
113
137
  }
114
138
  if (supportsViewTransitions) {
115
- finished = document.startViewTransition(() => updateDOM(dir, html)).finished;
139
+ finished = document.startViewTransition(() => updateDOM(dir, html, state)).finished;
116
140
  } else {
117
- finished = updateDOM(dir, html, getFallback());
141
+ finished = updateDOM(dir, html, state, getFallback());
118
142
  }
119
143
  try {
120
144
  await finished;
@@ -165,25 +189,30 @@ const { fallback = 'animate' } = Astro.props as Props;
165
189
  ev.preventDefault();
166
190
  navigate('forward', link.href);
167
191
  currentHistoryIndex++;
168
- history.pushState({ index: currentHistoryIndex }, '', link.href);
192
+ const newState: State = { index: currentHistoryIndex, scrollY };
193
+ persistState({ index: currentHistoryIndex - 1, scrollY });
194
+ history.pushState(newState, '', link.href);
169
195
  }
170
196
  });
171
- window.addEventListener('popstate', (ev) => {
197
+ addEventListener('popstate', (ev) => {
172
198
  if (!transitionEnabledOnThisPage()) {
173
199
  // The current page doesn't haven't View Transitions,
174
200
  // respect that with a full page reload
175
201
  location.reload();
176
202
  return;
177
203
  }
204
+
178
205
  // hash change creates no state.
179
206
  if (ev.state === null) {
180
- history.replaceState({ index: currentHistoryIndex }, '');
207
+ persistState({ index: currentHistoryIndex, scrollY });
181
208
  ev.preventDefault();
182
209
  return;
183
210
  }
184
- const nextIndex = history.state?.index ?? currentHistoryIndex + 1;
211
+
212
+ const state: State | undefined = history.state;
213
+ const nextIndex = state?.index ?? currentHistoryIndex + 1;
185
214
  const direction: Direction = nextIndex > currentHistoryIndex ? 'forward' : 'back';
186
- navigate(direction, location.href);
215
+ navigate(direction, location.href, state);
187
216
  currentHistoryIndex = nextIndex;
188
217
  });
189
218
 
@@ -206,5 +235,16 @@ const { fallback = 'animate' } = Astro.props as Props;
206
235
  );
207
236
  });
208
237
  addEventListener('load', onload);
238
+ // There's not a good way to record scroll position before a back button.
239
+ // So the way we do it is by listening to scroll and just continuously recording it.
240
+ addEventListener(
241
+ 'scroll',
242
+ throttle(() => {
243
+ if (history.state) {
244
+ persistState({ ...history.state, scrollY });
245
+ }
246
+ }, 300),
247
+ { passive: true }
248
+ );
209
249
  }
210
250
  </script>
@@ -1826,7 +1826,6 @@ export interface SSRMetadata {
1826
1826
  headInTree: boolean;
1827
1827
  extraHead: string[];
1828
1828
  propagators: Map<AstroComponentFactory, AstroComponentInstance>;
1829
- contentKeys: Set<string>;
1830
1829
  }
1831
1830
  export interface PreviewServer {
1832
1831
  host?: string;
@@ -5,8 +5,8 @@ import {
5
5
  createComponent,
6
6
  createHeadAndContent,
7
7
  renderComponent,
8
+ renderScriptElement,
8
9
  renderTemplate,
9
- renderUniqueScriptElement,
10
10
  renderUniqueStylesheet,
11
11
  unescapeHTML
12
12
  } from "../runtime/server/index.js";
@@ -222,7 +222,7 @@ async function render({
222
222
  }).join("");
223
223
  }
224
224
  if (Array.isArray(collectedScripts)) {
225
- scripts = collectedScripts.map((script) => renderUniqueScriptElement(result, script)).join("");
225
+ scripts = collectedScripts.map((script) => renderScriptElement(script)).join("");
226
226
  }
227
227
  let props = baseProps;
228
228
  if (id.endsWith("mdx")) {
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "2.9.4";
1
+ const ASTRO_VERSION = "2.9.5";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -54,7 +54,7 @@ async function dev(settings, options) {
54
54
  isRestart: options.isRestart
55
55
  })
56
56
  );
57
- const currentVersion = "2.9.4";
57
+ const currentVersion = "2.9.5";
58
58
  if (currentVersion.includes("-")) {
59
59
  warn(options.logging, null, msg.prerelease({ currentVersion }));
60
60
  }
@@ -47,7 +47,7 @@ function serverStart({
47
47
  base,
48
48
  isRestart = false
49
49
  }) {
50
- const version = "2.9.4";
50
+ const version = "2.9.5";
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.9.4"}`
236
+ `v${"2.9.5"}`
237
237
  )} ${headline}`
238
238
  );
239
239
  }
@@ -178,8 +178,7 @@ function createResult(args) {
178
178
  hasDirectives: /* @__PURE__ */ new Set(),
179
179
  headInTree: false,
180
180
  extraHead: [],
181
- propagators: /* @__PURE__ */ new Map(),
182
- contentKeys: /* @__PURE__ */ new Set()
181
+ propagators: /* @__PURE__ */ new Map()
183
182
  }
184
183
  };
185
184
  return result;
@@ -3,7 +3,7 @@ export { createAstro } from './astro-global.js';
3
3
  export { renderEndpoint } from './endpoint.js';
4
4
  export { escapeHTML, HTMLBytes, HTMLString, isHTMLString, markHTMLString, unescapeHTML, } from './escape.js';
5
5
  export { renderJSX } from './jsx.js';
6
- export { addAttribute, createHeadAndContent, defineScriptVars, Fragment, maybeRenderHead, renderTemplate as render, renderComponent, Renderer as Renderer, renderHead, renderHTMLElement, renderPage, renderScriptElement, renderSlot, renderSlotToString, renderTemplate, renderToString, renderUniqueScriptElement, renderUniqueStylesheet, voidElementNames, } from './render/index.js';
6
+ export { addAttribute, createHeadAndContent, defineScriptVars, Fragment, maybeRenderHead, renderTemplate as render, renderComponent, Renderer as Renderer, renderHead, renderHTMLElement, renderPage, renderScriptElement, renderSlot, renderSlotToString, renderTemplate, renderToString, renderUniqueStylesheet, voidElementNames, } from './render/index.js';
7
7
  export type { AstroComponentFactory, AstroComponentInstance, ComponentSlots, RenderInstruction, } from './render/index.js';
8
8
  export { renderTransition } from './transition.js';
9
9
  export declare function mergeSlots(...slotted: unknown[]): Record<string, () => any>;
@@ -27,7 +27,6 @@ import {
27
27
  renderSlotToString,
28
28
  renderTemplate as renderTemplate2,
29
29
  renderToString,
30
- renderUniqueScriptElement,
31
30
  renderUniqueStylesheet,
32
31
  voidElementNames
33
32
  } from "./render/index.js";
@@ -116,7 +115,6 @@ export {
116
115
  renderTemplate2 as renderTemplate,
117
116
  renderToString,
118
117
  renderTransition,
119
- renderUniqueScriptElement,
120
118
  renderUniqueStylesheet,
121
119
  spreadAttributes,
122
120
  unescapeHTML,
@@ -15,6 +15,6 @@ export declare class AstroComponentInstance {
15
15
  init(result: SSRResult): Promise<AstroFactoryReturnValue>;
16
16
  render(destination: RenderDestination): Promise<void>;
17
17
  }
18
- export declare function createAstroComponentInstance(result: SSRResult, displayName: string, factory: AstroComponentFactory, props: ComponentProps, slots?: any): Promise<AstroComponentInstance>;
18
+ export declare function createAstroComponentInstance(result: SSRResult, displayName: string, factory: AstroComponentFactory, props: ComponentProps, slots?: any): AstroComponentInstance;
19
19
  export declare function isAstroComponentInstance(obj: unknown): obj is AstroComponentInstance;
20
20
  export {};
@@ -17,6 +17,8 @@ class AstroComponentInstance {
17
17
  }
18
18
  }
19
19
  async init(result) {
20
+ if (this.returnValue !== void 0)
21
+ return this.returnValue;
20
22
  this.returnValue = this.factory(result, this.props, this.slotValues);
21
23
  return this.returnValue;
22
24
  }
@@ -47,15 +49,11 @@ function validateComponentProps(props, displayName) {
47
49
  }
48
50
  }
49
51
  }
50
- async function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
52
+ function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
51
53
  validateComponentProps(props, displayName);
52
54
  const instance = new AstroComponentInstance(result, props, slots, factory);
53
55
  if (isAPropagatingComponent(result, factory) && !result._metadata.propagators.has(factory)) {
54
56
  result._metadata.propagators.set(factory, instance);
55
- const returnValue = await instance.init(result);
56
- if (isHeadAndContent(returnValue)) {
57
- result._metadata.extraHead.push(returnValue.head);
58
- }
59
57
  }
60
58
  return instance;
61
59
  }
@@ -41,10 +41,10 @@ async function renderToReadableStream(result, componentFactory, props, children,
41
41
  );
42
42
  if (templateResult instanceof Response)
43
43
  return templateResult;
44
+ let renderedFirstPageChunk = false;
44
45
  if (isPage) {
45
46
  await bufferHeadContent(result);
46
47
  }
47
- let renderedFirstPageChunk = false;
48
48
  return new ReadableStream({
49
49
  start(controller) {
50
50
  const destination = {
@@ -320,7 +320,7 @@ async function renderHTMLComponent(result, Component, _props, slots = {}) {
320
320
  };
321
321
  }
322
322
  async function renderAstroComponent(result, displayName, Component, props, slots = {}) {
323
- const instance = await createAstroComponentInstance(result, displayName, Component, props, slots);
323
+ const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
324
324
  const chunks = [];
325
325
  const temporaryDestination = {
326
326
  write: (chunk) => chunks.push(chunk)
@@ -6,6 +6,6 @@ export { renderHTMLElement } from './dom.js';
6
6
  export { maybeRenderHead, renderHead } from './head.js';
7
7
  export { renderPage } from './page.js';
8
8
  export { renderSlot, renderSlotToString, type ComponentSlots } from './slot.js';
9
- export { renderScriptElement, renderUniqueScriptElement, renderUniqueStylesheet } from './tags.js';
9
+ export { renderScriptElement, renderUniqueStylesheet } from './tags.js';
10
10
  export type { RenderInstruction } from './types';
11
11
  export { addAttribute, defineScriptVars, voidElementNames } from './util.js';
@@ -5,7 +5,7 @@ import { renderHTMLElement } from "./dom.js";
5
5
  import { maybeRenderHead, renderHead } from "./head.js";
6
6
  import { renderPage } from "./page.js";
7
7
  import { renderSlot, renderSlotToString } from "./slot.js";
8
- import { renderScriptElement, renderUniqueScriptElement, renderUniqueStylesheet } from "./tags.js";
8
+ import { renderScriptElement, renderUniqueStylesheet } from "./tags.js";
9
9
  import { addAttribute, defineScriptVars, voidElementNames } from "./util.js";
10
10
  export {
11
11
  Fragment,
@@ -26,7 +26,6 @@ export {
26
26
  renderSlotToString,
27
27
  renderTemplate,
28
28
  renderToString,
29
- renderUniqueScriptElement,
30
29
  renderUniqueStylesheet,
31
30
  voidElementNames
32
31
  };
@@ -1,5 +1,4 @@
1
1
  import type { SSRElement, SSRResult } from '../../../@types/astro';
2
2
  import type { StylesheetAsset } from '../../../core/app/types';
3
3
  export declare function renderScriptElement({ props, children }: SSRElement): string;
4
- export declare function renderUniqueScriptElement(result: SSRResult, { props, children }: SSRElement): string;
5
4
  export declare function renderUniqueStylesheet(result: SSRResult, sheet: StylesheetAsset): string | undefined;
@@ -5,52 +5,19 @@ function renderScriptElement({ props, children }) {
5
5
  children
6
6
  });
7
7
  }
8
- function renderUniqueScriptElement(result, { props, children }) {
9
- if (Array.from(result.scripts).some((s) => {
10
- if (s.props.type === props.type && s.props.src === props.src) {
11
- return true;
12
- }
13
- if (!props.src && s.children === children)
14
- return true;
15
- }))
16
- return "";
17
- const key = `script-${props.type}-${props.src}-${children}`;
18
- if (checkOrAddContentKey(result, key))
19
- return "";
20
- return renderScriptElement({ props, children });
21
- }
22
8
  function renderUniqueStylesheet(result, sheet) {
23
9
  if (sheet.type === "external") {
24
10
  if (Array.from(result.styles).some((s) => s.props.href === sheet.src))
25
11
  return "";
26
- const key = "link-external-" + sheet.src;
27
- if (checkOrAddContentKey(result, key))
28
- return "";
29
- return renderElement("link", {
30
- props: {
31
- rel: "stylesheet",
32
- href: sheet.src
33
- },
34
- children: ""
35
- });
12
+ return renderElement("link", { props: { rel: "stylesheet", href: sheet.src }, children: "" });
36
13
  }
37
14
  if (sheet.type === "inline") {
38
15
  if (Array.from(result.styles).some((s) => s.children.includes(sheet.content)))
39
16
  return "";
40
- const key = `link-inline-` + sheet.content;
41
- if (checkOrAddContentKey(result, key))
42
- return "";
43
17
  return renderElement("style", { props: { type: "text/css" }, children: sheet.content });
44
18
  }
45
19
  }
46
- function checkOrAddContentKey(result, key) {
47
- if (result._metadata.contentKeys.has(key))
48
- return true;
49
- result._metadata.contentKeys.add(key);
50
- return false;
51
- }
52
20
  export {
53
21
  renderScriptElement,
54
- renderUniqueScriptElement,
55
22
  renderUniqueStylesheet
56
23
  };
@@ -22,7 +22,7 @@ type HandleRoute = {
22
22
  incomingRequest: http.IncomingMessage;
23
23
  incomingResponse: http.ServerResponse;
24
24
  manifest: SSRManifest;
25
- status?: number;
25
+ status?: 404 | 500;
26
26
  };
27
27
  export declare function handleRoute({ matchedRoute, url, pathname, status, body, origin, env, manifestData, incomingRequest, incomingResponse, manifest, }: HandleRoute): Promise<void>;
28
28
  export {};
@@ -3,6 +3,7 @@ import { attachToResponse } from "../core/cookies/index.js";
3
3
  import { AstroErrorData, isAstroError } from "../core/errors/index.js";
4
4
  import { warn } from "../core/logger/core.js";
5
5
  import { loadMiddleware } from "../core/middleware/loadMiddleware.js";
6
+ import { isEndpointResult } from "../core/render/core.js";
6
7
  import {
7
8
  createRenderContext,
8
9
  getParamsAndProps,
@@ -151,7 +152,7 @@ async function handleRoute({
151
152
  });
152
153
  const onRequest = (_a = options.middleware) == null ? void 0 : _a.onRequest;
153
154
  const result = await tryRenderRoute(route.type, renderContext, env, mod, onRequest);
154
- if (route.type === "endpoint" && !(result instanceof Response)) {
155
+ if (isEndpointResult(result, route.type)) {
155
156
  if (result.type === "response") {
156
157
  if (result.response.headers.get("X-Astro-Response") === "Not-Found") {
157
158
  const fourOhFourRoute = await matchRoute("/404", env, manifestData);
@@ -186,7 +187,7 @@ async function handleRoute({
186
187
  attachToResponse(response, result.cookies);
187
188
  await writeWebResponse(incomingResponse, response);
188
189
  }
189
- } else if (result instanceof Response) {
190
+ } else {
190
191
  if (result.status === 404) {
191
192
  const fourOhFourRoute = await matchRoute("/404", env, manifestData);
192
193
  return handleRoute({
@@ -204,7 +205,17 @@ async function handleRoute({
204
205
  });
205
206
  }
206
207
  let response = result;
207
- if (status && response.status !== status) {
208
+ if (
209
+ // We are in a recursion, and it's possible that this function is called itself with a status code
210
+ // By default, the status code passed via parameters is computed by the matched route.
211
+ //
212
+ // By default, we should give priority to the status code passed, although it's possible that
213
+ // the `Response` emitted by the user is a redirect. If so, then return the returned response.
214
+ response.status < 400 && response.status >= 300
215
+ ) {
216
+ await writeSSRResult(request, response, incomingResponse);
217
+ return;
218
+ } else if (status && response.status !== status && (status === 404 || status === 500)) {
208
219
  response = new Response(result.body, { ...result, status });
209
220
  }
210
221
  await writeSSRResult(request, response, incomingResponse);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "2.9.4",
3
+ "version": "2.9.5",
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",