@cedarjs/prerender 7.0.0-rc.128 → 8.0.0-canary.3263

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 (72) hide show
  1. package/dist/browserUtils/index.d.ts +1 -1
  2. package/dist/browserUtils/index.d.ts.map +1 -1
  3. package/dist/build-and-import/buildAndImport.d.ts +1 -1
  4. package/dist/build-and-import/buildAndImport.d.ts.map +1 -1
  5. package/dist/build-and-import/buildAndImport.js +2 -9
  6. package/dist/build-and-import/rollupPlugins/rollup-plugin-cedarjs-routes-auto-loader.d.ts.map +1 -1
  7. package/dist/graphql/graphql.d.ts +17 -2
  8. package/dist/graphql/graphql.d.ts.map +1 -1
  9. package/dist/{cjs/index.d.ts.map → index.d.ts.map} +1 -1
  10. package/dist/index.js +1 -0
  11. package/dist/runPrerender.d.ts.map +1 -0
  12. package/dist/{runPrerenderEsm.js → runPrerender.js} +65 -56
  13. package/package.json +20 -51
  14. package/dist/babelPlugins/babel-plugin-redwood-cell.d.ts +0 -5
  15. package/dist/babelPlugins/babel-plugin-redwood-cell.d.ts.map +0 -1
  16. package/dist/babelPlugins/babel-plugin-redwood-cell.js +0 -98
  17. package/dist/babelPlugins/babel-plugin-redwood-prerender-media-imports.d.ts +0 -5
  18. package/dist/babelPlugins/babel-plugin-redwood-prerender-media-imports.d.ts.map +0 -1
  19. package/dist/babelPlugins/babel-plugin-redwood-prerender-media-imports.js +0 -77
  20. package/dist/babelPlugins/utils.d.ts +0 -2
  21. package/dist/babelPlugins/utils.d.ts.map +0 -1
  22. package/dist/babelPlugins/utils.js +0 -15
  23. package/dist/cjs/apolloState.d.ts +0 -13
  24. package/dist/cjs/apolloState.d.ts.map +0 -1
  25. package/dist/cjs/apolloState.js +0 -30
  26. package/dist/cjs/babelPlugins/babel-plugin-redwood-cell.d.ts +0 -5
  27. package/dist/cjs/babelPlugins/babel-plugin-redwood-cell.d.ts.map +0 -1
  28. package/dist/cjs/babelPlugins/babel-plugin-redwood-cell.js +0 -122
  29. package/dist/cjs/babelPlugins/babel-plugin-redwood-prerender-media-imports.d.ts +0 -5
  30. package/dist/cjs/babelPlugins/babel-plugin-redwood-prerender-media-imports.d.ts.map +0 -1
  31. package/dist/cjs/babelPlugins/babel-plugin-redwood-prerender-media-imports.js +0 -101
  32. package/dist/cjs/babelPlugins/utils.d.ts +0 -2
  33. package/dist/cjs/babelPlugins/utils.d.ts.map +0 -1
  34. package/dist/cjs/babelPlugins/utils.js +0 -49
  35. package/dist/cjs/browserUtils/index.d.ts +0 -8
  36. package/dist/cjs/browserUtils/index.d.ts.map +0 -1
  37. package/dist/cjs/browserUtils/index.js +0 -47
  38. package/dist/cjs/build-and-import/buildAndImport.js +0 -193
  39. package/dist/cjs/build-and-import/load-tsconfig.d.js +0 -1
  40. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedar-remove-dev-fatal-error-page.js +0 -53
  41. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-cell.js +0 -184
  42. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-directory-named-imports.js +0 -83
  43. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-external.js +0 -125
  44. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-ignore-html-and-css-imports.js +0 -48
  45. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-inject-file-globals.js +0 -66
  46. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-prerender-media-imports.js +0 -118
  47. package/dist/cjs/build-and-import/rollupPlugins/rollup-plugin-cedarjs-routes-auto-loader.js +0 -146
  48. package/dist/cjs/build-and-import/rollupPlugins/utils.js +0 -78
  49. package/dist/cjs/build-and-import/utils.js +0 -68
  50. package/dist/cjs/detection/detection.d.ts +0 -11
  51. package/dist/cjs/detection/detection.d.ts.map +0 -1
  52. package/dist/cjs/detection/detection.js +0 -46
  53. package/dist/cjs/errors.d.ts +0 -19
  54. package/dist/cjs/errors.d.ts.map +0 -1
  55. package/dist/cjs/errors.js +0 -52
  56. package/dist/cjs/graphql/graphql.d.ts +0 -19
  57. package/dist/cjs/graphql/graphql.d.ts.map +0 -1
  58. package/dist/cjs/graphql/graphql.js +0 -152
  59. package/dist/cjs/graphql/node-runner.js +0 -97
  60. package/dist/cjs/graphql/vite-plugin-cedar-auto-import.js +0 -107
  61. package/dist/cjs/index.js +0 -22
  62. package/dist/cjs/internal.d.ts +0 -28
  63. package/dist/cjs/internal.d.ts.map +0 -1
  64. package/dist/cjs/internal.js +0 -135
  65. package/dist/cjs/package.json +0 -1
  66. package/dist/cjs/runPrerender.d.ts.map +0 -1
  67. package/dist/cjs/runPrerender.js +0 -311
  68. package/dist/cjs/runPrerenderEsm.js +0 -308
  69. package/dist/runPrerenderEsm.d.ts +0 -9
  70. package/dist/runPrerenderEsm.d.ts.map +0 -1
  71. /package/dist/{cjs/index.d.ts → index.d.ts} +0 -0
  72. /package/dist/{cjs/runPrerender.d.ts → runPrerender.d.ts} +0 -0
@@ -1,311 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var runPrerender_exports = {};
30
- __export(runPrerender_exports, {
31
- runPrerender: () => runPrerender,
32
- writePrerenderedHtmlFile: () => writePrerenderedHtmlFile
33
- });
34
- module.exports = __toCommonJS(runPrerender_exports);
35
- var import_node_fs = __toESM(require("node:fs"), 1);
36
- var import_node_path = __toESM(require("node:path"), 1);
37
- var import_react = __toESM(require("react"), 1);
38
- var apolloClient = __toESM(require("@apollo/client"), 1);
39
- var import_cheerio = require("cheerio");
40
- var import_server = __toESM(require("react-dom/server"), 1);
41
- var import_babel_config = require("@cedarjs/babel-config");
42
- var import_project_config = require("@cedarjs/project-config");
43
- var import_apolloState = require("./apolloState.js");
44
- var import_babel_plugin_redwood_cell = require("./babelPlugins/babel-plugin-redwood-cell.js");
45
- var import_babel_plugin_redwood_prerender_media_imports = require("./babelPlugins/babel-plugin-redwood-prerender-media-imports.js");
46
- var import_detection = require("./detection/detection.js");
47
- var import_errors = require("./errors.js");
48
- var import_graphql = require("./graphql/graphql.js");
49
- var import_internal = require("./internal.js");
50
- const { ApolloClient, InMemoryCache } = apolloClient.default || apolloClient;
51
- const prerenderApolloClient = new ApolloClient({ cache: new InMemoryCache() });
52
- async function recursivelyRender(App, Routes, renderPath, fileImporter, gqlHandler, queryCache) {
53
- const { CellCacheContextProvider, getOperationName } = require("@cedarjs/web");
54
- const { LocationProvider } = require("@cedarjs/router");
55
- let shouldShowGraphqlHandlerNotFoundWarn = false;
56
- await Promise.all(
57
- Object.entries(queryCache).map(async ([cacheKey, value]) => {
58
- if (value.hasProcessed) {
59
- return Promise.resolve("");
60
- }
61
- try {
62
- const resultString = await (0, import_graphql.executeQuery)(
63
- fileImporter,
64
- gqlHandler,
65
- value.query,
66
- value.variables
67
- );
68
- let result;
69
- try {
70
- result = JSON.parse(resultString);
71
- } catch (e) {
72
- if (e instanceof SyntaxError) {
73
- throw new import_errors.JSONParseError({
74
- query: value.query,
75
- variables: value.variables,
76
- result: resultString
77
- });
78
- }
79
- }
80
- if (result.errors) {
81
- const message = result.errors[0].message ?? JSON.stringify(result.errors, null, 4);
82
- if (result.errors[0]?.extensions?.code === "UNAUTHENTICATED") {
83
- const queryName = getOperationName(value.query);
84
- console.error(
85
- `
86
-
87
- \u{1F6D1} Cannot prerender the query ${queryName} as it requires auth.
88
- `
89
- );
90
- }
91
- throw new import_errors.PrerenderGqlError(message);
92
- }
93
- queryCache[cacheKey] = {
94
- ...value,
95
- data: result.data,
96
- hasProcessed: true
97
- };
98
- return result;
99
- } catch (e) {
100
- if (e instanceof import_errors.GqlHandlerImportError) {
101
- shouldShowGraphqlHandlerNotFoundWarn = true;
102
- queryCache[cacheKey] = {
103
- ...value,
104
- // tried to fetch, but failed
105
- renderLoading: true,
106
- hasProcessed: true
107
- };
108
- return;
109
- } else {
110
- throw e;
111
- }
112
- }
113
- })
114
- );
115
- const prerenderUrl = process.env.RWJS_PRERENDER_ORIGIN || "http://localhost" + renderPath;
116
- const componentAsHtml = import_server.default.renderToString(
117
- /* @__PURE__ */ import_react.default.createElement(LocationProvider, { location: new URL(prerenderUrl) }, /* @__PURE__ */ import_react.default.createElement(CellCacheContextProvider, { queryCache }, /* @__PURE__ */ import_react.default.createElement(App, null, /* @__PURE__ */ import_react.default.createElement(Routes, null))))
118
- );
119
- if (Object.values(queryCache).some((value) => !value.hasProcessed)) {
120
- return recursivelyRender(
121
- App,
122
- Routes,
123
- renderPath,
124
- fileImporter,
125
- gqlHandler,
126
- queryCache
127
- );
128
- } else {
129
- if (shouldShowGraphqlHandlerNotFoundWarn) {
130
- console.warn(
131
- '\n \u26A0\uFE0F Could not load your GraphQL handler. \n Your Cells have been prerendered in the "Loading" state. \n'
132
- );
133
- }
134
- return Promise.resolve(componentAsHtml);
135
- }
136
- }
137
- function insertChunkLoadingScript(indexHtmlTree, renderPath) {
138
- const { matchPath } = require("@cedarjs/router/dist/util");
139
- const prerenderRoutes = (0, import_detection.detectPrerenderRoutes)();
140
- const route = prerenderRoutes.find((route2) => {
141
- if (!route2.routePath) {
142
- return false;
143
- }
144
- return matchPath(route2.routePath, renderPath).match;
145
- });
146
- if (!route) {
147
- throw new Error("Could not find a Route matching " + renderPath);
148
- }
149
- if (!route.pageIdentifier) {
150
- throw new Error(`Route for ${renderPath} has no pageIdentifier`);
151
- }
152
- const buildManifest = JSON.parse(
153
- import_node_fs.default.readFileSync(
154
- import_node_path.default.join((0, import_project_config.getPaths)().web.dist, "client-build-manifest.json"),
155
- "utf-8"
156
- )
157
- );
158
- const chunkPaths = [];
159
- if (route?.filePath) {
160
- const pagesIndex = route.filePath.indexOf(import_node_path.default.join("web", "src", "pages")) + 4;
161
- const pagePath = (0, import_project_config.ensurePosixPath)(route.filePath.slice(pagesIndex));
162
- const pageChunkPath = buildManifest[pagePath]?.file;
163
- if (pageChunkPath) {
164
- chunkPaths.push("/" + pageChunkPath);
165
- }
166
- }
167
- if (chunkPaths.length === 0) {
168
- return;
169
- }
170
- chunkPaths.forEach((chunkPath) => {
171
- indexHtmlTree("head").prepend(
172
- `<script defer="defer" src="${chunkPath}" type="module"></script>`
173
- );
174
- });
175
- chunkPaths.forEach((chunkPath) => {
176
- const fullChunkPath = import_node_path.default.join((0, import_project_config.getPaths)().web.dist, chunkPath);
177
- const jsChunk = import_node_fs.default.readFileSync(fullChunkPath, "utf-8");
178
- const matches = jsChunk.match(/export\s*\{\s*\w+ as default\s*\}/g) || [];
179
- const lastIndex = jsChunk.lastIndexOf(matches[matches.length - 1]);
180
- const varNameMatch = jsChunk.slice(lastIndex).match(/export\s*\{\s*(\w+) as default\s*\}/);
181
- import_node_fs.default.writeFileSync(
182
- fullChunkPath,
183
- jsChunk + `globalThis.__REDWOOD__PRERENDER_PAGES = globalThis.__REDWOOD__PRERENDER_PAGES || {};
184
- globalThis.__REDWOOD__PRERENDER_PAGES.${route?.pageIdentifier}=${varNameMatch?.[1]};
185
- `
186
- );
187
- });
188
- }
189
- const runPrerender = async ({
190
- queryCache,
191
- renderPath
192
- }) => {
193
- (0, import_internal.registerShims)(renderPath);
194
- (0, import_babel_config.registerApiSideBabelHook)({
195
- plugins: [
196
- [
197
- "babel-plugin-module-resolver",
198
- {
199
- alias: {
200
- api: (0, import_project_config.getPaths)().api.base,
201
- web: (0, import_project_config.getPaths)().web.base
202
- },
203
- loglevel: "silent"
204
- // to silence the unnecessary warnings
205
- }
206
- ]
207
- ],
208
- overrides: [
209
- {
210
- test: ["./api/"],
211
- plugins: [
212
- [
213
- "babel-plugin-module-resolver",
214
- {
215
- alias: {
216
- src: (0, import_project_config.getPaths)().api.src
217
- },
218
- loglevel: "silent"
219
- },
220
- "exec-api-src-module-resolver"
221
- ]
222
- ]
223
- }
224
- ]
225
- });
226
- const gqlHandler = await (0, import_graphql.getGqlHandler)(require);
227
- (0, import_babel_config.registerWebSideBabelHook)({
228
- overrides: [
229
- {
230
- plugins: [
231
- // Vite handles CSS imports for the browser build
232
- ["ignore-html-and-css-imports"],
233
- [import_babel_plugin_redwood_prerender_media_imports.babelPluginRedwoodPrerenderMediaImports]
234
- ]
235
- },
236
- {
237
- test: /.+Cell.(js|tsx|jsx)$/,
238
- plugins: [import_babel_plugin_redwood_cell.babelPluginRedwoodCell]
239
- }
240
- ],
241
- options: {
242
- forPrerender: true
243
- }
244
- });
245
- const indexContent = import_node_fs.default.readFileSync((0, import_internal.getRootHtmlPath)()).toString();
246
- const { default: App } = require((0, import_project_config.getPaths)().web.app);
247
- const { default: Routes } = require((0, import_project_config.getPaths)().web.routes);
248
- const componentAsHtml = await recursivelyRender(
249
- App,
250
- Routes,
251
- renderPath,
252
- require,
253
- gqlHandler,
254
- queryCache
255
- );
256
- const { helmet } = globalThis.__REDWOOD__HELMET_CONTEXT;
257
- Object.keys(queryCache).forEach((queryKey) => {
258
- const { query, variables, data } = queryCache[queryKey];
259
- prerenderApolloClient.writeQuery({
260
- query,
261
- variables,
262
- data
263
- });
264
- });
265
- const indexHtmlTree = (0, import_cheerio.load)(indexContent);
266
- if (helmet) {
267
- const helmetElements = `
268
- ${helmet?.link.toString()}
269
- ${helmet?.meta.toString()}
270
- ${helmet?.script.toString()}
271
- ${helmet?.noscript.toString()}
272
- `;
273
- indexHtmlTree("head").prepend(helmetElements);
274
- const titleHtmlTag = helmet.title.toString();
275
- if ((0, import_cheerio.load)(titleHtmlTag)("title").text() !== "") {
276
- if (indexHtmlTree("title").text().length === 0) {
277
- indexHtmlTree("head").prepend(titleHtmlTag);
278
- } else {
279
- indexHtmlTree("title").replaceWith(titleHtmlTag);
280
- }
281
- }
282
- }
283
- const apolloState = prerenderApolloClient.extract();
284
- if ((0, import_apolloState.hasApolloState)(apolloState)) {
285
- indexHtmlTree("head").append(
286
- `<script> globalThis.__CEDAR__APOLLO_STATE = ${JSON.stringify(
287
- apolloState
288
- )}</script>`
289
- );
290
- }
291
- prerenderApolloClient.resetStore();
292
- insertChunkLoadingScript(indexHtmlTree, renderPath);
293
- indexHtmlTree("#cedar-app, #redwood-app").append(componentAsHtml);
294
- const renderOutput = indexHtmlTree.html();
295
- return renderOutput;
296
- };
297
- const writePrerenderedHtmlFile = (outputHtmlPath, content) => {
298
- const outputHtmlAbsPath = import_node_path.default.join((0, import_project_config.getPaths)().base, outputHtmlPath);
299
- if (outputHtmlPath === "web/dist/index.html") {
300
- const html200Path = import_node_path.default.join((0, import_project_config.getPaths)().web.dist, "200.html");
301
- if (!import_node_fs.default.existsSync(html200Path)) {
302
- import_node_fs.default.copyFileSync(outputHtmlAbsPath, html200Path);
303
- }
304
- }
305
- (0, import_internal.writeToDist)(outputHtmlAbsPath, content);
306
- };
307
- // Annotate the CommonJS export names for ESM import in node:
308
- 0 && (module.exports = {
309
- runPrerender,
310
- writePrerenderedHtmlFile
311
- });
@@ -1,308 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var runPrerenderEsm_exports = {};
30
- __export(runPrerenderEsm_exports, {
31
- runPrerender: () => runPrerender,
32
- writePrerenderedHtmlFile: () => writePrerenderedHtmlFile
33
- });
34
- module.exports = __toCommonJS(runPrerenderEsm_exports);
35
- var import_node_fs = __toESM(require("node:fs"), 1);
36
- var import_node_path = __toESM(require("node:path"), 1);
37
- var import_react = __toESM(require("react"), 1);
38
- var apolloClient = __toESM(require("@apollo/client"), 1);
39
- var import_cheerio = require("cheerio");
40
- var import_server = __toESM(require("react-dom/server"), 1);
41
- var import_project_config = require("@cedarjs/project-config");
42
- var import_util = require("@cedarjs/router/dist/util");
43
- var import_apolloState = require("./apolloState.js");
44
- var import_buildAndImport = require("./build-and-import/buildAndImport.js");
45
- var import_detection = require("./detection/detection.js");
46
- var import_errors = require("./errors.js");
47
- var import_graphql = require("./graphql/graphql.js");
48
- var import_node_runner = require("./graphql/node-runner.js");
49
- var import_internal = require("./internal.js");
50
- const { ApolloClient, InMemoryCache } = apolloClient.default;
51
- const prerenderApolloClient = new ApolloClient({ cache: new InMemoryCache() });
52
- async function recursivelyRender(App, Routes, CellCacheContextProvider, LocationProvider, renderPath, fileImporter, gqlHandler, queryCache) {
53
- const { getOperationName } = await import("@cedarjs/web");
54
- let shouldShowGraphqlHandlerNotFoundWarn = false;
55
- await Promise.all(
56
- Object.entries(queryCache).map(async ([cacheKey, value]) => {
57
- if (value.hasProcessed) {
58
- return Promise.resolve("");
59
- }
60
- try {
61
- const resultString = await (0, import_graphql.executeQuery)(
62
- fileImporter,
63
- gqlHandler,
64
- value.query,
65
- value.variables
66
- );
67
- let result;
68
- try {
69
- result = JSON.parse(resultString);
70
- } catch (e) {
71
- if (e instanceof SyntaxError) {
72
- throw new import_errors.JSONParseError({
73
- query: value.query,
74
- variables: value.variables,
75
- result: resultString
76
- });
77
- }
78
- }
79
- if (result.errors) {
80
- const message = result.errors[0].message ?? JSON.stringify(result.errors, null, 4);
81
- if (result.errors[0]?.extensions?.code === "UNAUTHENTICATED") {
82
- const queryName = getOperationName(value.query);
83
- console.error(
84
- `
85
-
86
- \u{1F6D1} Cannot prerender the query ${queryName} as it requires auth.
87
- `
88
- );
89
- }
90
- throw new import_errors.PrerenderGqlError(message);
91
- }
92
- queryCache[cacheKey] = {
93
- ...value,
94
- data: result.data,
95
- hasProcessed: true
96
- };
97
- return result;
98
- } catch (e) {
99
- if (e instanceof import_errors.GqlHandlerImportError) {
100
- shouldShowGraphqlHandlerNotFoundWarn = true;
101
- queryCache[cacheKey] = {
102
- ...value,
103
- // tried to fetch, but failed
104
- renderLoading: true,
105
- hasProcessed: true
106
- };
107
- return;
108
- } else {
109
- throw e;
110
- }
111
- }
112
- })
113
- );
114
- const prerenderUrl = process.env.RWJS_PRERENDER_ORIGIN || "http://localhost" + renderPath;
115
- const componentAsHtml = import_server.default.renderToString(
116
- /* @__PURE__ */ import_react.default.createElement(LocationProvider, { location: new URL(prerenderUrl) }, /* @__PURE__ */ import_react.default.createElement(CellCacheContextProvider, { queryCache }, /* @__PURE__ */ import_react.default.createElement(App, null, /* @__PURE__ */ import_react.default.createElement(Routes, null))))
117
- );
118
- if (Object.values(queryCache).some((value) => !value.hasProcessed)) {
119
- return recursivelyRender(
120
- App,
121
- Routes,
122
- CellCacheContextProvider,
123
- LocationProvider,
124
- renderPath,
125
- fileImporter,
126
- gqlHandler,
127
- queryCache
128
- );
129
- } else {
130
- if (shouldShowGraphqlHandlerNotFoundWarn) {
131
- console.warn(
132
- '\n \u26A0\uFE0F Could not load your GraphQL handler. \n Your Cells have been prerendered in the "Loading" state. \n'
133
- );
134
- }
135
- return Promise.resolve(componentAsHtml);
136
- }
137
- }
138
- function insertChunkLoadingScript(indexHtmlTree, renderPath) {
139
- const prerenderRoutes = (0, import_detection.detectPrerenderRoutes)();
140
- const route = prerenderRoutes.find((route2) => {
141
- if (!route2.routePath) {
142
- return false;
143
- }
144
- return (0, import_util.matchPath)(route2.routePath, renderPath).match;
145
- });
146
- if (!route) {
147
- throw new Error("Could not find a Route matching " + renderPath);
148
- }
149
- if (!route.pageIdentifier) {
150
- throw new Error(`Route for ${renderPath} has no pageIdentifier`);
151
- }
152
- const buildManifest = JSON.parse(
153
- import_node_fs.default.readFileSync(
154
- import_node_path.default.join((0, import_project_config.getPaths)().web.dist, "client-build-manifest.json"),
155
- "utf-8"
156
- )
157
- );
158
- const chunkPaths = [];
159
- if (route?.filePath) {
160
- const pagesIndex = route.filePath.indexOf(import_node_path.default.join("web", "src", "pages")) + 4;
161
- const pagePath = (0, import_project_config.ensurePosixPath)(route.filePath.slice(pagesIndex));
162
- const pageChunkPath = buildManifest[pagePath]?.file;
163
- if (pageChunkPath) {
164
- chunkPaths.push("/" + pageChunkPath);
165
- }
166
- }
167
- if (chunkPaths.length === 0) {
168
- return;
169
- }
170
- chunkPaths.forEach((chunkPath) => {
171
- indexHtmlTree("head").prepend(
172
- `<script defer="defer" src="${chunkPath}" type="module"></script>`
173
- );
174
- });
175
- chunkPaths.forEach((chunkPath) => {
176
- const fullChunkPath = import_node_path.default.join((0, import_project_config.getPaths)().web.dist, chunkPath);
177
- const jsChunk = import_node_fs.default.readFileSync(fullChunkPath, "utf-8");
178
- const matches = jsChunk.match(/export\s*\{\s*\w+ as default\s*\}/g) || [];
179
- const lastIndex = jsChunk.lastIndexOf(matches[matches.length - 1]);
180
- const varNameMatch = jsChunk.slice(lastIndex).match(/export\s*\{\s*(\w+) as default\s*\}/);
181
- import_node_fs.default.writeFileSync(
182
- fullChunkPath,
183
- jsChunk + `globalThis.__REDWOOD__PRERENDER_PAGES = globalThis.__REDWOOD__PRERENDER_PAGES || {};
184
- globalThis.__REDWOOD__PRERENDER_PAGES.${route?.pageIdentifier}=${varNameMatch?.[1]};
185
- `
186
- );
187
- });
188
- }
189
- async function createCombinedEntry({ appPath, routesPath, outDir }) {
190
- const combinedContent = `
191
- import { LocationProvider } from '@cedarjs/router'
192
- import { CellCacheContextProvider } from '@cedarjs/web'
193
-
194
- import App from "${(0, import_project_config.importStatementPath)(appPath.replace(".tsx", ""))}";
195
- import Routes from "${(0, import_project_config.importStatementPath)(routesPath.replace(".tsx", ""))}";
196
-
197
- export { LocationProvider, CellCacheContextProvider, App, Routes };
198
- `;
199
- const tempFilePath = import_node_path.default.join(outDir, "__prerender-temp-entry.tsx");
200
- await import_node_fs.default.promises.writeFile(tempFilePath, combinedContent, "utf8");
201
- return tempFilePath;
202
- }
203
- const renderCache = {};
204
- const runPrerender = async ({
205
- queryCache,
206
- renderPath
207
- }) => {
208
- (0, import_internal.registerShims)(renderPath);
209
- const nodeRunner = new import_node_runner.NodeRunner();
210
- const gqlHandler = await (0, import_graphql.getGqlHandler)(nodeRunner.importFile.bind(nodeRunner));
211
- const prerenderDistPath = import_node_path.default.join((0, import_project_config.getPaths)().web.dist, "__prerender");
212
- import_node_fs.default.mkdirSync(prerenderDistPath, { recursive: true });
213
- if (!renderCache.App) {
214
- const entryPath = await createCombinedEntry({
215
- appPath: (0, import_project_config.getPaths)().web.app,
216
- routesPath: (0, import_project_config.getPaths)().web.routes,
217
- outDir: prerenderDistPath
218
- });
219
- const required = await (0, import_buildAndImport.buildAndImport)({
220
- filepath: entryPath,
221
- preserveTemporaryFile: true
222
- });
223
- renderCache.App = required.App;
224
- renderCache.Routes = required.Routes;
225
- renderCache.CellCacheContextProvider = required.CellCacheContextProvider;
226
- renderCache.LocationProvider = required.LocationProvider;
227
- }
228
- const { LocationProvider, App, Routes, CellCacheContextProvider } = renderCache;
229
- if (!App) {
230
- throw new Error("App not found");
231
- }
232
- if (!Routes) {
233
- throw new Error("Routes not found");
234
- }
235
- if (!CellCacheContextProvider) {
236
- throw new Error("CellCacheContextProvider not found");
237
- }
238
- if (!LocationProvider) {
239
- throw new Error("LocationProvider not found");
240
- }
241
- const componentAsHtml = await recursivelyRender(
242
- App,
243
- Routes,
244
- CellCacheContextProvider,
245
- LocationProvider,
246
- renderPath,
247
- nodeRunner.importFile.bind(nodeRunner),
248
- gqlHandler,
249
- queryCache
250
- );
251
- nodeRunner.close();
252
- const { helmet } = globalThis.__REDWOOD__HELMET_CONTEXT;
253
- Object.keys(queryCache).forEach((queryKey) => {
254
- const { query, variables, data } = queryCache[queryKey];
255
- prerenderApolloClient.writeQuery({
256
- query,
257
- variables,
258
- data
259
- });
260
- });
261
- const indexContent = import_node_fs.default.readFileSync((0, import_internal.getRootHtmlPath)()).toString();
262
- const indexHtmlTree = (0, import_cheerio.load)(indexContent);
263
- if (helmet) {
264
- const helmetElements = `
265
- ${helmet?.link.toString()}
266
- ${helmet?.meta.toString()}
267
- ${helmet?.script.toString()}
268
- ${helmet?.noscript.toString()}
269
- `;
270
- indexHtmlTree("head").prepend(helmetElements);
271
- const titleHtmlTag = helmet.title.toString();
272
- if ((0, import_cheerio.load)(titleHtmlTag)("title").text() !== "") {
273
- if (indexHtmlTree("title").text().length === 0) {
274
- indexHtmlTree("head").prepend(titleHtmlTag);
275
- } else {
276
- indexHtmlTree("title").replaceWith(titleHtmlTag);
277
- }
278
- }
279
- }
280
- const apolloState = prerenderApolloClient.extract();
281
- if ((0, import_apolloState.hasApolloState)(apolloState)) {
282
- indexHtmlTree("head").append(
283
- `<script> globalThis.__CEDAR__APOLLO_STATE = ${JSON.stringify(
284
- apolloState
285
- )}</script>`
286
- );
287
- }
288
- prerenderApolloClient.resetStore();
289
- insertChunkLoadingScript(indexHtmlTree, renderPath);
290
- indexHtmlTree("#cedar-app, #redwood-app").append(componentAsHtml);
291
- const renderOutput = indexHtmlTree.html();
292
- return renderOutput;
293
- };
294
- const writePrerenderedHtmlFile = (outputHtmlPath, content) => {
295
- const outputHtmlAbsPath = import_node_path.default.join((0, import_project_config.getPaths)().base, outputHtmlPath);
296
- if (outputHtmlPath === "web/dist/index.html") {
297
- const html200Path = import_node_path.default.join((0, import_project_config.getPaths)().web.dist, "200.html");
298
- if (!import_node_fs.default.existsSync(html200Path)) {
299
- import_node_fs.default.copyFileSync(outputHtmlAbsPath, html200Path);
300
- }
301
- }
302
- (0, import_internal.writeToDist)(outputHtmlAbsPath, content);
303
- };
304
- // Annotate the CommonJS export names for ESM import in node:
305
- 0 && (module.exports = {
306
- runPrerender,
307
- writePrerenderedHtmlFile
308
- });
@@ -1,9 +0,0 @@
1
- import type { QueryInfo } from '@cedarjs/web';
2
- interface PrerenderParams {
3
- queryCache: Record<string, QueryInfo>;
4
- renderPath: string;
5
- }
6
- export declare const runPrerender: ({ queryCache, renderPath, }: PrerenderParams) => Promise<string | void>;
7
- export declare const writePrerenderedHtmlFile: (outputHtmlPath: string, content: string) => void;
8
- export {};
9
- //# sourceMappingURL=runPrerenderEsm.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"runPrerenderEsm.d.ts","sourceRoot":"","sources":["../src/runPrerenderEsm.tsx"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAqQ7C,UAAU,eAAe;IACvB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;IACrC,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,eAAO,MAAM,YAAY,GAAU,6BAGhC,eAAe,KAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CA4HzC,CAAA;AAGD,eAAO,MAAM,wBAAwB,GACnC,gBAAgB,MAAM,EACtB,SAAS,MAAM,SAchB,CAAA"}
File without changes