| ... | ... | @@ -1,11 +1,16 @@ |
| 1 | // This file contains the main site generator build process. |
| 2 | // By using `Incremental`'s ability to automatically purge stale |
| 3 | // assets, the `sitegen` function performs partial rebuilds. |
| 4 | |
| 1 | 5 | export function main(incremental?: Incremental) { |
| 2 | 6 | return withSpinner<Record<string, unknown>, any>({ |
| 3 | 7 | text: "Recovering State", |
| 4 | 8 | successText, |
| 5 | 9 | failureText: () => "sitegen FAIL", |
| 6 | 10 | }, async (spinner) => { |
| 7 | | const incr = Incremental.fromDisk(); |
| 8 | | await incr.statAllFiles(); |
| 11 | // const incr = Incremental.fromDisk(); |
| 12 | // await incr.statAllFiles(); |
| 13 | const incr = new Incremental(); |
| 9 | 14 | const result = await sitegen(spinner, incr); |
| 10 | 15 | incr.toDisk(); // Allows picking up this state again |
| 11 | 16 | return result; |
| ... | ... | @@ -94,26 +99,42 @@ export async function sitegen( |
| 94 | 99 | scripts = scripts.filter(({ file }) => !file.match(/\.client\.[tj]sx?/)); |
| 95 | 100 | const globalCssPath = join("global.css"); |
| 96 | 101 | |
| 97 | | // TODO: invalidate incremental resources |
| 102 | // TODO: make sure that `static` and `pages` does not overlap |
| 98 | 103 | |
| 99 | | // -- server side render -- |
| 104 | // -- inline style sheets, used and shared by pages and views -- |
| 100 | 105 | status.text = "Building"; |
| 101 | | const cssOnce = new OnceMap<css.Output>(); |
| 102 | | const cssQueue = new Queue<[string, string[], css.Theme], css.Output>({ |
| 106 | const cssOnce = new OnceMap(); |
| 107 | const cssQueue = new Queue({ |
| 103 | 108 | name: "Bundle", |
| 104 | | fn: ([, files, theme]) => css.bundleCssFiles(files, theme), |
| 109 | async fn([, key, files, theme]: [string, string, string[], css.Theme]) { |
| 110 | const { text, sources } = await css.bundleCssFiles(files, theme); |
| 111 | incr.put({ |
| 112 | kind: "style", |
| 113 | key, |
| 114 | sources, |
| 115 | value: text, |
| 116 | }); |
| 117 | }, |
| 105 | 118 | passive: true, |
| 106 | 119 | getItemText: ([id]) => id, |
| 107 | 120 | maxJobs: 2, |
| 108 | 121 | }); |
| 109 | | interface RenderResult { |
| 110 | | body: string; |
| 111 | | head: string; |
| 112 | | css: css.Output; |
| 113 | | clientRefs: string[]; |
| 114 | | item: FileItem; |
| 122 | function ensureCssGetsBuilt( |
| 123 | cssImports: string[], |
| 124 | theme: css.Theme, |
| 125 | referrer: string, |
| 126 | ) { |
| 127 | const key = css.styleKey(cssImports, theme); |
| 128 | cssOnce.get( |
| 129 | key, |
| 130 | async () => { |
| 131 | incr.getArtifact("style", key) ?? |
| 132 | await cssQueue.add([referrer, key, cssImports, theme]); |
| 133 | }, |
| 134 | ); |
| 115 | 135 | } |
| 116 | | const renderResults: RenderResult[] = []; |
| 136 | |
| 137 | // -- server side render pages -- |
| 117 | 138 | async function loadPageModule({ file }: FileItem) { |
| 118 | 139 | require(file); |
| 119 | 140 | } |
| ... | ... | @@ -125,28 +146,27 @@ export async function sitegen( |
| 125 | 146 | theme: pageTheme, |
| 126 | 147 | layout, |
| 127 | 148 | } = require(item.file); |
| 128 | | if (!Page) throw new Error("Page is missing a 'default' export."); |
| 149 | if (!Page) { |
| 150 | throw new Error("Page is missing a 'default' export."); |
| 151 | } |
| 129 | 152 | if (!metadata) { |
| 130 | 153 | throw new Error("Page is missing 'meta' export with a title."); |
| 131 | 154 | } |
| 155 | |
| 156 | // -- css -- |
| 132 | 157 | if (layout?.theme) pageTheme = layout.theme; |
| 133 | | const theme = { |
| 134 | | bg: "#fff", |
| 135 | | fg: "#050505", |
| 136 | | primary: "#2e7dab", |
| 158 | const theme: css.Theme = { |
| 159 | ...css.defaultTheme, |
| 137 | 160 | ...pageTheme, |
| 138 | 161 | }; |
| 162 | const cssImports = [globalCssPath, ...hot.getCssImports(item.file)]; |
| 163 | ensureCssGetsBuilt(cssImports, theme, item.id); |
| 139 | 164 | |
| 140 | 165 | // -- metadata -- |
| 141 | 166 | const renderedMetaPromise = Promise.resolve( |
| 142 | 167 | typeof metadata === "function" ? metadata({ ssr: true }) : metadata, |
| 143 | 168 | ).then((m) => meta.renderMeta(m)); |
| 144 | | // -- css -- |
| 145 | | const cssImports = [globalCssPath, ...hot.getCssImports(item.file)]; |
| 146 | | const cssPromise = cssOnce.get( |
| 147 | | cssImports.join(":") + JSON.stringify(theme), |
| 148 | | () => cssQueue.add([item.id, cssImports, theme]), |
| 149 | | ); |
| 169 | |
| 150 | 170 | // -- html -- |
| 151 | 171 | let page = [engine.kElement, Page, {}]; |
| 152 | 172 | if (layout?.default) { |
| ... | ... | @@ -156,9 +176,8 @@ export async function sitegen( |
| 156 | 176 | sitegen: sg.initRender(), |
| 157 | 177 | }); |
| 158 | 178 | |
| 159 | | const [{ text, addon }, cssBundle, renderedMeta] = await Promise.all([ |
| 179 | const [{ text, addon }, renderedMeta] = await Promise.all([ |
| 160 | 180 | bodyPromise, |
| 161 | | cssPromise, |
| 162 | 181 | renderedMetaPromise, |
| 163 | 182 | ]); |
| 164 | 183 | if (!renderedMeta.includes("<title>")) { |
| ... | ... | @@ -167,20 +186,72 @@ export async function sitegen( |
| 167 | 186 | "All pages need a title tag.", |
| 168 | 187 | ); |
| 169 | 188 | } |
| 170 | | // The script content is not ready, allow another page to Render. The page |
| 171 | | // contents will be rebuilt at the end. This is more convenient anyways |
| 172 | | // because it means client scripts don't re-render the page. |
| 173 | | renderResults.push({ |
| 174 | | body: text, |
| 175 | | head: renderedMeta, |
| 176 | | css: cssBundle, |
| 177 | | clientRefs: Array.from(addon.sitegen.scripts), |
| 178 | | item: item, |
| 189 | incr.put({ |
| 190 | kind: "pageMetadata", |
| 191 | key: item.id, |
| 192 | // Incremental integrates with `hot.ts` + `require` |
| 193 | // to trace all the needed source files here. |
| 194 | sources: [item.file], |
| 195 | value: { |
| 196 | html: text, |
| 197 | meta: renderedMeta, |
| 198 | cssImports, |
| 199 | theme: theme ?? null, |
| 200 | clientRefs: Array.from(addon.sitegen.scripts), |
| 201 | }, |
| 202 | }); |
| 203 | } |
| 204 | async function prepareView(view: FileItem) { |
| 205 | const module = require(view.file); |
| 206 | if (!module.meta) { |
| 207 | throw new Error(`${view.file} is missing 'export const meta'`); |
| 208 | } |
| 209 | if (!module.default) { |
| 210 | throw new Error(`${view.file} is missing a default export.`); |
| 211 | } |
| 212 | const pageTheme = module.layout?.theme ?? module.theme; |
| 213 | const theme: css.Theme = { |
| 214 | ...css.defaultTheme, |
| 215 | ...pageTheme, |
| 216 | }; |
| 217 | const cssImports = hot.getCssImports(view.file) |
| 218 | .concat("src/global.css") |
| 219 | .map((file) => path.relative(hot.projectRoot, path.resolve(file))); |
| 220 | incr.put({ |
| 221 | kind: "viewMetadata", |
| 222 | key: view.id, |
| 223 | sources: [view.file], |
| 224 | value: { |
| 225 | file: path.relative(hot.projectRoot, view.file), |
| 226 | cssImports, |
| 227 | theme, |
| 228 | clientRefs: hot.getClientScriptRefs(view.file), |
| 229 | hasLayout: !!module.layout?.default, |
| 230 | }, |
| 179 | 231 | }); |
| 180 | 232 | } |
| 233 | |
| 234 | // Of the pages that are already built, a call to 'ensureCssGetsBuilt' is |
| 235 | // required so that it's (1) re-built if needed, (2) not pruned from build. |
| 236 | const neededPages = pages.filter((page) => { |
| 237 | const existing = incr.getArtifact("pageMetadata", page.id); |
| 238 | if (existing) { |
| 239 | const { cssImports, theme } = existing; |
| 240 | ensureCssGetsBuilt(cssImports, theme, page.id); |
| 241 | } |
| 242 | return !existing; |
| 243 | }); |
| 244 | const neededViews = views.filter((view) => { |
| 245 | const existing = incr.getArtifact("viewMetadata", view.id); |
| 246 | if (existing) { |
| 247 | const { cssImports, theme } = existing; |
| 248 | ensureCssGetsBuilt(cssImports, theme, view.id); |
| 249 | } |
| 250 | return !existing; |
| 251 | }); |
| 252 | |
| 181 | 253 | // This is done in two passes so that a page that throws during evaluation |
| 182 | 254 | // will report "Load Render Module" instead of "Render Static Page". |
| 183 | | const neededPages = pages.filter((page) => incr.needsBuild("asset", page.id)); |
| 184 | 255 | const spinnerFormat = status.format; |
| 185 | 256 | status.format = () => ""; |
| 186 | 257 | const moduleLoadQueue = new Queue({ |
| ... | ... | @@ -190,6 +261,7 @@ export async function sitegen( |
| 190 | 261 | maxJobs: 1, |
| 191 | 262 | }); |
| 192 | 263 | moduleLoadQueue.addMany(neededPages); |
| 264 | moduleLoadQueue.addMany(neededViews); |
| 193 | 265 | await moduleLoadQueue.done({ method: "stop" }); |
| 194 | 266 | const pageQueue = new Queue({ |
| 195 | 267 | name: "Render Static Page", |
| ... | ... | @@ -198,32 +270,52 @@ export async function sitegen( |
| 198 | 270 | maxJobs: 2, |
| 199 | 271 | }); |
| 200 | 272 | pageQueue.addMany(neededPages); |
| 273 | const viewQueue = new Queue({ |
| 274 | name: "Build Dynamic View", |
| 275 | fn: prepareView, |
| 276 | getItemText, |
| 277 | maxJobs: 2, |
| 278 | }); |
| 279 | viewQueue.addMany(neededViews); |
| 201 | 280 | await pageQueue.done({ method: "stop" }); |
| 281 | await viewQueue.done({ method: "stop" }); |
| 202 | 282 | status.format = spinnerFormat; |
| 203 | 283 | |
| 204 | 284 | // -- bundle backend and views -- |
| 205 | | status.text = "Bundle backend code"; |
| 206 | | const backend = await bundle.bundleServerJavaScript( |
| 207 | | join("backend.ts"), |
| 208 | | views, |
| 209 | | ); |
| 210 | | const viewCssPromise = await Promise.all( |
| 211 | | backend.views.map((view) => |
| 212 | | cssOnce.get( |
| 213 | | view.cssImports.join(":") + JSON.stringify(view.theme), |
| 214 | | () => cssQueue.add([view.id, view.cssImports, view.theme ?? {}]), |
| 215 | | ) |
| 216 | | ), |
| 217 | | ); |
| 285 | // status.text = "Bundle backend code"; |
| 286 | // const backend = await bundle.bundleServerJavaScript( |
| 287 | // join("backend.ts"), |
| 288 | // views, |
| 289 | // ); |
| 290 | // const viewCssPromise = await Promise.all( |
| 291 | // backend.views.map((view) => |
| 292 | // cssOnce.get( |
| 293 | // view.cssImports.join(":") + JSON.stringify(view.theme), |
| 294 | // () => cssQueue.add([view.id, view.cssImports, view.theme ?? {}]), |
| 295 | // ) |
| 296 | // ), |
| 297 | // ); |
| 218 | 298 | |
| 219 | 299 | // -- bundle scripts -- |
| 220 | 300 | const referencedScripts = Array.from( |
| 221 | | new Set([ |
| 222 | | ...renderResults.flatMap((r) => r.clientRefs), |
| 223 | | ...backend.views.flatMap((r) => r.clientRefs), |
| 224 | | ]), |
| 301 | new Set( |
| 302 | [ |
| 303 | ...pages.map((item) => |
| 304 | UNWRAP( |
| 305 | incr.getArtifact("pageMetadata", item.id), |
| 306 | `Missing pageMetadata ${item.id}`, |
| 307 | ) |
| 308 | ), |
| 309 | ...views.map((item) => |
| 310 | UNWRAP( |
| 311 | incr.getArtifact("viewMetadata", item.id), |
| 312 | `Missing viewMetadata ${item.id}`, |
| 313 | ) |
| 314 | ), |
| 315 | ].flatMap((item) => item.clientRefs), |
| 316 | ), |
| 225 | 317 | (script) => path.resolve(hot.projectSrc, script), |
| 226 | | ); |
| 318 | ).filter((file) => !incr.hasArtifact("script", hot.getScriptId(file))); |
| 227 | 319 | const extraPublicScripts = scripts.map((entry) => entry.file); |
| 228 | 320 | const uniqueCount = new Set([ |
| 229 | 321 | ...referencedScripts, |
| ... | ... | @@ -237,7 +329,7 @@ export async function sitegen( |
| 237 | 329 | ); |
| 238 | 330 | |
| 239 | 331 | // -- finalize backend bundle -- |
| 240 | | await bundle.finalizeServerJavaScript(backend, await viewCssPromise, incr); |
| 332 | // await bundle.finalizeServerJavaScript(backend, await viewCssPromise, incr); |
| 241 | 333 | |
| 242 | 334 | // -- copy/compress static files -- |
| 243 | 335 | async function doStaticFile(item: FileItem) { |
| ... | ... | @@ -256,37 +348,51 @@ export async function sitegen( |
| 256 | 348 | }); |
| 257 | 349 | status.format = () => ""; |
| 258 | 350 | staticQueue.addMany( |
| 259 | | staticFiles.filter((file) => incr.needsBuild("asset", file.id)), |
| 351 | staticFiles.filter((file) => !incr.hasArtifact("asset", file.id)), |
| 260 | 352 | ); |
| 261 | 353 | await staticQueue.done({ method: "stop" }); |
| 262 | 354 | status.format = spinnerFormat; |
| 263 | 355 | |
| 356 | await cssQueue.done({ method: "stop" }); |
| 357 | |
| 264 | 358 | // -- concatenate static rendered pages -- |
| 265 | | status.text = `Concat ${renderResults.length} Pages`; |
| 266 | | await Promise.all( |
| 267 | | renderResults.map( |
| 268 | | async ( |
| 269 | | { item: page, body, head, css, clientRefs: scriptFiles }, |
| 270 | | ) => { |
| 271 | | const doc = wrapDocument({ |
| 272 | | body, |
| 273 | | head, |
| 274 | | inlineCss: css.text, |
| 275 | | scripts: scriptFiles.map( |
| 276 | | (file) => UNWRAP(incr.out.script.get(hot.getScriptId(file))), |
| 277 | | ).map((x) => `{${x}}`).join("\n"), |
| 278 | | }); |
| 279 | | await incr.putAsset({ |
| 280 | | sources: [page.file, ...css.sources], |
| 281 | | key: page.id, |
| 282 | | body: doc, |
| 283 | | headers: { |
| 284 | | "Content-Type": "text/html", |
| 285 | | }, |
| 286 | | }); |
| 359 | status.text = `Concat Pages`; |
| 360 | await Promise.all(pages.map(async (page) => { |
| 361 | if (incr.hasArtifact("asset", page.id)) return; |
| 362 | const { |
| 363 | html, |
| 364 | meta, |
| 365 | cssImports, |
| 366 | theme, |
| 367 | clientRefs, |
| 368 | } = UNWRAP(incr.out.pageMetadata.get(page.id)); |
| 369 | const scriptIds = clientRefs.map(hot.getScriptId); |
| 370 | const styleKey = css.styleKey(cssImports, theme); |
| 371 | const style = UNWRAP( |
| 372 | incr.out.style.get(styleKey), |
| 373 | `Missing style ${styleKey}`, |
| 374 | ); |
| 375 | const doc = wrapDocument({ |
| 376 | body: html, |
| 377 | head: meta, |
| 378 | inlineCss: style, |
| 379 | scripts: scriptIds.map( |
| 380 | (ref) => UNWRAP(incr.out.script.get(ref), `Missing script ${ref}`), |
| 381 | ).map((x) => `{${x}}`).join("\n"), |
| 382 | }); |
| 383 | await incr.putAsset({ |
| 384 | sources: [ |
| 385 | page.file, |
| 386 | ...incr.sourcesFor("style", styleKey), |
| 387 | ...scriptIds.flatMap((ref) => incr.sourcesFor("script", ref)), |
| 388 | ], |
| 389 | key: page.id, |
| 390 | body: doc, |
| 391 | headers: { |
| 392 | "Content-Type": "text/html", |
| 287 | 393 | }, |
| 288 | | ), |
| 289 | | ); |
| 394 | }); |
| 395 | })); |
| 290 | 396 | status.format = () => ""; |
| 291 | 397 | status.text = ``; |
| 292 | 398 | // This will wait for all compression jobs to finish, which up |