vike 0.4.194 → 0.4.195-commit-486b49a

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 (41) hide show
  1. package/LICENSE.md +9 -0
  2. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.js +5 -1
  3. package/dist/cjs/node/runtime/html/injectAssets/getHtmlTags.js +17 -12
  4. package/dist/cjs/node/runtime/html/injectAssets/injectHtmlTags.js +1 -1
  5. package/dist/cjs/node/runtime/html/injectAssets.js +2 -2
  6. package/dist/cjs/node/runtime/renderPage/analyzePage.js +4 -4
  7. package/dist/cjs/node/runtime/renderPage/createHttpResponse.js +24 -12
  8. package/dist/cjs/node/runtime/renderPage/handleErrorWithoutErrorPage.js +2 -2
  9. package/dist/cjs/node/runtime/renderPage/renderPageAlreadyRouted.js +1 -1
  10. package/dist/cjs/node/runtime/renderPage.js +11 -10
  11. package/dist/cjs/shared/getPageFiles/analyzeClientSide.js +3 -3
  12. package/dist/cjs/shared/route/executeOnBeforeRouteHook.js +1 -1
  13. package/dist/cjs/utils/PROJECT_VERSION.js +1 -1
  14. package/dist/esm/client/client-routing-runtime/isClientSideRoutable.js +2 -2
  15. package/dist/esm/client/client-routing-runtime/renderPageClientSide.js +29 -15
  16. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.js +5 -1
  17. package/dist/esm/node/runtime/html/injectAssets/getHtmlTags.d.ts +1 -1
  18. package/dist/esm/node/runtime/html/injectAssets/getHtmlTags.js +17 -12
  19. package/dist/esm/node/runtime/html/injectAssets/injectHtmlTags.js +1 -1
  20. package/dist/esm/node/runtime/html/injectAssets.js +2 -2
  21. package/dist/esm/node/runtime/renderPage/analyzePage.js +4 -4
  22. package/dist/esm/node/runtime/renderPage/createHttpResponse.d.ts +7 -3
  23. package/dist/esm/node/runtime/renderPage/createHttpResponse.js +24 -12
  24. package/dist/esm/node/runtime/renderPage/handleErrorWithoutErrorPage.d.ts +2 -0
  25. package/dist/esm/node/runtime/renderPage/handleErrorWithoutErrorPage.js +3 -3
  26. package/dist/esm/node/runtime/renderPage/renderPageAlreadyRouted.js +2 -2
  27. package/dist/esm/node/runtime/renderPage.js +11 -10
  28. package/dist/esm/shared/getPageFiles/analyzeClientSide.d.ts +1 -1
  29. package/dist/esm/shared/getPageFiles/analyzeClientSide.js +3 -3
  30. package/dist/esm/shared/page-configs/Config.d.ts +2 -2
  31. package/dist/esm/shared/route/executeOnBeforeRouteHook.js +1 -1
  32. package/dist/esm/utils/PROJECT_VERSION.d.ts +1 -1
  33. package/dist/esm/utils/PROJECT_VERSION.js +1 -1
  34. package/dist/esm/utils/projectInfo.d.ts +1 -1
  35. package/package.json +5 -4
  36. /package/dist/cjs/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/assertNoInfiniteHttpRedirect.js +0 -0
  37. /package/dist/cjs/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/getCacheControl.js +0 -0
  38. /package/dist/esm/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/assertNoInfiniteHttpRedirect.d.ts +0 -0
  39. /package/dist/esm/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/assertNoInfiniteHttpRedirect.js +0 -0
  40. /package/dist/esm/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/getCacheControl.d.ts +0 -0
  41. /package/dist/esm/node/runtime/renderPage/{createHttpResponseObject → createHttpResponse}/getCacheControl.js +0 -0
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Romuald Brillout
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -77,7 +77,11 @@ const configDefinitionsBuiltIn = {
77
77
  meta: {
78
78
  env: { config: true }
79
79
  },
80
- clientEntryLoaded: {
80
+ // Whether the page loads:
81
+ // - Vike's client runtime
82
+ // - User's client hooks
83
+ // In other words, whether the page is "HTML-only" (https://vike.dev/render-modes). HTML-only pages shouldn't load the client runtime nor client hooks.
84
+ isClientRuntimeLoaded: {
81
85
  env: { server: true, client: true },
82
86
  eager: true,
83
87
  _computed: (configValueSources) => {
@@ -25,7 +25,7 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
25
25
  if (asset.isEntry && asset.assetType === 'script') {
26
26
  // We could allow the user to change the position of <script> but we currently don't:
27
27
  // - Because of mergeScriptEntries()
28
- // - We would need to add STREAM to to PreloadFilterInject
28
+ // - We would need to add HTML_STREAM to to PreloadFilterInject
29
29
  // To suppor this, we should add the JavaScript entry to injectFilterEntries (with an `src` value of `null`)
30
30
  return false;
31
31
  }
@@ -82,31 +82,36 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
82
82
  // ==========
83
83
  // JavaScript
84
84
  // ==========
85
- // - The pageContext JSON should be fully sent before Vike's client runtime starts executing.
85
+ // - By default, we place the entry <script> towards the end of the HTML for better performance.
86
+ // - Performance-wise, it's more interesting to start showing the page (parse HTML and load CSS) before starting loading scripts.
87
+ // - But with HTML streaming, in order to support [Progressive Rendering](https://vike.dev/streaming#progressive-rendering), the entry <script> should be injected earlier instead.
88
+ // - The entry <script> shouldn't be `<script defer>` upon HTML streaming, otherwise progressive hydration while SSR streaming won't work.
89
+ // - `<script id="vike_pageContext" type="application/json">` (the `pageContext` JSON) should be fully sent before Vike's client runtime starts executing.
86
90
  // - Otherwise, race condition "SyntaxError: Unterminated string in JSON": https://github.com/vikejs/vike/issues/567
87
- // - <script id="vike_pageContext" type="application/json"> must appear before the entry <script> (which loads Vike's client runtime).
88
- // - <script id="vike_pageContext" type="application/json"> can't be async nor defer.
89
- // - The entry <script> can't be defer, otherwise progressive hydration while SSR streaming won't work.
90
- // - The entry <script> should be towards the end of the HTML as performance-wise it's more interesting to parse <div id="page-view"> before running the entry <script> which initiates the hydration.
91
- // - But with HTML streaming, in order to support [Progressive Rendering](https://vike.dev/streaming#progressive-rendering), the entry <script> should be injected early instead.
91
+ // - `<script id="vike_pageContext" type="application/json">` must appear before the entry <script> (which loads Vike's client runtime).
92
+ // - `<script id="vike_pageContext" type="application/json">` can't be async nor defer.
93
+ const positionJavaScriptDefault = 'HTML_END';
92
94
  const positionJavaScriptEntry = (() => {
93
95
  if (injectScriptsAt !== null) {
94
96
  if (pageContext._pageContextPromise) {
95
97
  (0, utils_js_1.assertWarning)(injectScriptsAt === 'HTML_END' || !isStream, `You're setting injectScriptsAt to ${picocolors_1.default.code(JSON.stringify(injectScriptsAt))} while using HTML streaming with a pageContext promise (https://vike.dev/streaming#initial-data-after-stream-end) which is contradictory: the pageContext promise is skipped.`, { onlyOnce: true });
96
98
  }
99
+ if (injectScriptsAt === 'HTML_STREAM' && !isStream) {
100
+ return positionJavaScriptDefault;
101
+ }
97
102
  return injectScriptsAt;
98
103
  }
99
104
  if (pageContext._pageContextPromise) {
100
105
  // - If there is a pageContext._pageContextPromise then <script id="vike_pageContext" type="application/json"> needs to await for it.
101
106
  // - pageContext._pageContextPromise is typically resolved only after the page's components are rendered and the stream ended.
102
107
  // - https://vike.dev/streaming#initial-data-after-stream-end
103
- return 'HTML_END';
108
+ return positionJavaScriptDefault;
104
109
  }
105
110
  if (streamFromReactStreamingPackage && !streamFromReactStreamingPackage.hasStreamEnded()) {
106
111
  // If there is a stream then, in order to support progressive hydration, inject the JavaScript during the stream after React(/Vue/Solid/...) resolved the first suspense boundary.
107
- return 'STREAM';
112
+ return 'HTML_STREAM';
108
113
  }
109
- return 'HTML_END';
114
+ return positionJavaScriptDefault;
110
115
  })();
111
116
  if (pageContext._pageContextPromise && streamFromReactStreamingPackage) {
112
117
  // - Should we show this warning for Solid as well? Solid seems to also support progressive rendering.
@@ -140,7 +145,7 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
140
145
  const htmlTag = (0, inferHtmlTags_js_1.inferPreloadTag)(asset);
141
146
  if (!asset.inject)
142
147
  return;
143
- // Ideally, instead of this conditional ternary operator, we should add STREAM to PreloadFilterInject (or a better fitting name such as HTML_STREAM)
148
+ // Ideally, instead of this conditional ternary operator, we should add HTML_STREAM to PreloadFilterInject
144
149
  const position = asset.inject === 'HTML_END' ? positionJavaScriptEntry : asset.inject;
145
150
  htmlTags.push({ htmlTag, position });
146
151
  });
@@ -223,6 +228,6 @@ function getInjectScriptsAt(pageId, pageConfigs) {
223
228
  (0, utils_js_1.assertUsage)(injectScriptsAt === null ||
224
229
  injectScriptsAt === 'HTML_BEGIN' ||
225
230
  injectScriptsAt === 'HTML_END' ||
226
- injectScriptsAt === 'STREAM', `${configDefinedAt} has an invalid value`);
231
+ injectScriptsAt === 'HTML_STREAM', `${configDefinedAt} has an invalid value`);
227
232
  return injectScriptsAt;
228
233
  }
@@ -13,7 +13,7 @@ function injectHtmlTags(htmlString, htmlTags, position) {
13
13
  exports.injectHtmlTags = injectHtmlTags;
14
14
  // Is it worth it? Should we remove this? https://github.com/vikejs/vike/pull/1740#issuecomment-2230540892
15
15
  function injectHtmlTagsUsingStream(htmlTags, streamFromReactStreamingPackage) {
16
- const htmlFragment = joinHtmlTags(htmlTags.filter((h) => h.position === 'STREAM'));
16
+ const htmlFragment = joinHtmlTags(htmlTags.filter((h) => h.position === 'HTML_STREAM'));
17
17
  if (htmlFragment) {
18
18
  (0, utils_js_1.assert)(!streamFromReactStreamingPackage.hasStreamEnded());
19
19
  streamFromReactStreamingPackage.injectToStream(htmlFragment, { flush: true });
@@ -13,7 +13,7 @@ async function injectHtmlTagsToString(htmlParts, pageContext, injectFilter) {
13
13
  let htmlString = htmlPartsToString(htmlParts, pageAssets);
14
14
  htmlString = injectToHtmlBegin(htmlString, htmlTags);
15
15
  htmlString = injectToHtmlEnd(htmlString, htmlTags);
16
- (0, utils_js_1.assert)(htmlTags.filter((snippet) => snippet.position === 'STREAM').length === 0);
16
+ (0, utils_js_1.assert)(htmlTags.filter((snippet) => snippet.position === 'HTML_STREAM').length === 0);
17
17
  return htmlString;
18
18
  }
19
19
  exports.injectHtmlTagsToString = injectHtmlTagsToString;
@@ -41,7 +41,7 @@ function injectHtmlTagsToStream(pageContext, streamFromReactStreamingPackage, in
41
41
  if (streamFromReactStreamingPackage)
42
42
  return null;
43
43
  (0, utils_js_1.assert)(htmlTags);
44
- const tags = htmlTags.filter((h) => h.position === 'STREAM');
44
+ const tags = htmlTags.filter((h) => h.position === 'HTML_STREAM');
45
45
  if (tags.length === 0)
46
46
  return null;
47
47
  const htmlFragment = (0, injectHtmlTags_js_1.joinHtmlTags)(tags);
@@ -9,17 +9,17 @@ const globalContext_js_1 = require("../globalContext.js");
9
9
  const getConfigValue_js_1 = require("../../../shared/page-configs/getConfigValue.js");
10
10
  function analyzePage(pageFilesAll, pageConfig, pageId) {
11
11
  if (pageConfig) {
12
- const { clientEntryLoaded, isClientRouting } = (0, analyzeClientSide_js_1.analyzeClientSide)(pageConfig, pageFilesAll, pageId);
12
+ const { isClientRuntimeLoaded, isClientRouting } = (0, analyzeClientSide_js_1.analyzeClientSide)(pageConfig, pageFilesAll, pageId);
13
13
  const clientEntries = [];
14
14
  const clientFilePath = (0, getConfigValue_js_1.getConfigValueRuntime)(pageConfig, 'client', 'string')?.value ?? null;
15
15
  if (clientFilePath)
16
16
  clientEntries.push(clientFilePath);
17
- if (clientEntryLoaded)
17
+ if (isClientRuntimeLoaded)
18
18
  clientEntries.push((0, determineClientEntry_js_1.getVikeClientEntry)(isClientRouting));
19
19
  const clientDependencies = [];
20
20
  clientDependencies.push({
21
21
  id: (0, virtualFilePageConfigValuesAll_js_1.getVirtualFileIdPageConfigValuesAll)(pageConfig.pageId, true),
22
- onlyAssets: clientEntryLoaded ? false : true,
22
+ onlyAssets: isClientRuntimeLoaded ? false : true,
23
23
  eagerlyImported: false
24
24
  });
25
25
  // In production we inject the import of the server virtual module with ?extractAssets inside the client virtual module
@@ -55,7 +55,7 @@ function analyzePage(pageFilesAll, pageConfig, pageId) {
55
55
  });
56
56
  });
57
57
  return {
58
- isHtmlOnly: !clientEntryLoaded,
58
+ isHtmlOnly: !isClientRuntimeLoaded,
59
59
  isClientRouting,
60
60
  clientEntries,
61
61
  clientDependencies,
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createHttpResponseFavicon404 = exports.createHttpResponseRedirect = exports.createHttpResponseError = exports.createHttpResponsePageContextJson = exports.createHttpResponse = void 0;
3
+ exports.createHttpResponseFavicon404 = exports.createHttpResponseRedirect = exports.createHttpResponseError = exports.createHttpResponsePageContextJson = exports.createHttpResponsePage = void 0;
4
4
  const utils_js_1 = require("../utils.js");
5
5
  const error_page_js_1 = require("../../../shared/error-page.js");
6
6
  const getHttpResponseBody_js_1 = require("./getHttpResponseBody.js");
7
7
  const getEarlyHints_js_1 = require("./getEarlyHints.js");
8
- const getCacheControl_js_1 = require("./createHttpResponseObject/getCacheControl.js");
9
- const assertNoInfiniteHttpRedirect_js_1 = require("./createHttpResponseObject/assertNoInfiniteHttpRedirect.js");
10
- async function createHttpResponse(htmlRender, renderHook, pageContext) {
8
+ const getCacheControl_js_1 = require("./createHttpResponse/getCacheControl.js");
9
+ const assertNoInfiniteHttpRedirect_js_1 = require("./createHttpResponse/assertNoInfiniteHttpRedirect.js");
10
+ async function createHttpResponsePage(htmlRender, renderHook, pageContext) {
11
11
  let statusCode = pageContext.abortStatusCode;
12
12
  if (!statusCode) {
13
13
  const isError = !pageContext._pageId || (0, error_page_js_1.isErrorPage)(pageContext._pageId, pageContext._pageConfigs);
@@ -30,21 +30,33 @@ async function createHttpResponse(htmlRender, renderHook, pageContext) {
30
30
  if (cacheControl) {
31
31
  headers.push(['Cache-Control', cacheControl]);
32
32
  }
33
- return getHttpResponse(statusCode, 'text/html;charset=utf-8', headers, htmlRender, earlyHints, renderHook);
33
+ return createHttpResponse(statusCode, 'text/html;charset=utf-8', headers, htmlRender, earlyHints, renderHook);
34
34
  }
35
- exports.createHttpResponse = createHttpResponse;
35
+ exports.createHttpResponsePage = createHttpResponsePage;
36
36
  function createHttpResponseFavicon404() {
37
- const httpResponse = getHttpResponse(404, 'text/html;charset=utf-8', [], "<p>No favicon.ico found.</p><script>console.log('This HTTP response was generated by Vike.')</script>");
37
+ const httpResponse = createHttpResponse(404, 'text/html;charset=utf-8', [], "<p>No favicon.ico found.</p><script>console.log('This HTTP response was generated by Vike.')</script>");
38
38
  return httpResponse;
39
39
  }
40
40
  exports.createHttpResponseFavicon404 = createHttpResponseFavicon404;
41
- function createHttpResponseError() {
42
- const httpResponse = getHttpResponse(500, 'text/html;charset=utf-8', [], "<p>An error occurred.</p><script>console.log('This HTTP response was generated by Vike. This response is used instead of rendering the error page (https://vike.dev/error-page), either because there isn't error page or because an error occurred while rendering the error page.')</script>");
41
+ function createHttpResponseError(pageContext) {
42
+ const reason = (() => {
43
+ if (!pageContext) {
44
+ return 'no error page (https://vike.dev/error-page) could be rendered';
45
+ }
46
+ const errorPageId = (0, error_page_js_1.getErrorPageId)(pageContext._pageFilesAll, pageContext._pageConfigs);
47
+ if (errorPageId) {
48
+ return "the error page (https://vike.dev/error-page) couldn't be rendered (for example if an error occurred while rendering the error page)";
49
+ }
50
+ else {
51
+ return 'no error page (https://vike.dev/error-page) is defined, make sure to create one';
52
+ }
53
+ })();
54
+ const httpResponse = createHttpResponse(500, 'text/html;charset=utf-8', [], `<p>An error occurred.</p><script>console.log(${JSON.stringify(`This HTTP response was generated by Vike. Vike returned this response because ${reason}.`)})</script>`);
43
55
  return httpResponse;
44
56
  }
45
57
  exports.createHttpResponseError = createHttpResponseError;
46
58
  async function createHttpResponsePageContextJson(pageContextSerialized) {
47
- const httpResponse = getHttpResponse(200, 'application/json', [], pageContextSerialized, [], null);
59
+ const httpResponse = createHttpResponse(200, 'application/json', [], pageContextSerialized, [], null);
48
60
  return httpResponse;
49
61
  }
50
62
  exports.createHttpResponsePageContextJson = createHttpResponsePageContextJson;
@@ -56,13 +68,13 @@ urlLogical) {
56
68
  (0, utils_js_1.assert)(statusCode);
57
69
  (0, utils_js_1.assert)(300 <= statusCode && statusCode <= 399);
58
70
  const headers = [['Location', url]];
59
- return getHttpResponse(statusCode, 'text/html;charset=utf-8', headers,
71
+ return createHttpResponse(statusCode, 'text/html;charset=utf-8', headers,
60
72
  // For bots / programmatic crawlig: show what's going on.
61
73
  // For users: showing a blank page is probably better than a flickering text.
62
74
  `<p style="display: none">Redirecting to ${url}</p><script>console.log('This HTTP response was generated by Vike.')</script>`);
63
75
  }
64
76
  exports.createHttpResponseRedirect = createHttpResponseRedirect;
65
- function getHttpResponse(statusCode, contentType, headers, htmlRender, earlyHints = [], renderHook = null) {
77
+ function createHttpResponse(statusCode, contentType, headers, htmlRender, earlyHints = [], renderHook = null) {
66
78
  headers.push(['Content-Type', contentType]);
67
79
  (0, utils_js_1.assert)(renderHook || typeof htmlRender === 'string');
68
80
  return {
@@ -18,14 +18,14 @@ async function handleErrorWithoutErrorPage(pageContext) {
18
18
  warnMissingErrorPage(isV1);
19
19
  }
20
20
  if (!pageContext.isClientSideNavigation) {
21
- const httpResponse = (0, createHttpResponse_js_1.createHttpResponseError)();
21
+ const httpResponse = (0, createHttpResponse_js_1.createHttpResponseError)(pageContext);
22
22
  (0, utils_js_1.objectAssign)(pageContext, { httpResponse });
23
23
  return pageContext;
24
24
  }
25
25
  else {
26
26
  const __getPageAssets = async () => [];
27
27
  (0, utils_js_1.objectAssign)(pageContext, { __getPageAssets });
28
- const httpResponse = await (0, createHttpResponse_js_1.createHttpResponse)((0, stringify_1.stringify)({ serverSideError: true }), null, pageContext);
28
+ const httpResponse = await (0, createHttpResponse_js_1.createHttpResponsePage)((0, stringify_1.stringify)({ serverSideError: true }), null, pageContext);
29
29
  (0, utils_js_1.objectAssign)(pageContext, { httpResponse });
30
30
  return pageContext;
31
31
  }
@@ -58,7 +58,7 @@ async function renderPageAlreadyRouted(pageContext) {
58
58
  }
59
59
  const renderHookResult = await (0, executeOnRenderHtmlHook_js_1.executeOnRenderHtmlHook)(pageContext);
60
60
  const { htmlRender, renderHook } = renderHookResult;
61
- const httpResponse = await (0, createHttpResponse_js_1.createHttpResponse)(htmlRender, renderHook, pageContext);
61
+ const httpResponse = await (0, createHttpResponse_js_1.createHttpResponsePage)(htmlRender, renderHook, pageContext);
62
62
  (0, utils_js_1.objectAssign)(pageContext, { httpResponse });
63
63
  return pageContext;
64
64
  }
@@ -56,7 +56,7 @@ async function renderPageAndPrepare(pageContextInit, httpRequestId) {
56
56
  // Invalid config
57
57
  const handleInvalidConfig = (err) => {
58
58
  (0, loggerRuntime_js_1.logRuntimeInfo)?.(picocolors_1.default.bold(picocolors_1.default.red('Error while loading a Vike config file, see error above.')), httpRequestId, 'error');
59
- const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit);
59
+ const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit, null);
60
60
  return pageContextWithError;
61
61
  };
62
62
  if (isConfigInvalid_js_1.isConfigInvalid) {
@@ -76,7 +76,7 @@ async function renderPageAndPrepare(pageContextInit, httpRequestId) {
76
76
  // initGlobalContext_renderPage() and getRenderContext() don't call any user hooks => err isn't thrown from user code.
77
77
  (0, utils_js_1.assert)(!(0, abort_js_1.isAbortError)(err));
78
78
  (0, loggerRuntime_js_1.logRuntimeError)(err, httpRequestId);
79
- const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit);
79
+ const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit, null);
80
80
  return pageContextWithError;
81
81
  }
82
82
  if (isConfigInvalid_js_1.isConfigInvalid) {
@@ -182,7 +182,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
182
182
  if (!handled.pageContextReturn) {
183
183
  const pageContextAbort = errErrorPage._pageContextAbort;
184
184
  (0, utils_js_1.assertWarning)(false, `Failed to render error page because ${picocolors_1.default.cyan(pageContextAbort._abortCall)} was called: make sure ${picocolors_1.default.cyan(pageContextAbort._abortCaller)} doesn't occur while the error page is being rendered.`, { onlyOnce: false });
185
- const pageContextHttpWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit);
185
+ const pageContextHttpWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit, pageContextErrorPageInit);
186
186
  return pageContextHttpWithError;
187
187
  }
188
188
  // `throw redirect()` / `throw render(url)`
@@ -191,7 +191,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
191
191
  if ((0, isNewError_js_1.isNewError)(errErrorPage, errNominalPage)) {
192
192
  (0, loggerRuntime_js_1.logRuntimeError)(errErrorPage, httpRequestId);
193
193
  }
194
- const pageContextWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit);
194
+ const pageContextWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit, pageContextErrorPageInit);
195
195
  return pageContextWithError;
196
196
  }
197
197
  return pageContextErrorPage;
@@ -242,9 +242,12 @@ function logHttpResponse(urlOriginalPretty, httpRequestId, pageContextReturn) {
242
242
  }
243
243
  (0, loggerRuntime_js_1.logRuntimeInfo)?.(msg, httpRequestId, isNominal ? 'info' : 'error');
244
244
  }
245
- function getPageContextHttpResponseError(err, pageContextInit) {
245
+ function prettyUrl(url) {
246
+ return picocolors_1.default.bold(decodeURI(url));
247
+ }
248
+ function getPageContextHttpResponseError(err, pageContextInit, pageContext) {
246
249
  const pageContextWithError = createPageContext(pageContextInit);
247
- const httpResponse = (0, createHttpResponse_js_1.createHttpResponseError)();
250
+ const httpResponse = (0, createHttpResponse_js_1.createHttpResponseError)(pageContext);
248
251
  (0, utils_js_1.objectAssign)(pageContextWithError, {
249
252
  httpResponse,
250
253
  errorWhileRendering: err
@@ -284,6 +287,7 @@ async function renderPageNominal(pageContext) {
284
287
  }
285
288
  }
286
289
  (0, utils_js_1.assert)((0, utils_js_1.hasProp)(pageContext, '_pageId', 'string'));
290
+ (0, utils_js_1.assert)(pageContext.errorWhileRendering === null);
287
291
  // Render
288
292
  const pageContextAfterRender = await (0, renderPageAlreadyRouted_js_1.renderPageAlreadyRouted)(pageContext);
289
293
  (0, utils_js_1.assert)(pageContext === pageContextAfterRender);
@@ -446,8 +450,5 @@ function assertBaseUrl(pageContextInit) {
446
450
  const { urlOriginal } = pageContextInit;
447
451
  const { urlWithoutPageContextRequestSuffix } = (0, handlePageContextRequestUrl_js_1.handlePageContextRequestUrl)(urlOriginal);
448
452
  const { hasBaseServer } = (0, utils_js_1.parseUrl)(urlWithoutPageContextRequestSuffix, baseServer);
449
- (0, utils_js_1.assertUsage)(hasBaseServer, `${picocolors_1.default.code('renderPage(pageContextInit)')} (https://vike.dev/renderPage) called with ${picocolors_1.default.code(`pageContextInit.urlOriginal===${JSON.stringify(urlOriginal)}`)} which doesn't start with Base URL ${prettyUrl(baseServer)} (https://vike.dev/base-url)`);
450
- }
451
- function prettyUrl(url) {
452
- return picocolors_1.default.code(decodeURI(url));
453
+ (0, utils_js_1.assertUsage)(hasBaseServer, `${picocolors_1.default.code('renderPage(pageContextInit)')} (https://vike.dev/renderPage) called with ${picocolors_1.default.code(`pageContextInit.urlOriginal===${JSON.stringify(urlOriginal)}`)} which doesn't start with Base URL ${picocolors_1.default.code(baseServer)} (https://vike.dev/base-url)`);
453
454
  }
@@ -7,14 +7,14 @@ function analyzeClientSide(pageConfig, pageFilesAll, pageId) {
7
7
  // V1 design
8
8
  if (pageConfig) {
9
9
  const isClientRouting = (0, getConfigValue_js_1.getConfigValueRuntime)(pageConfig, 'clientRouting', 'boolean')?.value ?? false;
10
- const clientEntryLoaded = (0, getConfigValue_js_1.getConfigValueRuntime)(pageConfig, 'clientEntryLoaded', 'boolean')?.value ?? false;
11
- return { clientEntryLoaded, isClientRouting };
10
+ const isClientRuntimeLoaded = (0, getConfigValue_js_1.getConfigValueRuntime)(pageConfig, 'isClientRuntimeLoaded', 'boolean')?.value ?? false;
11
+ return { isClientRuntimeLoaded, isClientRouting };
12
12
  }
13
13
  else {
14
14
  // TODO/v1-release: remove
15
15
  // V0.4 design
16
16
  const { isHtmlOnly, isClientRouting } = (0, analyzePageClientSide_js_1.analyzePageClientSide)(pageFilesAll, pageId);
17
- return { clientEntryLoaded: !isHtmlOnly, isClientRouting };
17
+ return { isClientRuntimeLoaded: !isHtmlOnly, isClientRouting };
18
18
  }
19
19
  }
20
20
  exports.analyzeClientSide = analyzeClientSide;
@@ -72,7 +72,7 @@ async function getPageContextFromHook(onBeforeRouteHook, pageContext) {
72
72
  }
73
73
  if ((0, utils_js_1.hasProp)(hookReturn.pageContext, 'urlLogical')) {
74
74
  (0, utils_js_1.assertUsageUrlPathnameAbsolute)(
75
- // We type-cast to string instead of assertUsage() in order to save client-side KBs
75
+ // We skip validation and type-cast instead of assertUsage() in order to save client-side KBs
76
76
  hookReturn.pageContext.urlLogical, `${errPrefix} returned ${picocolors_1.default.cyan('{ pageContext: { urlLogical } }')} but ${picocolors_1.default.cyan('urlLogical')}`);
77
77
  }
78
78
  (0, assertPageContextProvidedByUser_js_1.assertPageContextProvidedByUser)(hookReturn.pageContext, {
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PROJECT_VERSION = void 0;
4
4
  // Automatically updated by @brillout/release-me
5
- exports.PROJECT_VERSION = '0.4.194';
5
+ exports.PROJECT_VERSION = '0.4.195-commit-486b49a';
@@ -7,6 +7,6 @@ async function isClientSideRoutable(pageId, pageContext) {
7
7
  sharedPageFilesAlreadyLoaded: false
8
8
  });
9
9
  const pageConfig = findPageConfig(pageContext._pageConfigs, pageId);
10
- const { clientEntryLoaded, isClientRouting } = analyzeClientSide(pageConfig, pageContext._pageFilesAll, pageId);
11
- return clientEntryLoaded && isClientRouting;
10
+ const { isClientRuntimeLoaded, isClientRouting } = analyzeClientSide(pageConfig, pageContext._pageFilesAll, pageId);
11
+ return isClientRuntimeLoaded && isClientRouting;
12
12
  }
@@ -20,6 +20,7 @@ import { getErrorPageId } from '../../shared/error-page.js';
20
20
  const globalObject = getGlobalObject('renderPageClientSide.ts', { renderCounter: 0 });
21
21
  async function renderPageClientSide(renderArgs) {
22
22
  const { scrollTarget, urlOriginal = getCurrentUrl(), overwriteLastHistoryEntry = false, isBackwardNavigation, pageContextsFromRewrite = [], redirectCount = 0, isUserLandPushStateNavigation, isClientSideNavigation = true } = renderArgs;
23
+ const { previousPageContext } = globalObject;
23
24
  const { isRenderOutdated, setHydrationCanBeAborted, isFirstRender } = getIsRenderOutdated();
24
25
  // Note that pageContext.isHydration isn't equivalent to isFirstRender
25
26
  // - Thus pageContext.isHydration isn't equivalent to !pageContext.isClientSideNavigation
@@ -41,7 +42,6 @@ async function renderPageClientSide(renderArgs) {
41
42
  return;
42
43
  // onPageTransitionStart()
43
44
  if (globalObject.isFirstRenderDone) {
44
- const { previousPageContext } = globalObject;
45
45
  assert(previousPageContext);
46
46
  // We use the hook of the previous page in order to be able to call onPageTransitionStart() before fetching the files of the next page.
47
47
  // https://github.com/vikejs/vike/issues/1560
@@ -81,23 +81,30 @@ async function renderPageClientSide(renderArgs) {
81
81
  }
82
82
  if (isRenderOutdated())
83
83
  return;
84
- let isClientRoutable;
85
84
  if (!pageContextFromRoute._pageId) {
86
- isClientRoutable = false;
87
- }
88
- else {
89
- isClientRoutable = await isClientSideRoutable(pageContextFromRoute._pageId, pageContext);
90
- if (isRenderOutdated())
91
- return;
85
+ /*
86
+ // We don't use the client router to render the 404 page:
87
+ // - So that the +redirects setting (https://vike.dev/redirects) can be applied.
88
+ // - This is the main argument.
89
+ // - See also failed CI: https://github.com/vikejs/vike/pull/1871
90
+ // - So that server-side error tracking can track 404 links?
91
+ // - We do use the client router for rendering the error page, so I don't think this is much of an argument.
92
+ await renderErrorPage({ is404: true })
93
+ */
94
+ redirectHard(urlOriginal);
95
+ return;
92
96
  }
97
+ assert(hasProp(pageContextFromRoute, '_pageId', 'string')); // Help TS
98
+ const isClientRoutable = await isClientSideRoutable(pageContextFromRoute._pageId, pageContext);
99
+ if (isRenderOutdated())
100
+ return;
93
101
  if (!isClientRoutable) {
94
102
  redirectHard(urlOriginal);
95
103
  return;
96
104
  }
97
- assert(hasProp(pageContextFromRoute, '_pageId', 'string')); // Help TS
98
105
  const isSamePage = pageContextFromRoute._pageId &&
99
- globalObject.previousPageContext?._pageId &&
100
- pageContextFromRoute._pageId === globalObject.previousPageContext._pageId;
106
+ previousPageContext?._pageId &&
107
+ pageContextFromRoute._pageId === previousPageContext._pageId;
101
108
  if (isUserLandPushStateNavigation && isSamePage) {
102
109
  // Skip's Vike's rendering; let the user handle the navigation
103
110
  return;
@@ -171,7 +178,7 @@ async function renderPageClientSide(renderArgs) {
171
178
  objectAssign(pageContext, {
172
179
  isBackwardNavigation,
173
180
  isClientSideNavigation,
174
- _previousPageContext: globalObject.previousPageContext
181
+ _previousPageContext: previousPageContext
175
182
  });
176
183
  {
177
184
  const pageContextFromAllRewrites = getPageContextFromAllRewrites(pageContextsFromRewrite);
@@ -208,9 +215,10 @@ async function renderPageClientSide(renderArgs) {
208
215
  const pageContext = await getPageContextBegin();
209
216
  if (isRenderOutdated())
210
217
  return;
211
- if (args.pageContextError) {
218
+ if (args.is404)
219
+ objectAssign(pageContext, { is404: true });
220
+ if (args.pageContextError)
212
221
  objectAssign(pageContext, args.pageContextError);
213
- }
214
222
  if ('err' in args) {
215
223
  const { err } = args;
216
224
  assert(!('errorWhileRendering' in pageContext));
@@ -266,6 +274,13 @@ async function renderPageClientSide(renderArgs) {
266
274
  objectAssign(pageContext, {
267
275
  _pageId: errorPageId
268
276
  });
277
+ const isClientRoutable = await isClientSideRoutable(pageContext._pageId, pageContext);
278
+ if (isRenderOutdated())
279
+ return;
280
+ if (!isClientRoutable) {
281
+ redirectHard(urlOriginal);
282
+ return;
283
+ }
269
284
  try {
270
285
  objectAssign(pageContext, await loadUserFilesClientSide(pageContext._pageId, pageContext._pageFilesAll, pageContext._pageConfigs));
271
286
  }
@@ -367,7 +382,6 @@ async function renderPageClientSide(renderArgs) {
367
382
  // onPageTransitionEnd()
368
383
  if (globalObject.isTransitioning) {
369
384
  globalObject.isTransitioning = undefined;
370
- const { previousPageContext } = globalObject;
371
385
  assert(previousPageContext);
372
386
  assertHook(previousPageContext, 'onPageTransitionEnd');
373
387
  const hook = getHook(previousPageContext, 'onPageTransitionEnd');
@@ -76,7 +76,11 @@ const configDefinitionsBuiltIn = {
76
76
  meta: {
77
77
  env: { config: true }
78
78
  },
79
- clientEntryLoaded: {
79
+ // Whether the page loads:
80
+ // - Vike's client runtime
81
+ // - User's client hooks
82
+ // In other words, whether the page is "HTML-only" (https://vike.dev/render-modes). HTML-only pages shouldn't load the client runtime nor client hooks.
83
+ isClientRuntimeLoaded: {
80
84
  env: { server: true, client: true },
81
85
  eager: true,
82
86
  _computed: (configValueSources) => {
@@ -22,7 +22,7 @@ type InjectFilterEntry = {
22
22
  isEntry: boolean;
23
23
  inject: PreloadFilterInject;
24
24
  };
25
- type Position = 'HTML_BEGIN' | 'HTML_END' | 'STREAM';
25
+ type Position = 'HTML_BEGIN' | 'HTML_END' | 'HTML_STREAM';
26
26
  type HtmlTag = {
27
27
  htmlTag: string | (() => string);
28
28
  position: Position;
@@ -20,7 +20,7 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
20
20
  if (asset.isEntry && asset.assetType === 'script') {
21
21
  // We could allow the user to change the position of <script> but we currently don't:
22
22
  // - Because of mergeScriptEntries()
23
- // - We would need to add STREAM to to PreloadFilterInject
23
+ // - We would need to add HTML_STREAM to to PreloadFilterInject
24
24
  // To suppor this, we should add the JavaScript entry to injectFilterEntries (with an `src` value of `null`)
25
25
  return false;
26
26
  }
@@ -77,31 +77,36 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
77
77
  // ==========
78
78
  // JavaScript
79
79
  // ==========
80
- // - The pageContext JSON should be fully sent before Vike's client runtime starts executing.
80
+ // - By default, we place the entry <script> towards the end of the HTML for better performance.
81
+ // - Performance-wise, it's more interesting to start showing the page (parse HTML and load CSS) before starting loading scripts.
82
+ // - But with HTML streaming, in order to support [Progressive Rendering](https://vike.dev/streaming#progressive-rendering), the entry <script> should be injected earlier instead.
83
+ // - The entry <script> shouldn't be `<script defer>` upon HTML streaming, otherwise progressive hydration while SSR streaming won't work.
84
+ // - `<script id="vike_pageContext" type="application/json">` (the `pageContext` JSON) should be fully sent before Vike's client runtime starts executing.
81
85
  // - Otherwise, race condition "SyntaxError: Unterminated string in JSON": https://github.com/vikejs/vike/issues/567
82
- // - <script id="vike_pageContext" type="application/json"> must appear before the entry <script> (which loads Vike's client runtime).
83
- // - <script id="vike_pageContext" type="application/json"> can't be async nor defer.
84
- // - The entry <script> can't be defer, otherwise progressive hydration while SSR streaming won't work.
85
- // - The entry <script> should be towards the end of the HTML as performance-wise it's more interesting to parse <div id="page-view"> before running the entry <script> which initiates the hydration.
86
- // - But with HTML streaming, in order to support [Progressive Rendering](https://vike.dev/streaming#progressive-rendering), the entry <script> should be injected early instead.
86
+ // - `<script id="vike_pageContext" type="application/json">` must appear before the entry <script> (which loads Vike's client runtime).
87
+ // - `<script id="vike_pageContext" type="application/json">` can't be async nor defer.
88
+ const positionJavaScriptDefault = 'HTML_END';
87
89
  const positionJavaScriptEntry = (() => {
88
90
  if (injectScriptsAt !== null) {
89
91
  if (pageContext._pageContextPromise) {
90
92
  assertWarning(injectScriptsAt === 'HTML_END' || !isStream, `You're setting injectScriptsAt to ${pc.code(JSON.stringify(injectScriptsAt))} while using HTML streaming with a pageContext promise (https://vike.dev/streaming#initial-data-after-stream-end) which is contradictory: the pageContext promise is skipped.`, { onlyOnce: true });
91
93
  }
94
+ if (injectScriptsAt === 'HTML_STREAM' && !isStream) {
95
+ return positionJavaScriptDefault;
96
+ }
92
97
  return injectScriptsAt;
93
98
  }
94
99
  if (pageContext._pageContextPromise) {
95
100
  // - If there is a pageContext._pageContextPromise then <script id="vike_pageContext" type="application/json"> needs to await for it.
96
101
  // - pageContext._pageContextPromise is typically resolved only after the page's components are rendered and the stream ended.
97
102
  // - https://vike.dev/streaming#initial-data-after-stream-end
98
- return 'HTML_END';
103
+ return positionJavaScriptDefault;
99
104
  }
100
105
  if (streamFromReactStreamingPackage && !streamFromReactStreamingPackage.hasStreamEnded()) {
101
106
  // If there is a stream then, in order to support progressive hydration, inject the JavaScript during the stream after React(/Vue/Solid/...) resolved the first suspense boundary.
102
- return 'STREAM';
107
+ return 'HTML_STREAM';
103
108
  }
104
- return 'HTML_END';
109
+ return positionJavaScriptDefault;
105
110
  })();
106
111
  if (pageContext._pageContextPromise && streamFromReactStreamingPackage) {
107
112
  // - Should we show this warning for Solid as well? Solid seems to also support progressive rendering.
@@ -135,7 +140,7 @@ function getHtmlTags(pageContext, streamFromReactStreamingPackage, injectFilter,
135
140
  const htmlTag = inferPreloadTag(asset);
136
141
  if (!asset.inject)
137
142
  return;
138
- // Ideally, instead of this conditional ternary operator, we should add STREAM to PreloadFilterInject (or a better fitting name such as HTML_STREAM)
143
+ // Ideally, instead of this conditional ternary operator, we should add HTML_STREAM to PreloadFilterInject
139
144
  const position = asset.inject === 'HTML_END' ? positionJavaScriptEntry : asset.inject;
140
145
  htmlTags.push({ htmlTag, position });
141
146
  });
@@ -217,6 +222,6 @@ function getInjectScriptsAt(pageId, pageConfigs) {
217
222
  assertUsage(injectScriptsAt === null ||
218
223
  injectScriptsAt === 'HTML_BEGIN' ||
219
224
  injectScriptsAt === 'HTML_END' ||
220
- injectScriptsAt === 'STREAM', `${configDefinedAt} has an invalid value`);
225
+ injectScriptsAt === 'HTML_STREAM', `${configDefinedAt} has an invalid value`);
221
226
  return injectScriptsAt;
222
227
  }
@@ -16,7 +16,7 @@ function injectHtmlTags(htmlString, htmlTags, position) {
16
16
  }
17
17
  // Is it worth it? Should we remove this? https://github.com/vikejs/vike/pull/1740#issuecomment-2230540892
18
18
  function injectHtmlTagsUsingStream(htmlTags, streamFromReactStreamingPackage) {
19
- const htmlFragment = joinHtmlTags(htmlTags.filter((h) => h.position === 'STREAM'));
19
+ const htmlFragment = joinHtmlTags(htmlTags.filter((h) => h.position === 'HTML_STREAM'));
20
20
  if (htmlFragment) {
21
21
  assert(!streamFromReactStreamingPackage.hasStreamEnded());
22
22
  streamFromReactStreamingPackage.injectToStream(htmlFragment, { flush: true });
@@ -12,7 +12,7 @@ async function injectHtmlTagsToString(htmlParts, pageContext, injectFilter) {
12
12
  let htmlString = htmlPartsToString(htmlParts, pageAssets);
13
13
  htmlString = injectToHtmlBegin(htmlString, htmlTags);
14
14
  htmlString = injectToHtmlEnd(htmlString, htmlTags);
15
- assert(htmlTags.filter((snippet) => snippet.position === 'STREAM').length === 0);
15
+ assert(htmlTags.filter((snippet) => snippet.position === 'HTML_STREAM').length === 0);
16
16
  return htmlString;
17
17
  }
18
18
  function injectHtmlTagsToStream(pageContext, streamFromReactStreamingPackage, injectFilter) {
@@ -39,7 +39,7 @@ function injectHtmlTagsToStream(pageContext, streamFromReactStreamingPackage, in
39
39
  if (streamFromReactStreamingPackage)
40
40
  return null;
41
41
  assert(htmlTags);
42
- const tags = htmlTags.filter((h) => h.position === 'STREAM');
42
+ const tags = htmlTags.filter((h) => h.position === 'HTML_STREAM');
43
43
  if (tags.length === 0)
44
44
  return null;
45
45
  const htmlFragment = joinHtmlTags(tags);
@@ -7,17 +7,17 @@ import { getGlobalContext } from '../globalContext.js';
7
7
  import { getConfigValueRuntime } from '../../../shared/page-configs/getConfigValue.js';
8
8
  function analyzePage(pageFilesAll, pageConfig, pageId) {
9
9
  if (pageConfig) {
10
- const { clientEntryLoaded, isClientRouting } = analyzeClientSide(pageConfig, pageFilesAll, pageId);
10
+ const { isClientRuntimeLoaded, isClientRouting } = analyzeClientSide(pageConfig, pageFilesAll, pageId);
11
11
  const clientEntries = [];
12
12
  const clientFilePath = getConfigValueRuntime(pageConfig, 'client', 'string')?.value ?? null;
13
13
  if (clientFilePath)
14
14
  clientEntries.push(clientFilePath);
15
- if (clientEntryLoaded)
15
+ if (isClientRuntimeLoaded)
16
16
  clientEntries.push(getVikeClientEntry(isClientRouting));
17
17
  const clientDependencies = [];
18
18
  clientDependencies.push({
19
19
  id: getVirtualFileIdPageConfigValuesAll(pageConfig.pageId, true),
20
- onlyAssets: clientEntryLoaded ? false : true,
20
+ onlyAssets: isClientRuntimeLoaded ? false : true,
21
21
  eagerlyImported: false
22
22
  });
23
23
  // In production we inject the import of the server virtual module with ?extractAssets inside the client virtual module
@@ -53,7 +53,7 @@ function analyzePage(pageFilesAll, pageConfig, pageId) {
53
53
  });
54
54
  });
55
55
  return {
56
- isHtmlOnly: !clientEntryLoaded,
56
+ isHtmlOnly: !isClientRuntimeLoaded,
57
57
  isClientRouting,
58
58
  clientEntries,
59
59
  clientDependencies,
@@ -1,4 +1,4 @@
1
- export { createHttpResponse };
1
+ export { createHttpResponsePage };
2
2
  export { createHttpResponsePageContextJson };
3
3
  export { createHttpResponseError };
4
4
  export { createHttpResponseRedirect };
@@ -11,6 +11,7 @@ import type { RenderHook } from './executeOnRenderHtmlHook.js';
11
11
  import type { RedirectStatusCode, AbortStatusCode, UrlRedirect } from '../../../shared/route/abort.js';
12
12
  import { HttpResponseBody } from './getHttpResponseBody.js';
13
13
  import { type EarlyHint } from './getEarlyHints.js';
14
+ import type { PageFile } from '../../../shared/getPageFiles.js';
14
15
  type HttpResponse = {
15
16
  statusCode: 200 | 404 | 500 | RedirectStatusCode | AbortStatusCode;
16
17
  headers: [string, string][];
@@ -18,7 +19,7 @@ type HttpResponse = {
18
19
  /** **Deprecated**: use `headers` instead, see https://vike.dev/migration/0.4.134 */
19
20
  contentType: 'application/json' | 'text/html;charset=utf-8';
20
21
  } & HttpResponseBody;
21
- declare function createHttpResponse(htmlRender: HtmlRender, renderHook: null | RenderHook, pageContext: {
22
+ declare function createHttpResponsePage(htmlRender: HtmlRender, renderHook: null | RenderHook, pageContext: {
22
23
  _pageId: null | string;
23
24
  is404: null | boolean;
24
25
  errorWhileRendering: null | Error;
@@ -27,6 +28,9 @@ declare function createHttpResponse(htmlRender: HtmlRender, renderHook: null | R
27
28
  abortStatusCode?: AbortStatusCode;
28
29
  }): Promise<HttpResponse>;
29
30
  declare function createHttpResponseFavicon404(): HttpResponse;
30
- declare function createHttpResponseError(): HttpResponse;
31
+ declare function createHttpResponseError(pageContext: null | {
32
+ _pageFilesAll: PageFile[];
33
+ _pageConfigs: PageConfigRuntime[];
34
+ }): HttpResponse;
31
35
  declare function createHttpResponsePageContextJson(pageContextSerialized: string): Promise<HttpResponse>;
32
36
  declare function createHttpResponseRedirect({ url, statusCode }: UrlRedirect, urlLogical: string): HttpResponse;
@@ -1,15 +1,15 @@
1
- export { createHttpResponse };
1
+ export { createHttpResponsePage };
2
2
  export { createHttpResponsePageContextJson };
3
3
  export { createHttpResponseError };
4
4
  export { createHttpResponseRedirect };
5
5
  export { createHttpResponseFavicon404 };
6
6
  import { assert, assertWarning } from '../utils.js';
7
- import { isErrorPage } from '../../../shared/error-page.js';
7
+ import { getErrorPageId, isErrorPage } from '../../../shared/error-page.js';
8
8
  import { getHttpResponseBody, getHttpResponseBodyStreamHandlers } from './getHttpResponseBody.js';
9
9
  import { getEarlyHints } from './getEarlyHints.js';
10
- import { getCacheControl } from './createHttpResponseObject/getCacheControl.js';
11
- import { assertNoInfiniteHttpRedirect } from './createHttpResponseObject/assertNoInfiniteHttpRedirect.js';
12
- async function createHttpResponse(htmlRender, renderHook, pageContext) {
10
+ import { getCacheControl } from './createHttpResponse/getCacheControl.js';
11
+ import { assertNoInfiniteHttpRedirect } from './createHttpResponse/assertNoInfiniteHttpRedirect.js';
12
+ async function createHttpResponsePage(htmlRender, renderHook, pageContext) {
13
13
  let statusCode = pageContext.abortStatusCode;
14
14
  if (!statusCode) {
15
15
  const isError = !pageContext._pageId || isErrorPage(pageContext._pageId, pageContext._pageConfigs);
@@ -32,18 +32,30 @@ async function createHttpResponse(htmlRender, renderHook, pageContext) {
32
32
  if (cacheControl) {
33
33
  headers.push(['Cache-Control', cacheControl]);
34
34
  }
35
- return getHttpResponse(statusCode, 'text/html;charset=utf-8', headers, htmlRender, earlyHints, renderHook);
35
+ return createHttpResponse(statusCode, 'text/html;charset=utf-8', headers, htmlRender, earlyHints, renderHook);
36
36
  }
37
37
  function createHttpResponseFavicon404() {
38
- const httpResponse = getHttpResponse(404, 'text/html;charset=utf-8', [], "<p>No favicon.ico found.</p><script>console.log('This HTTP response was generated by Vike.')</script>");
38
+ const httpResponse = createHttpResponse(404, 'text/html;charset=utf-8', [], "<p>No favicon.ico found.</p><script>console.log('This HTTP response was generated by Vike.')</script>");
39
39
  return httpResponse;
40
40
  }
41
- function createHttpResponseError() {
42
- const httpResponse = getHttpResponse(500, 'text/html;charset=utf-8', [], "<p>An error occurred.</p><script>console.log('This HTTP response was generated by Vike. This response is used instead of rendering the error page (https://vike.dev/error-page), either because there isn't error page or because an error occurred while rendering the error page.')</script>");
41
+ function createHttpResponseError(pageContext) {
42
+ const reason = (() => {
43
+ if (!pageContext) {
44
+ return 'no error page (https://vike.dev/error-page) could be rendered';
45
+ }
46
+ const errorPageId = getErrorPageId(pageContext._pageFilesAll, pageContext._pageConfigs);
47
+ if (errorPageId) {
48
+ return "the error page (https://vike.dev/error-page) couldn't be rendered (for example if an error occurred while rendering the error page)";
49
+ }
50
+ else {
51
+ return 'no error page (https://vike.dev/error-page) is defined, make sure to create one';
52
+ }
53
+ })();
54
+ const httpResponse = createHttpResponse(500, 'text/html;charset=utf-8', [], `<p>An error occurred.</p><script>console.log(${JSON.stringify(`This HTTP response was generated by Vike. Vike returned this response because ${reason}.`)})</script>`);
43
55
  return httpResponse;
44
56
  }
45
57
  async function createHttpResponsePageContextJson(pageContextSerialized) {
46
- const httpResponse = getHttpResponse(200, 'application/json', [], pageContextSerialized, [], null);
58
+ const httpResponse = createHttpResponse(200, 'application/json', [], pageContextSerialized, [], null);
47
59
  return httpResponse;
48
60
  }
49
61
  function createHttpResponseRedirect({ url, statusCode },
@@ -54,12 +66,12 @@ urlLogical) {
54
66
  assert(statusCode);
55
67
  assert(300 <= statusCode && statusCode <= 399);
56
68
  const headers = [['Location', url]];
57
- return getHttpResponse(statusCode, 'text/html;charset=utf-8', headers,
69
+ return createHttpResponse(statusCode, 'text/html;charset=utf-8', headers,
58
70
  // For bots / programmatic crawlig: show what's going on.
59
71
  // For users: showing a blank page is probably better than a flickering text.
60
72
  `<p style="display: none">Redirecting to ${url}</p><script>console.log('This HTTP response was generated by Vike.')</script>`);
61
73
  }
62
- function getHttpResponse(statusCode, contentType, headers, htmlRender, earlyHints = [], renderHook = null) {
74
+ function createHttpResponse(statusCode, contentType, headers, htmlRender, earlyHints = [], renderHook = null) {
63
75
  headers.push(['Content-Type', contentType]);
64
76
  assert(renderHook || typeof htmlRender === 'string');
65
77
  return {
@@ -1,11 +1,13 @@
1
1
  export { handleErrorWithoutErrorPage };
2
2
  import type { PageContextAfterRender } from './renderPageAlreadyRouted.js';
3
3
  import type { PageConfigRuntime } from '../../../shared/page-configs/PageConfig.js';
4
+ import type { PageFile } from '../../../shared/getPageFiles.js';
4
5
  declare function handleErrorWithoutErrorPage<PageContext extends {
5
6
  isClientSideNavigation: boolean;
6
7
  errorWhileRendering: null | Error;
7
8
  is404: null | boolean;
8
9
  _pageId: null;
10
+ _pageFilesAll: PageFile[];
9
11
  _pageConfigs: PageConfigRuntime[];
10
12
  urlOriginal: string;
11
13
  }>(pageContext: PageContext): Promise<PageContext & PageContextAfterRender>;
@@ -2,7 +2,7 @@ export { handleErrorWithoutErrorPage };
2
2
  import { stringify } from '@brillout/json-serializer/stringify';
3
3
  import { getGlobalContext } from '../globalContext.js';
4
4
  import { assert, assertWarning, objectAssign } from '../utils.js';
5
- import { createHttpResponse, createHttpResponseError } from './createHttpResponse.js';
5
+ import { createHttpResponsePage, createHttpResponseError } from './createHttpResponse.js';
6
6
  import pc from '@brillout/picocolors';
7
7
  // When the user hasn't defined _error.page.js
8
8
  async function handleErrorWithoutErrorPage(pageContext) {
@@ -13,14 +13,14 @@ async function handleErrorWithoutErrorPage(pageContext) {
13
13
  warnMissingErrorPage(isV1);
14
14
  }
15
15
  if (!pageContext.isClientSideNavigation) {
16
- const httpResponse = createHttpResponseError();
16
+ const httpResponse = createHttpResponseError(pageContext);
17
17
  objectAssign(pageContext, { httpResponse });
18
18
  return pageContext;
19
19
  }
20
20
  else {
21
21
  const __getPageAssets = async () => [];
22
22
  objectAssign(pageContext, { __getPageAssets });
23
- const httpResponse = await createHttpResponse(stringify({ serverSideError: true }), null, pageContext);
23
+ const httpResponse = await createHttpResponsePage(stringify({ serverSideError: true }), null, pageContext);
24
24
  objectAssign(pageContext, { httpResponse });
25
25
  return pageContext;
26
26
  }
@@ -10,7 +10,7 @@ import { assert, assertUsage, assertWarning, hasProp, normalizeHeaders, objectAs
10
10
  import { serializePageContextClientSide } from '../html/serializePageContextClientSide.js';
11
11
  import { getPageContextUrlComputed } from '../../../shared/getPageContextUrlComputed.js';
12
12
  import { getGlobalContext } from '../globalContext.js';
13
- import { createHttpResponse, createHttpResponsePageContextJson } from './createHttpResponse.js';
13
+ import { createHttpResponsePage, createHttpResponsePageContextJson } from './createHttpResponse.js';
14
14
  import { loadUserFilesServerSide } from './loadUserFilesServerSide.js';
15
15
  import { executeOnRenderHtmlHook } from './executeOnRenderHtmlHook.js';
16
16
  import { executeOnBeforeRenderAndDataHooks } from './executeOnBeforeRenderAndDataHooks.js';
@@ -57,7 +57,7 @@ async function renderPageAlreadyRouted(pageContext) {
57
57
  }
58
58
  const renderHookResult = await executeOnRenderHtmlHook(pageContext);
59
59
  const { htmlRender, renderHook } = renderHookResult;
60
- const httpResponse = await createHttpResponse(htmlRender, renderHook, pageContext);
60
+ const httpResponse = await createHttpResponsePage(htmlRender, renderHook, pageContext);
61
61
  objectAssign(pageContext, { httpResponse });
62
62
  return pageContext;
63
63
  }
@@ -50,7 +50,7 @@ async function renderPageAndPrepare(pageContextInit, httpRequestId) {
50
50
  // Invalid config
51
51
  const handleInvalidConfig = (err) => {
52
52
  logRuntimeInfo?.(pc.bold(pc.red('Error while loading a Vike config file, see error above.')), httpRequestId, 'error');
53
- const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit);
53
+ const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit, null);
54
54
  return pageContextWithError;
55
55
  };
56
56
  if (isConfigInvalid) {
@@ -70,7 +70,7 @@ async function renderPageAndPrepare(pageContextInit, httpRequestId) {
70
70
  // initGlobalContext_renderPage() and getRenderContext() don't call any user hooks => err isn't thrown from user code.
71
71
  assert(!isAbortError(err));
72
72
  logRuntimeError(err, httpRequestId);
73
- const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit);
73
+ const pageContextWithError = getPageContextHttpResponseError(err, pageContextInit, null);
74
74
  return pageContextWithError;
75
75
  }
76
76
  if (isConfigInvalid) {
@@ -176,7 +176,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
176
176
  if (!handled.pageContextReturn) {
177
177
  const pageContextAbort = errErrorPage._pageContextAbort;
178
178
  assertWarning(false, `Failed to render error page because ${pc.cyan(pageContextAbort._abortCall)} was called: make sure ${pc.cyan(pageContextAbort._abortCaller)} doesn't occur while the error page is being rendered.`, { onlyOnce: false });
179
- const pageContextHttpWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit);
179
+ const pageContextHttpWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit, pageContextErrorPageInit);
180
180
  return pageContextHttpWithError;
181
181
  }
182
182
  // `throw redirect()` / `throw render(url)`
@@ -185,7 +185,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
185
185
  if (isNewError(errErrorPage, errNominalPage)) {
186
186
  logRuntimeError(errErrorPage, httpRequestId);
187
187
  }
188
- const pageContextWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit);
188
+ const pageContextWithError = getPageContextHttpResponseError(errNominalPage, pageContextInit, pageContextErrorPageInit);
189
189
  return pageContextWithError;
190
190
  }
191
191
  return pageContextErrorPage;
@@ -236,9 +236,12 @@ function logHttpResponse(urlOriginalPretty, httpRequestId, pageContextReturn) {
236
236
  }
237
237
  logRuntimeInfo?.(msg, httpRequestId, isNominal ? 'info' : 'error');
238
238
  }
239
- function getPageContextHttpResponseError(err, pageContextInit) {
239
+ function prettyUrl(url) {
240
+ return pc.bold(decodeURI(url));
241
+ }
242
+ function getPageContextHttpResponseError(err, pageContextInit, pageContext) {
240
243
  const pageContextWithError = createPageContext(pageContextInit);
241
- const httpResponse = createHttpResponseError();
244
+ const httpResponse = createHttpResponseError(pageContext);
242
245
  objectAssign(pageContextWithError, {
243
246
  httpResponse,
244
247
  errorWhileRendering: err
@@ -278,6 +281,7 @@ async function renderPageNominal(pageContext) {
278
281
  }
279
282
  }
280
283
  assert(hasProp(pageContext, '_pageId', 'string'));
284
+ assert(pageContext.errorWhileRendering === null);
281
285
  // Render
282
286
  const pageContextAfterRender = await renderPageAlreadyRouted(pageContext);
283
287
  assert(pageContext === pageContextAfterRender);
@@ -440,8 +444,5 @@ function assertBaseUrl(pageContextInit) {
440
444
  const { urlOriginal } = pageContextInit;
441
445
  const { urlWithoutPageContextRequestSuffix } = handlePageContextRequestUrl(urlOriginal);
442
446
  const { hasBaseServer } = parseUrl(urlWithoutPageContextRequestSuffix, baseServer);
443
- assertUsage(hasBaseServer, `${pc.code('renderPage(pageContextInit)')} (https://vike.dev/renderPage) called with ${pc.code(`pageContextInit.urlOriginal===${JSON.stringify(urlOriginal)}`)} which doesn't start with Base URL ${prettyUrl(baseServer)} (https://vike.dev/base-url)`);
444
- }
445
- function prettyUrl(url) {
446
- return pc.code(decodeURI(url));
447
+ assertUsage(hasBaseServer, `${pc.code('renderPage(pageContextInit)')} (https://vike.dev/renderPage) called with ${pc.code(`pageContextInit.urlOriginal===${JSON.stringify(urlOriginal)}`)} which doesn't start with Base URL ${pc.code(baseServer)} (https://vike.dev/base-url)`);
447
448
  }
@@ -2,6 +2,6 @@ export { analyzeClientSide };
2
2
  import type { PageConfigRuntime } from '../page-configs/PageConfig.js';
3
3
  import type { PageFile } from './getPageFileObject.js';
4
4
  declare function analyzeClientSide(pageConfig: PageConfigRuntime | null, pageFilesAll: PageFile[], pageId: string): {
5
- clientEntryLoaded: boolean;
5
+ isClientRuntimeLoaded: boolean;
6
6
  isClientRouting: boolean;
7
7
  };
@@ -5,13 +5,13 @@ function analyzeClientSide(pageConfig, pageFilesAll, pageId) {
5
5
  // V1 design
6
6
  if (pageConfig) {
7
7
  const isClientRouting = getConfigValueRuntime(pageConfig, 'clientRouting', 'boolean')?.value ?? false;
8
- const clientEntryLoaded = getConfigValueRuntime(pageConfig, 'clientEntryLoaded', 'boolean')?.value ?? false;
9
- return { clientEntryLoaded, isClientRouting };
8
+ const isClientRuntimeLoaded = getConfigValueRuntime(pageConfig, 'isClientRuntimeLoaded', 'boolean')?.value ?? false;
9
+ return { isClientRuntimeLoaded, isClientRouting };
10
10
  }
11
11
  else {
12
12
  // TODO/v1-release: remove
13
13
  // V0.4 design
14
14
  const { isHtmlOnly, isClientRouting } = analyzePageClientSide(pageFilesAll, pageId);
15
- return { clientEntryLoaded: !isHtmlOnly, isClientRouting };
15
+ return { isClientRuntimeLoaded: !isHtmlOnly, isClientRouting };
16
16
  }
17
17
  }
@@ -41,7 +41,7 @@ type HookName = HookNamePage | HookNameGlobal | HookNameOldDesign;
41
41
  type HookNamePage = 'onHydrationEnd' | 'onBeforePrerenderStart' | 'onBeforeRender' | 'onPageTransitionStart' | 'onPageTransitionEnd' | 'onRenderHtml' | 'onRenderClient' | 'guard' | 'data';
42
42
  type HookNameGlobal = 'onBeforePrerender' | 'onBeforeRoute' | 'onPrerenderStart';
43
43
  type HookNameOldDesign = 'render' | 'prerender';
44
- type ConfigNameBuiltIn = Exclude<keyof Config, keyof ConfigVikeUserProvided | 'onBeforeRoute' | 'onPrerenderStart'> | 'prerender' | 'clientEntryLoaded' | 'onBeforeRenderEnv' | 'dataEnv' | 'hooksTimeout' | 'clientHooks';
44
+ type ConfigNameBuiltIn = Exclude<keyof Config, keyof ConfigVikeUserProvided | 'onBeforeRoute' | 'onPrerenderStart'> | 'prerender' | 'isClientRuntimeLoaded' | 'onBeforeRenderEnv' | 'dataEnv' | 'hooksTimeout' | 'clientHooks';
45
45
  type Config = ConfigBuiltIn & Vike.Config & (VikePackages.ConfigVikeReact | VikePackages.ConfigVikeVue | VikePackages.ConfigVikeSolid | VikePackages.ConfigVikeSvelte | VikePackages.ConfigVikeAngular);
46
46
  /** Hook for fetching data.
47
47
  *
@@ -358,7 +358,7 @@ type ConfigBuiltIn = {
358
358
  *
359
359
  * https://vike.dev/injectScriptsAt
360
360
  */
361
- injectScriptsAt?: 'HTML_BEGIN' | 'HTML_END' | 'STREAM' | null;
361
+ injectScriptsAt?: 'HTML_BEGIN' | 'HTML_END' | 'HTML_STREAM' | null;
362
362
  /** Used by Vike extensions to set their name.
363
363
  *
364
364
  * https://vike.dev/extends
@@ -66,7 +66,7 @@ async function getPageContextFromHook(onBeforeRouteHook, pageContext) {
66
66
  }
67
67
  if (hasProp(hookReturn.pageContext, 'urlLogical')) {
68
68
  assertUsageUrlPathnameAbsolute(
69
- // We type-cast to string instead of assertUsage() in order to save client-side KBs
69
+ // We skip validation and type-cast instead of assertUsage() in order to save client-side KBs
70
70
  hookReturn.pageContext.urlLogical, `${errPrefix} returned ${pc.cyan('{ pageContext: { urlLogical } }')} but ${pc.cyan('urlLogical')}`);
71
71
  }
72
72
  assertPageContextProvidedByUser(hookReturn.pageContext, {
@@ -1 +1 @@
1
- export declare const PROJECT_VERSION: "0.4.194";
1
+ export declare const PROJECT_VERSION: "0.4.195-commit-486b49a";
@@ -1,2 +1,2 @@
1
1
  // Automatically updated by @brillout/release-me
2
- export const PROJECT_VERSION = '0.4.194';
2
+ export const PROJECT_VERSION = '0.4.195-commit-486b49a';
@@ -1,4 +1,4 @@
1
1
  export declare const projectInfo: {
2
2
  projectName: "Vike";
3
- projectVersion: "0.4.194";
3
+ projectVersion: "0.4.195-commit-486b49a";
4
4
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vike",
3
- "version": "0.4.194",
3
+ "version": "0.4.195-commit-486b49a",
4
4
  "repository": "https://github.com/vikejs/vike",
5
5
  "exports": {
6
6
  "./server": {
@@ -123,7 +123,7 @@
123
123
  "dependencies": {
124
124
  "@brillout/import": "^0.2.3",
125
125
  "@brillout/json-serializer": "^0.5.13",
126
- "@brillout/picocolors": "^1.0.14",
126
+ "@brillout/picocolors": "^1.0.15",
127
127
  "@brillout/require-shim": "^0.1.2",
128
128
  "@brillout/vite-plugin-server-entry": "^0.4.11",
129
129
  "acorn": "^8.0.0",
@@ -225,11 +225,12 @@
225
225
  ],
226
226
  "devDependencies": {
227
227
  "@biomejs/biome": "^1.5.3",
228
- "@brillout/release-me": "^0.4.0",
228
+ "@brillout/release-me": "^0.4.2",
229
229
  "@types/estree": "^1.0.5",
230
230
  "@types/jest": "^29.5.11",
231
231
  "@types/node": "^20.10.5",
232
232
  "@types/resolve": "^1.20.6",
233
+ "@types/semver": "^7.5.8",
233
234
  "@types/source-map-support": "^0.5.10",
234
235
  "acorn": "^8.11.2",
235
236
  "cac": "^6.7.14",
@@ -255,4 +256,4 @@
255
256
  "release:minor": "release-me minor",
256
257
  "release:commit": "release-me commit"
257
258
  }
258
- }
259
+ }