@bdocs/ssg 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node.cjs +1 -1
- package/dist/node.mjs +1 -1
- package/package.json +4 -2
package/dist/node.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./state-CAM2wH0H.cjs`);let n=require(`react/jsx-runtime`),r=require(`@bdocs/dui`),i=require(`node:module`),a=require(`node:os`);a=e.t(a,1);let o=require(`node:path`);o=e.t(o,1);let s=require(`fs-extra`);s=e.t(s,1);let c=require(`vite`),l=require(`node:crypto`);l=e.t(l,1);let u=require(`node:events`),d=require(`node:stream`),f=require(`react-dom/server`);f=e.t(f);let p=require(`node:fs`);p=e.t(p,1);let m=require(`node:fs/promises`);m=e.t(m,1);const h=/import\("([^)]+)"\)/g;let g=null;async function _(){if(!g){let{matchRoutes:e}=await import(`react-router-dom`);g=e}return g}async function ee({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await _())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(h);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=v(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function v(e,t){let n=new Set;if(!t)return n;for(let r of t)y(e,r,n);return n}function y(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{y(e,t,n)}),n):n}async function te(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function b(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const x=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function S({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${x}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function C(e,t=`index.html`){let[,n]=[...(await s.default.readFile((0,o.join)(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function w(e){return`<link rel="stylesheet" href="${e}">`}function ne(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=T(e);r&&n.push(r)}}),n.join(``)}function T(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function E(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function D(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function re(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;E(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:D(e.headers)};return new Request(n.href,r)}async function ie(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=d.Readable.from(n);r.pipe(t),await(0,u.once)(r,`end`)}else t.end()}function O(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function k(e){return f.renderToString((0,n.jsx)(n.Fragment,{children:e}))}function A(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let j=null;function M(){return j||(j=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=require(`node:module`);return e(require(`url`).pathToFileURL(__filename).href)(`react-helmet-async`).HelmetProvider})(),j)}let N=null;async function ae(){return N||=await import(`react-router-dom`),N}var P=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,n)=>{let{routes:r,base:i}=this.context,{matchRoutes:a}=await ae(),o=re(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=a(t.r([...r],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},i);if(!l){n.statusCode=404,n.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){n.statusCode=404,n.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){n.statusCode=200,n.end(`There is no loader for the route: ${c}`);return}await ie(await F({loader:d,params:u.params,request:o,routeId:c}),n)},this.context=e}async render(e){let{base:r,routes:i,getStyleCollector:a,routerOptions:o}=this.context,s=t.s(e),c=s;if(r!==`/`){let e=t.s(r).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let l=`http://localhost${c}`,u=new Request(l),d=a?await a():null,f={},p=null,{StaticRouterProvider:m,createStaticHandler:h,createStaticRouter:g}=await ae(),_=this._dataRoutes??=t.r([...i],e=>e);this._staticHandler??=h(_,{basename:r});let{query:ee}=this._staticHandler,v=await ee(u),y=0;for(;v instanceof Response&&y<10;){let e=v.headers.get(`Location`);if(!e)break;let n;if(/^https?:\/\//i.test(e))try{let r=new URL(e);if(r.hostname===`localhost`||r.hostname===``)n=`http://localhost${t.s(r.pathname+r.search+r.hash)}`;else break}catch{break}else n=`http://localhost${t.s(e)}`;v=await ee(new Request(n)),y++}if(v instanceof Response)throw v;p=v;let te=g(_,p,{future:o.future}),b=M(),x=b;x&&typeof x==`function`&&(x.canUseDOM=!1);let S=(0,n.jsx)(b,{context:f,children:(0,n.jsx)(m,{router:te,context:p})});d&&(S=d.collect(S));let C=await k(S),{htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E}=A(C,f,d);return{appHTML:C,htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E,routerContext:p}}};async function F({loader:e,params:t,request:n,routeId:r}){let{json:i}=await ae(),a=await e({request:O(L(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return I(a)?a:i(a)}function I(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function L(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function oe(e){return new P(e)}var R=`0.3.0`;async function se(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&B(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function z(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:(0,o.join)(e.root,t))}const ce=/[:*?]/;function B(e){return e?ce.test(e):!1}const V=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),le=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function H(e){try{return p.default.statSync(e).size}catch{return 0}}async function ue(e,t){let n=(0,o.join)(e,`.vite`),r=(0,o.join)(e,`assets`),i={},a=(0,o.join)(n,`manifest.json`);p.default.existsSync(a)&&(i=JSON.parse(await p.default.readFileSync(a,`utf-8`)));let s=0,c=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=H((0,o.join)(e,n));s+=i;for(let t of r)c+=H((0,o.join)(e,t))}let l=0,u=0;if(p.default.existsSync(r)){let e=p.default.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=o.default.extname(t.name).toLowerCase(),n=(0,o.join)(r,t.name);V.has(e)?l+=H(n):le.has(e)&&u++}}let d=(0,o.join)(e,`index.html`),f=0,m=[];if(p.default.existsSync(d)){let e=H(d);f+=e,m.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=p.default.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=H((0,o.join)(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);f+=t,m.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:s,totalCSSBundleSize:c,totalImagesSize:l,totalHTMLSize:f,fontCount:u,pages:m}}function de(e,t){let n=o.default.resolve(e,`..`,`.boltdocs`,`reports`);p.default.existsSync(n)||p.default.mkdirSync(n,{recursive:!0});let r=(0,o.join)(n,`performance.json`);p.default.writeFileSync(r,JSON.stringify(t,null,2))}const fe=Number.parseInt(c.version)>=5?[`.vite`]:[];function pe(e){return Number.parseInt(c.version)>=8?{rolldownOptions:e}:{rollupOptions:e}}const U=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),me=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function he(e){let t=[];if(!s.default.existsSync(e))return t;let n=s.default.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>me.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();U.has(r)&&t.push((0,o.join)(n,e.name))}return t}let W=null,G=null;function ge(e,t,n,r){try{let n=[],i=(0,o.join)(e,t);s.default.existsSync(i)&&n.push(...he(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=(0,o.join)(e,t);s.default.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(W&&G===a)return W;let c=Array(n.length);for(let e=0;e<n.length;e++){let t=s.default.statSync(n[e]);c[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=(0,o.join)(r,`hash-meta.json`),t=(0,o.join)(r,`client-hash.txt`);try{if(s.default.existsSync(e)&&s.default.existsSync(t)){let r=JSON.parse(s.default.readFileSync(e,`utf-8`)),i=Math.max(...c.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=s.default.readFileSync(t,`utf-8`).trim();if(e)return W=e,G=a,e}}}catch{}}let u=l.default.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of c)u.update((0,o.relative)(e,t).replace(/\\/g,`/`)),u.update(n.toString()),u.update(r.toString());let d=u.digest(`hex`);if(W=d,G=a,r)try{let e=Math.max(...c.map(e=>e.mtime)),t=(0,o.join)(r,`hash-meta.json`);s.default.mkdirSync(r,{recursive:!0}),s.default.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return d}catch{return Math.random().toString(36).substring(2,12)}}function _e(e,n){return`static-loader-data${t.s(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${n}.json`}function ve(e,n=`/`){let r=t.s(e),i=r;if(n!==`/`){let e=t.s(n).replace(/\/$/,``);!r.startsWith(e+`/`)&&r!==e&&(i=`${e}${r}`)}return i!==`/`&&i.endsWith(`/`)?i.slice(0,-1):i}function ye(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function K(e={},n={}){let u=process.env.MODE||process.env.NODE_ENV||e.mode||`production`;u!==process.env.NODE_ENV&&(process.env.NODE_ENV=u);let d=await(0,c.resolveConfig)(n,`build`,u,u),f=process.cwd(),p=d.root||f,m=d.build.outDir||`dist`,h=d.base,g=Object.assign({},d.ssgOptions||{},e),_=performance.now(),{script:v=`sync`,mock:y=!1,htmlEntry:w=`index.html`,entry:T=await C(p,w),formatting:E=`none`,includedRoutes:D=ye,onBeforePageRender:re,onPageRendered:ie,onFinished:O,onStep:k,dirStyle:A=`flat`,includeAllRoutes:j=!1,format:M=`esm`,concurrency:N=20,rootContainerId:ae=`root`,routeToSourceFileMap:P={},cacheDir:F=`.boltdocs/build`}=g,I=g.beastiesOptions??{},L=g.turbo??!1,R=`docs`,ce=Object.values(P);if(ce.length>0){let e=ce[0],t=(0,o.relative)(p,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(R=t[0])}let B=(0,o.isAbsolute)(m)?m:(0,o.join)(p,m),V=(0,o.isAbsolute)(F)?F:(0,o.join)(p,F),le=ge(p,R,m,V),H=le.substring(0,12),U=(0,o.join)(V,`ssr`,L?`turbo-ssr`:H),me=(0,o.join)(V,`client-hash.txt`),he=(0,o.join)(V,`template-index.html`),W=!1;try{s.default.existsSync(me)&&s.default.existsSync(he)&&s.default.existsSync(B)&&s.default.existsSync((0,o.join)(B,`assets`))&&(await s.default.readFile(me,`utf-8`)).trim()===le&&(W=!0)}catch{}function G(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=(0,c.createLogger)(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||G(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{G(e)||Ce(e,t)},W)k?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await s.default.ensureDir(B),await s.default.copy(he,(0,o.join)(B,w));else{let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...pe({input:{app:(0,o.join)(p,w||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){m=e.build.outDir||`dist`}}]})),k?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await s.default.ensureDir(V),await s.default.copy((0,o.join)(B,w),he),await s.default.writeFile(me,le,`utf-8`)}let we=()=>{};if(y){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));we=e()}let q=await z(d,T);if((L||W)&&s.default.existsSync(U)&&s.default.readdirSync(U).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)k?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{s.default.existsSync(U)&&await s.default.remove(U),process.env.VITE_SSG=`true`;let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{ssr:q,manifest:!0,outDir:U,minify:!1,cssCodeSplit:!1,...pe({output:M===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode})),k?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Te=M===`esm`&&process.platform===`win32`?`file://`:``,Ee=M===`esm`?`.mjs`:`.cjs`,De=q.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),Oe=Te+(0,o.join)(U,(q.includes(`/`)||q.includes(`\\`)?q.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(Ee,``):De)+Ee).replace(/\\/g,`/`),ke=JSON.parse(await s.default.readFile((0,o.join)(U,...fe,`manifest.json`),`utf-8`)),Ae=typeof require<`u`?require:(0,i.createRequire)(require(`url`).pathToFileURL(__filename).href),{createRoot:je,includedRoutes:Me}=M===`esm`?await import(Oe):Ae(Oe),Ne=Me||D,{routes:Pe}=await je(!1),{paths:Fe}=await se(Pe),J=j?Fe:await Ne(Fe,Pe||[]);J=ye(J,Pe||[]),J=Array.from(new Set(J));let Y;L&&(Y=await b(),Y||(0,r.warn)(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ie=I!==!1&&!Y?await te(m,{publicPath:h,...I}):void 0,Le=``;if(Y){let e=(0,o.join)(B,`assets`);if(s.default.existsSync(e)){let t=s.default.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Le+=s.default.readFileSync((0,o.join)(e,n),`utf-8`)+`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./state-CAM2wH0H.cjs`);let n=require(`react/jsx-runtime`),r=require(`@bdocs/dui`),i=require(`node:module`),a=require(`node:os`);a=e.t(a,1);let o=require(`node:path`);o=e.t(o,1);let s=require(`fs-extra`);s=e.t(s,1);let c=require(`vite`),l=require(`node:crypto`);l=e.t(l,1);let u=require(`node:events`),d=require(`node:stream`),f=require(`react-dom/server`);f=e.t(f);let p=require(`node:fs`);p=e.t(p,1);let m=require(`node:fs/promises`);m=e.t(m,1);const h=/import\("([^)]+)"\)/g;let g=null;async function _(){if(!g){let{matchRoutes:e}=await import(`react-router-dom`);g=e}return g}async function ee({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await _())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(h);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=v(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function v(e,t){let n=new Set;if(!t)return n;for(let r of t)y(e,r,n);return n}function y(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{y(e,t,n)}),n):n}async function te(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function b(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const x=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function S({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${x}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function C(e,t=`index.html`){let[,n]=[...(await s.default.readFile((0,o.join)(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function w(e){return`<link rel="stylesheet" href="${e}">`}function ne(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=T(e);r&&n.push(r)}}),n.join(``)}function T(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function E(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function D(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function re(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;E(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:D(e.headers)};return new Request(n.href,r)}async function ie(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=d.Readable.from(n);r.pipe(t),await(0,u.once)(r,`end`)}else t.end()}function O(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function k(e){return f.renderToString((0,n.jsx)(n.Fragment,{children:e}))}function A(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let j=null;function M(){return j||(j=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=require(`node:module`);return e(require(`url`).pathToFileURL(__filename).href)(`react-helmet-async`).HelmetProvider})(),j)}let N=null;async function ae(){return N||=await import(`react-router-dom`),N}var P=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,n)=>{let{routes:r,base:i}=this.context,{matchRoutes:a}=await ae(),o=re(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=a(t.r([...r],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},i);if(!l){n.statusCode=404,n.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){n.statusCode=404,n.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){n.statusCode=200,n.end(`There is no loader for the route: ${c}`);return}await ie(await F({loader:d,params:u.params,request:o,routeId:c}),n)},this.context=e}async render(e){let{base:r,routes:i,getStyleCollector:a,routerOptions:o}=this.context,s=t.s(e),c=s;if(r!==`/`){let e=t.s(r).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let l=`http://localhost${c}`,u=new Request(l),d=a?await a():null,f={},p=null,{StaticRouterProvider:m,createStaticHandler:h,createStaticRouter:g}=await ae(),_=this._dataRoutes??=t.r([...i],e=>e);this._staticHandler??=h(_,{basename:r});let{query:ee}=this._staticHandler,v=await ee(u),y=0;for(;v instanceof Response&&y<10;){let e=v.headers.get(`Location`);if(!e)break;let n;if(/^https?:\/\//i.test(e))try{let r=new URL(e);if(r.hostname===`localhost`||r.hostname===``)n=`http://localhost${t.s(r.pathname+r.search+r.hash)}`;else break}catch{break}else n=`http://localhost${t.s(e)}`;v=await ee(new Request(n)),y++}if(v instanceof Response)throw v;p=v;let te=g(_,p,{future:o.future}),b=M(),x=b;x&&typeof x==`function`&&(x.canUseDOM=!1);let S=(0,n.jsx)(b,{context:f,children:(0,n.jsx)(m,{router:te,context:p})});d&&(S=d.collect(S));let C=await k(S),{htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E}=A(C,f,d);return{appHTML:C,htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E,routerContext:p}}};async function F({loader:e,params:t,request:n,routeId:r}){let{json:i}=await ae(),a=await e({request:O(L(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return I(a)?a:i(a)}function I(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function L(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function oe(e){return new P(e)}var R=`0.3.1`;async function se(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&B(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function z(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:(0,o.join)(e.root,t))}const ce=/[:*?]/;function B(e){return e?ce.test(e):!1}const V=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),le=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function H(e){try{return p.default.statSync(e).size}catch{return 0}}async function ue(e,t){let n=(0,o.join)(e,`.vite`),r=(0,o.join)(e,`assets`),i={},a=(0,o.join)(n,`manifest.json`);p.default.existsSync(a)&&(i=JSON.parse(await p.default.readFileSync(a,`utf-8`)));let s=0,c=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=H((0,o.join)(e,n));s+=i;for(let t of r)c+=H((0,o.join)(e,t))}let l=0,u=0;if(p.default.existsSync(r)){let e=p.default.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=o.default.extname(t.name).toLowerCase(),n=(0,o.join)(r,t.name);V.has(e)?l+=H(n):le.has(e)&&u++}}let d=(0,o.join)(e,`index.html`),f=0,m=[];if(p.default.existsSync(d)){let e=H(d);f+=e,m.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=p.default.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=H((0,o.join)(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);f+=t,m.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:s,totalCSSBundleSize:c,totalImagesSize:l,totalHTMLSize:f,fontCount:u,pages:m}}function de(e,t){let n=o.default.resolve(e,`..`,`.boltdocs`,`reports`);p.default.existsSync(n)||p.default.mkdirSync(n,{recursive:!0});let r=(0,o.join)(n,`performance.json`);p.default.writeFileSync(r,JSON.stringify(t,null,2))}const fe=Number.parseInt(c.version)>=5?[`.vite`]:[];function pe(e){return Number.parseInt(c.version)>=8?{rolldownOptions:e}:{rollupOptions:e}}const U=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),me=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function he(e){let t=[];if(!s.default.existsSync(e))return t;let n=s.default.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>me.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();U.has(r)&&t.push((0,o.join)(n,e.name))}return t}let W=null,G=null;function ge(e,t,n,r){try{let n=[],i=(0,o.join)(e,t);s.default.existsSync(i)&&n.push(...he(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=(0,o.join)(e,t);s.default.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(W&&G===a)return W;let c=Array(n.length);for(let e=0;e<n.length;e++){let t=s.default.statSync(n[e]);c[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=(0,o.join)(r,`hash-meta.json`),t=(0,o.join)(r,`client-hash.txt`);try{if(s.default.existsSync(e)&&s.default.existsSync(t)){let r=JSON.parse(s.default.readFileSync(e,`utf-8`)),i=Math.max(...c.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=s.default.readFileSync(t,`utf-8`).trim();if(e)return W=e,G=a,e}}}catch{}}let u=l.default.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of c)u.update((0,o.relative)(e,t).replace(/\\/g,`/`)),u.update(n.toString()),u.update(r.toString());let d=u.digest(`hex`);if(W=d,G=a,r)try{let e=Math.max(...c.map(e=>e.mtime)),t=(0,o.join)(r,`hash-meta.json`);s.default.mkdirSync(r,{recursive:!0}),s.default.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return d}catch{return Math.random().toString(36).substring(2,12)}}function _e(e,n){return`static-loader-data${t.s(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${n}.json`}function ve(e,n=`/`){let r=t.s(e),i=r;if(n!==`/`){let e=t.s(n).replace(/\/$/,``);!r.startsWith(e+`/`)&&r!==e&&(i=`${e}${r}`)}return i!==`/`&&i.endsWith(`/`)?i.slice(0,-1):i}function ye(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function K(e={},n={}){let u=process.env.MODE||process.env.NODE_ENV||e.mode||`production`;u!==process.env.NODE_ENV&&(process.env.NODE_ENV=u);let d=await(0,c.resolveConfig)(n,`build`,u,u),f=process.cwd(),p=d.root||f,m=d.build.outDir||`dist`,h=d.base,g=Object.assign({},d.ssgOptions||{},e),_=performance.now(),{script:v=`sync`,mock:y=!1,htmlEntry:w=`index.html`,entry:T=await C(p,w),formatting:E=`none`,includedRoutes:D=ye,onBeforePageRender:re,onPageRendered:ie,onFinished:O,onStep:k,dirStyle:A=`flat`,includeAllRoutes:j=!1,format:M=`esm`,concurrency:N=20,rootContainerId:ae=`root`,routeToSourceFileMap:P={},cacheDir:F=`.boltdocs/build`}=g,I=g.beastiesOptions??{},L=g.turbo??!1,R=`docs`,ce=Object.values(P);if(ce.length>0){let e=ce[0],t=(0,o.relative)(p,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(R=t[0])}let B=(0,o.isAbsolute)(m)?m:(0,o.join)(p,m),V=(0,o.isAbsolute)(F)?F:(0,o.join)(p,F),le=ge(p,R,m,V),H=le.substring(0,12),U=(0,o.join)(V,`ssr`,L?`turbo-ssr`:H),me=(0,o.join)(V,`client-hash.txt`),he=(0,o.join)(V,`template-index.html`),W=!1;try{s.default.existsSync(me)&&s.default.existsSync(he)&&s.default.existsSync(B)&&s.default.existsSync((0,o.join)(B,`assets`))&&(await s.default.readFile(me,`utf-8`)).trim()===le&&(W=!0)}catch{}function G(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=(0,c.createLogger)(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||G(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{G(e)||Ce(e,t)},W)k?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await s.default.ensureDir(B),await s.default.copy(he,(0,o.join)(B,w));else{let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...pe({input:{app:(0,o.join)(p,w||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){m=e.build.outDir||`dist`}}]})),k?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await s.default.ensureDir(V),await s.default.copy((0,o.join)(B,w),he),await s.default.writeFile(me,le,`utf-8`)}let we=()=>{};if(y){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));we=e()}let q=await z(d,T);if((L||W)&&s.default.existsSync(U)&&s.default.readdirSync(U).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)k?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{s.default.existsSync(U)&&await s.default.remove(U),process.env.VITE_SSG=`true`;let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{ssr:q,manifest:!0,outDir:U,minify:!1,cssCodeSplit:!1,...pe({output:M===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode})),k?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Te=M===`esm`&&process.platform===`win32`?`file://`:``,Ee=M===`esm`?`.mjs`:`.cjs`,De=q.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),Oe=Te+(0,o.join)(U,(q.includes(`/`)||q.includes(`\\`)?q.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(Ee,``):De)+Ee).replace(/\\/g,`/`),ke=JSON.parse(await s.default.readFile((0,o.join)(U,...fe,`manifest.json`),`utf-8`)),Ae=typeof require<`u`?require:(0,i.createRequire)(require(`url`).pathToFileURL(__filename).href),{createRoot:je,includedRoutes:Me}=M===`esm`?await import(Oe):Ae(Oe),Ne=Me||D,{routes:Pe}=await je(!1),{paths:Fe}=await se(Pe),J=j?Fe:await Ne(Fe,Pe||[]);J=ye(J,Pe||[]),J=Array.from(new Set(J));let Y;L&&(Y=await b(),Y||(0,r.warn)(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ie=I!==!1&&!Y?await te(m,{publicPath:h,...I}):void 0,Le=``;if(Y){let e=(0,o.join)(B,`assets`);if(s.default.existsSync(e)){let t=s.default.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Le+=s.default.readFileSync((0,o.join)(e,n),`utf-8`)+`
|
|
2
2
|
`}}let Re=performance.now(),ze=JSON.parse(await s.default.readFile((0,o.join)(B,...fe,`ssr-manifest.json`),`utf-8`)),Be=JSON.parse(await s.default.readFile((0,o.join)(B,...fe,`manifest.json`),`utf-8`)),Ve=await s.default.readFile((0,o.join)(B,w),`utf-8`);s.default.rmSync((0,o.join)(B,w)),Ve=be(Ve,v);let He=(await import(`p-queue`)).default||await import(`p-queue`),Ue=new He({concurrency:N}),We=new He({concurrency:Math.min(a.default.cpus().length,4)}),Ge={},Ke=0,qe=new Map,Je=0,Ye=0,Xe=0,Ze=(0,o.join)(V,`ssg-cache.json`),X=(0,o.join)(V,`ssg-pages`),Z={};if(!L)try{s.default.existsSync(Ze)&&(Z=await s.default.readJson(Ze))}catch{}let Qe={...Z},Q=new Set;Q.add(X);for(let e of J){let t=A===`nested`?(0,o.join)(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;Q.add((0,o.join)(B,(0,o.dirname)(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;Q.add((0,o.join)(B,`static-loader-data`,(0,o.dirname)(n)))}Q.add((0,o.join)(B,`static-loader-data`)),await Promise.all([...Q].map(e=>s.default.ensureDir(e)));for(let e of J){let n=l.default.createHash(`md5`).update(e).digest(`hex`),i=(0,o.join)(X,`${n}.html`),a=(0,o.join)(X,`${n}.json`),c=`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`,u=A===`nested`?(0,o.join)(e.replace(/^\//g,``),`index.html`):c,d=(0,o.join)(B,u),f=t.s(e).replace(/\/$/,``),p=P[f]||P[e],m=!1,g=0;if(!L&&W&&p&&s.default.existsSync(p))try{if(g=Math.round(s.default.statSync(p).mtimeMs),s.default.existsSync(i)){let t=Z[f]||Z[e];t&&Math.round(t.mtime)===g&&(m=!0)}}catch{}if(m){Ue.add(async()=>{try{if(W)await s.default.copy(i,d);else{let e=await s.default.readFile(i,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${H}'`),await s.default.writeFile(d,e,`utf-8`)}let t=Z[f]||Z[e];if(t?.loaderDataFilePath&&s.default.existsSync(a)){let n=W?t.loaderDataFilePath:_e(e,H);await s.default.copy(a,(0,o.join)(B,n)),Ge[ve(e,h)]=n,Ke++}Ye++}catch(t){throw Error(`Error on cached page: ${e}\n${t.stack}`)}});continue}Ue.add(async()=>{try{let n=await je(!1,e),{base:c,routes:l,triggerOnSSRAppRendered:d,transformState:f=t.n,app:m,routerType:_}=n,v=await re?.(e,Ve,n)||Ve,y=`${t.c(c)}${t.a(e)}`,te=oe(n),b;if(!m&&_===`remix`){let t=qe.get(e);t?b=t:(b=await ee({routes:[...l],locationArg:y,base:c,serverManifest:ke,manifest:Be,ssrManifest:ze}),qe.set(e,b))}else b=new Set;let{appHTML:C,bodyAttributes:w,htmlAttributes:T,metaAttributes:D,styleTag:O,routerContext:k}=await te.render(e),A=k?.loaderData,j;if(A&&Object.keys(A).length>0){let t=_e(e,H);j=t,await s.default.writeFile((0,o.join)(B,t),JSON.stringify(A)),Ge[ve(e,h)]=t,Ke++}await d?.(e,C,n);let M=await S({rootContainerId:ae,appHTML:C,indexHTML:v,metaAttributes:D,bodyAttributes:w,htmlAttributes:T,initialState:null}),N=ne(b),P=M.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);N&&(P=P.replace(`<head>`,`<head>${N}`));let F=await ie?.(e,P,n)||P,I=``;if(A&&Object.keys(A).length>0){let t=JSON.stringify(A).replace(/</g,`\\u003c`);I=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${ve(e,h)}': ${t} };`}let R=``;if(k){let e={loaderData:k.loaderData??{},actionData:k.actionData??null,errors:k.errors??null};R=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let se=`<script>window.__VITE_REACT_SSG_HASH__ = '${H}';${I}${R}<\/script>`;if(F=F.replace(`<head>`,`<head>${se}`),F=F.replace(`<script>${x}<\/script>`,``),Y){try{Le&&(F=await Y.processHtml(F,Le))}catch(t){(0,r.warn)(`[zig-critters] Failed to inline CSS for "${e}": ${t instanceof Error?t.message:String(t)}`)}F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ie&&(F=await We.add(()=>Ie.process(F)),F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));O&&(F=F.replace(`<head>`,`<head>${O}`));let z=await xe(F,E);if(await s.default.writeFile((0,o.join)(B,u),z,`utf-8`),!L&&p&&s.default.existsSync(p)){await s.default.writeFile(i,z,`utf-8`);let n=t.s(e).replace(/\/$/,``),r=Math.round(g);A&&Object.keys(A).length>0&&j?(await s.default.writeFile(a,JSON.stringify(A),`utf-8`),Qe[n]={mtime:r,loaderDataFilePath:j}):Qe[n]={mtime:r}}Je++,Xe+=z.length}catch(t){throw Error(`Error on page: ${e}\n${t.stack}`)}})}await Ue.start().onIdle();let $e=Je+Ye,et=(Xe/1024/1024).toFixed(2),tt=0;if(!L)try{if(await s.default.ensureDir((0,o.dirname)(Ze)),await s.default.writeJson(Ze,Qe),s.default.existsSync(X)){let e=await s.default.readdir(X),t=new Set;for(let e of Object.keys(Qe)){let n=l.default.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}for(let n of e)(n.endsWith(`.html`)||n.endsWith(`.json`))&&(t.has(n)||(await s.default.remove((0,o.join)(X,n)),tt++))}}catch{}k?.({name:`Render pages`,duration:performance.now()-Re,success:!0,details:`${$e} pages (${Je} new, ${Ye} cached, ${et} MB)`,metrics:{renderedCount:Je,cachedCount:Ye,renderedSize:Xe,totalPages:$e,prunedCount:tt}});let nt=performance.now(),rt=JSON.stringify(Ge,null,0);await s.default.writeFile((0,o.join)(B,`static-loader-data-manifest-${H}.json`),rt),W||await s.default.remove((0,o.join)(V,`ssr`)),we();let it=d.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;it&&!it.disabled&&it.generateSW&&await it.generateSW();let at=Math.round(performance.now()-_),$=await ue(B,at);de(B,$),k?.({name:`Static loader data`,duration:performance.now()-nt,success:!0,details:`${Ke} loader data files`,metrics:{loaderDataFileCount:Ke}}),k?.({name:`Build metrics`,duration:0,success:!0,details:`Build time: ${(at/1e3).toFixed(1)}s, JS: ${($.totalJSBundleSize/1024).toFixed(0)} kB, CSS: ${($.totalCSSBundleSize/1024).toFixed(0)} kB`,metrics:{buildTime:at,totalPages:$.pages.length,jsSize:$.totalJSBundleSize,cssSize:$.totalCSSBundleSize}}),await O?.(m),setTimeout(()=>{(0,r.warn)(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function be(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function xe(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return(0,r.error)(`Error formatting html: ${t?.message}`),e}return e}function Se(e,t,n){if(e.url)try{let t=e.url,n=t.indexOf(`?`),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n):``;if(/%[0-9A-Fa-f]{2}/.test(r)){let t=decodeURI(r);if(t!==r){let n=t+i;e.url=n,e.originalUrl&&=n}}}catch{}n()}function Ce({template:e,ssrEntry:n,onBeforePageRender:i,entry:a,rootContainerId:o,onPageRendered:s}){return{name:`vite-react-ssg:dev-server`,configureServer(l){let u=async(u,d,f)=>{try{let r=u.originalUrl,f=await(await l.ssrLoadModule(n).then(e=>e.createRoot))(!1,r),p=oe(f),{app:m,base:h}=f,[g,_]=r.split(`?`),ee=new URLSearchParams(_);if(!m&&ee.has(`_data`))return p.handleLoader(u,d);let v=await l.transformIndexHtml(r,e),y=await i?.(r,v,f)||v,{appHTML:te,bodyAttributes:b,htmlAttributes:x,metaAttributes:C,styleTag:ne}=await p.render(t.o(g,h));C.push(ne);let T=await Promise.all([n,a].map(async e=>await l.moduleGraph.getModuleByUrl(e))),E=new Set,D=new Set,re=async e=>{if(!e||!e?.ssrTransformResult||D.has(e))return;D.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))E.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await l.moduleGraph.getModuleByUrl(e);t&&await re(t)}};await Promise.all(T.map(async e=>re(e)));let ie=[...E].map(e=>w(t.i(l.config.base,e)));C.push(...ie);let O=await S({rootContainerId:o,appHTML:te,indexHTML:y,metaAttributes:C,bodyAttributes:b,htmlAttributes:x,initialState:null}),k=await s?.(r,O,f)||O;d.statusCode=200,d.setHeader(`Content-Type`,`text/html`),(0,c.send)(u,d,k,`html`,{headers:`pluginContainer`in l?l.config.server.headers:l.config.preview.headers})}catch(e){l.ssrFixStacktrace(e),(0,r.error)(`SSR render error`,e),d.statusCode=500,d.end(e.stack)}};return l.middlewares.use(Se),()=>{l.middlewares.use(u)}}}}async function we(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await(0,c.resolveConfig)(e,`serve`,n,n),i=process.cwd(),a=r.root||i,s={...r.ssgOptions,...t},{htmlEntry:l=`index.html`,onBeforePageRender:u,onPageRendered:d,rootContainerId:f=`root`,mock:p=!1}=s,h=s.entry||await C(a,l),[g,_]=await Promise.all([z(r,h),m.default.readFile((0,o.join)(a,l),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,p){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));e()}return await(0,c.createServer)({...e,plugins:[...e.plugins??[],Ce({template:_,ssrEntry:g,onBeforePageRender:u,onPageRendered:d,entry:h,rootContainerId:f})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function q(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await we(t,e);return await r.listen(),Te(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){(0,r.error)(`failed to start server: ${e?.message??e}`),process.exit(1)}}function Te(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,i=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);i+=` ready in ${r.colors.reset(r.colors.bold(`${e}ms`))}`}n(`\n ${r.colors.cyan(` VITE-REACT-SSG v${R} `)}`,{clear:!e.config.logger.hasWarned}),n(`${r.colors.cyan(`\n VITE v${c.version}`)+r.colors.dim(i)}\n`),n(r.colors.green(` dev server running at:`)),e.printUrls()}exports.build=K,exports.createServer=we,exports.dev=q;
|
package/dist/node.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,c as t,i as n,n as r,o as i,r as a,s as o}from"./state-CkhLd6hN.mjs";import{createRequire as s}from"node:module";import{Fragment as c,jsx as l}from"react/jsx-runtime";import{colors as u,error as d,warn as f}from"@bdocs/dui";import p from"node:os";import m,{dirname as h,isAbsolute as g,join as _,relative as v}from"node:path";import y from"fs-extra";import{build as b,createLogger as x,createServer as S,mergeConfig as C,resolveConfig as w,send as T,version as E}from"vite";import D from"node:crypto";import{once as O}from"node:events";import{Readable as k}from"node:stream";import*as A from"react-dom/server";import j from"node:fs";import M from"node:fs/promises";var N=s(import.meta.url);const ee=/import\("([^)]+)"\)/g;let te=null;async function ne(){if(!te){let{matchRoutes:e}=await import(`react-router-dom`);te=e}return te}async function re({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await ne())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(ee);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=P(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function P(e,t){let n=new Set;if(!t)return n;for(let r of t)F(e,r,n);return n}function F(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{F(e,t,n)}),n):n}async function I(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function ie(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const ae=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function oe({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${ae}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function se(e,t=`index.html`){let[,n]=[...(await y.readFile(_(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function ce(e){return`<link rel="stylesheet" href="${e}">`}function le(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=L(e);r&&n.push(r)}}),n.join(``)}function L(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function ue(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function de(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function fe(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;ue(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:de(e.headers)};return new Request(n.href,r)}async function pe(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=k.from(n);r.pipe(t),await O(r,`end`)}else t.end()}function me(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function R(e){return A.renderToString(l(c,{children:e}))}function he(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let z=null;function B(){return z||(z=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=N(`node:module`);return e(import.meta.url)(`react-helmet-async`).HelmetProvider})(),z)}let V=null;async function H(){return V||=await import(`react-router-dom`),V}var U=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,t)=>{let{routes:n,base:r}=this.context,{matchRoutes:i}=await H(),o=fe(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=i(a([...n],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},r);if(!l){t.statusCode=404,t.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){t.statusCode=404,t.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){t.statusCode=200,t.end(`There is no loader for the route: ${c}`);return}await pe(await W({loader:d,params:u.params,request:o,routeId:c}),t)},this.context=e}async render(e){let{base:t,routes:n,getStyleCollector:r,routerOptions:i}=this.context,s=o(e),c=s;if(t!==`/`){let e=o(t).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let u=`http://localhost${c}`,d=new Request(u),f=r?await r():null,p={},m=null,{StaticRouterProvider:h,createStaticHandler:g,createStaticRouter:_}=await H(),v=this._dataRoutes??=a([...n],e=>e);this._staticHandler??=g(v,{basename:t});let{query:y}=this._staticHandler,b=await y(d),x=0;for(;b instanceof Response&&x<10;){let e=b.headers.get(`Location`);if(!e)break;let t;if(/^https?:\/\//i.test(e))try{let n=new URL(e);if(n.hostname===`localhost`||n.hostname===``)t=`http://localhost${o(n.pathname+n.search+n.hash)}`;else break}catch{break}else t=`http://localhost${o(e)}`;b=await y(new Request(t)),x++}if(b instanceof Response)throw b;m=b;let S=_(v,m,{future:i.future}),C=B(),w=C;w&&typeof w==`function`&&(w.canUseDOM=!1);let T=l(C,{context:p,children:l(h,{router:S,context:m})});f&&(T=f.collect(T));let E=await R(T),{htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A}=he(E,p,f);return{appHTML:E,htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A,routerContext:m}}};async function W({loader:e,params:t,request:n,routeId:r}){let{json:i}=await H(),a=await e({request:me(_e(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return ge(a)?a:i(a)}function ge(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function _e(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function ve(e){return new U(e)}var G=`0.3.0`;async function ye(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&K(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function be(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:_(e.root,t))}const xe=/[:*?]/;function K(e){return e?xe.test(e):!1}const Se=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),Ce=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function q(e){try{return j.statSync(e).size}catch{return 0}}async function we(e,t){let n=_(e,`.vite`),r=_(e,`assets`),i={},a=_(n,`manifest.json`);j.existsSync(a)&&(i=JSON.parse(await j.readFileSync(a,`utf-8`)));let o=0,s=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=q(_(e,n));o+=i;for(let t of r)s+=q(_(e,t))}let c=0,l=0;if(j.existsSync(r)){let e=j.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=m.extname(t.name).toLowerCase(),n=_(r,t.name);Se.has(e)?c+=q(n):Ce.has(e)&&l++}}let u=_(e,`index.html`),d=0,f=[];if(j.existsSync(u)){let e=q(u);d+=e,f.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=j.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=q(_(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);d+=t,f.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:o,totalCSSBundleSize:s,totalImagesSize:c,totalHTMLSize:d,fontCount:l,pages:f}}function Te(e,t){let n=m.resolve(e,`..`,`.boltdocs`,`reports`);j.existsSync(n)||j.mkdirSync(n,{recursive:!0});let r=_(n,`performance.json`);j.writeFileSync(r,JSON.stringify(t,null,2))}const Ee=Number.parseInt(E)>=5?[`.vite`]:[];function De(e){return Number.parseInt(E)>=8?{rolldownOptions:e}:{rollupOptions:e}}const J=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),Oe=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function ke(e){let t=[];if(!y.existsSync(e))return t;let n=y.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>Oe.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();J.has(r)&&t.push(_(n,e.name))}return t}let Ae=null,je=null;function Me(e,t,n,r){try{let n=[],i=_(e,t);y.existsSync(i)&&n.push(...ke(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=_(e,t);y.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(Ae&&je===a)return Ae;let o=Array(n.length);for(let e=0;e<n.length;e++){let t=y.statSync(n[e]);o[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=_(r,`hash-meta.json`),t=_(r,`client-hash.txt`);try{if(y.existsSync(e)&&y.existsSync(t)){let r=JSON.parse(y.readFileSync(e,`utf-8`)),i=Math.max(...o.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=y.readFileSync(t,`utf-8`).trim();if(e)return Ae=e,je=a,e}}}catch{}}let s=D.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of o)s.update(v(e,t).replace(/\\/g,`/`)),s.update(n.toString()),s.update(r.toString());let c=s.digest(`hex`);if(Ae=c,je=a,r)try{let e=Math.max(...o.map(e=>e.mtime)),t=_(r,`hash-meta.json`);y.mkdirSync(r,{recursive:!0}),y.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return c}catch{return Math.random().toString(36).substring(2,12)}}function Ne(e,t){return`static-loader-data${o(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${t}.json`}function Pe(e,t=`/`){let n=o(e),r=n;if(t!==`/`){let e=o(t).replace(/\/$/,``);!n.startsWith(e+`/`)&&n!==e&&(r=`${e}${n}`)}return r!==`/`&&r.endsWith(`/`)?r.slice(0,-1):r}function Fe(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function Ie(n={},i={}){let a=process.env.MODE||process.env.NODE_ENV||n.mode||`production`;a!==process.env.NODE_ENV&&(process.env.NODE_ENV=a);let c=await w(i,`build`,a,a),l=process.cwd(),u=c.root||l,d=c.build.outDir||`dist`,m=c.base,S=Object.assign({},c.ssgOptions||{},n),T=performance.now(),{script:E=`sync`,mock:O=!1,htmlEntry:k=`index.html`,entry:A=await se(u,k),formatting:j=`none`,includedRoutes:M=Fe,onBeforePageRender:ee,onPageRendered:te,onFinished:ne,onStep:P,dirStyle:F=`flat`,includeAllRoutes:ce=!1,format:L=`esm`,concurrency:ue=20,rootContainerId:de=`root`,routeToSourceFileMap:fe={},cacheDir:pe=`.boltdocs/build`}=S,me=S.beastiesOptions??{},R=S.turbo??!1,he=`docs`,z=Object.values(fe);if(z.length>0){let e=z[0],t=v(u,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(he=t[0])}let B=g(d)?d:_(u,d),V=g(pe)?pe:_(u,pe),H=Me(u,he,d,V),U=H.substring(0,12),W=_(V,`ssr`,R?`turbo-ssr`:U),ge=_(V,`client-hash.txt`),_e=_(V,`template-index.html`),G=!1;try{y.existsSync(ge)&&y.existsSync(_e)&&y.existsSync(B)&&y.existsSync(_(B,`assets`))&&(await y.readFile(ge,`utf-8`)).trim()===H&&(G=!0)}catch{}function xe(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=x(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||xe(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{xe(e)||Ce(e,t)},G)P?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await y.ensureDir(B),await y.copy(_e,_(B,k));else{let e=performance.now();await b(C(i,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...De({input:{app:_(u,k||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){d=e.build.outDir||`dist`}}]})),P?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await y.ensureDir(V),await y.copy(_(B,k),_e),await y.writeFile(ge,H,`utf-8`)}let q=()=>{};if(O){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);q=e()}let J=await be(c,A);if((R||G)&&y.existsSync(W)&&y.readdirSync(W).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)P?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{y.existsSync(W)&&await y.remove(W),process.env.VITE_SSG=`true`;let e=performance.now();await b(C(i,{logLevel:`warn`,build:{ssr:J,manifest:!0,outDir:W,minify:!1,cssCodeSplit:!1,...De({output:L===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode})),P?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Oe=L===`esm`&&process.platform===`win32`?`file://`:``,ke=L===`esm`?`.mjs`:`.cjs`,Ae=J.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),je=Oe+_(W,(J.includes(`/`)||J.includes(`\\`)?J.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(ke,``):Ae)+ke).replace(/\\/g,`/`),Ie=JSON.parse(await y.readFile(_(W,...Ee,`manifest.json`),`utf-8`)),ze=N===void 0?s(import.meta.url):N,{createRoot:Be,includedRoutes:Ve}=L===`esm`?await import(je):ze(je),He=Ve||M,{routes:Ue}=await Be(!1),{paths:We}=await ye(Ue),Y=ce?We:await He(We,Ue||[]);Y=Fe(Y,Ue||[]),Y=Array.from(new Set(Y));let X;R&&(X=await ie(),X||f(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ge=me!==!1&&!X?await I(d,{publicPath:m,...me}):void 0,Ke=``;if(X){let e=_(B,`assets`);if(y.existsSync(e)){let t=y.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Ke+=y.readFileSync(_(e,n),`utf-8`)+`
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,r as a,s as o}from"./state-CkhLd6hN.mjs";import{createRequire as s}from"node:module";import{Fragment as c,jsx as l}from"react/jsx-runtime";import{colors as u,error as d,warn as f}from"@bdocs/dui";import p from"node:os";import m,{dirname as h,isAbsolute as g,join as _,relative as v}from"node:path";import y from"fs-extra";import{build as b,createLogger as x,createServer as S,mergeConfig as C,resolveConfig as w,send as T,version as E}from"vite";import D from"node:crypto";import{once as O}from"node:events";import{Readable as k}from"node:stream";import*as A from"react-dom/server";import j from"node:fs";import M from"node:fs/promises";var N=s(import.meta.url);const ee=/import\("([^)]+)"\)/g;let te=null;async function ne(){if(!te){let{matchRoutes:e}=await import(`react-router-dom`);te=e}return te}async function re({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await ne())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(ee);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=P(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function P(e,t){let n=new Set;if(!t)return n;for(let r of t)F(e,r,n);return n}function F(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{F(e,t,n)}),n):n}async function I(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function ie(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const ae=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function oe({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${ae}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function se(e,t=`index.html`){let[,n]=[...(await y.readFile(_(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function ce(e){return`<link rel="stylesheet" href="${e}">`}function le(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=L(e);r&&n.push(r)}}),n.join(``)}function L(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function ue(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function de(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function fe(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;ue(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:de(e.headers)};return new Request(n.href,r)}async function pe(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=k.from(n);r.pipe(t),await O(r,`end`)}else t.end()}function me(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function R(e){return A.renderToString(l(c,{children:e}))}function he(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let z=null;function B(){return z||(z=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=N(`node:module`);return e(import.meta.url)(`react-helmet-async`).HelmetProvider})(),z)}let V=null;async function H(){return V||=await import(`react-router-dom`),V}var U=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,t)=>{let{routes:n,base:r}=this.context,{matchRoutes:i}=await H(),o=fe(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=i(a([...n],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},r);if(!l){t.statusCode=404,t.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){t.statusCode=404,t.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){t.statusCode=200,t.end(`There is no loader for the route: ${c}`);return}await pe(await W({loader:d,params:u.params,request:o,routeId:c}),t)},this.context=e}async render(e){let{base:t,routes:n,getStyleCollector:r,routerOptions:i}=this.context,s=o(e),c=s;if(t!==`/`){let e=o(t).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let u=`http://localhost${c}`,d=new Request(u),f=r?await r():null,p={},m=null,{StaticRouterProvider:h,createStaticHandler:g,createStaticRouter:_}=await H(),v=this._dataRoutes??=a([...n],e=>e);this._staticHandler??=g(v,{basename:t});let{query:y}=this._staticHandler,b=await y(d),x=0;for(;b instanceof Response&&x<10;){let e=b.headers.get(`Location`);if(!e)break;let t;if(/^https?:\/\//i.test(e))try{let n=new URL(e);if(n.hostname===`localhost`||n.hostname===``)t=`http://localhost${o(n.pathname+n.search+n.hash)}`;else break}catch{break}else t=`http://localhost${o(e)}`;b=await y(new Request(t)),x++}if(b instanceof Response)throw b;m=b;let S=_(v,m,{future:i.future}),C=B(),w=C;w&&typeof w==`function`&&(w.canUseDOM=!1);let T=l(C,{context:p,children:l(h,{router:S,context:m})});f&&(T=f.collect(T));let E=await R(T),{htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A}=he(E,p,f);return{appHTML:E,htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A,routerContext:m}}};async function W({loader:e,params:t,request:n,routeId:r}){let{json:i}=await H(),a=await e({request:me(_e(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return ge(a)?a:i(a)}function ge(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function _e(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function ve(e){return new U(e)}var G=`0.3.1`;async function ye(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&K(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function be(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:_(e.root,t))}const xe=/[:*?]/;function K(e){return e?xe.test(e):!1}const Se=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),Ce=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function q(e){try{return j.statSync(e).size}catch{return 0}}async function we(e,t){let n=_(e,`.vite`),r=_(e,`assets`),i={},a=_(n,`manifest.json`);j.existsSync(a)&&(i=JSON.parse(await j.readFileSync(a,`utf-8`)));let o=0,s=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=q(_(e,n));o+=i;for(let t of r)s+=q(_(e,t))}let c=0,l=0;if(j.existsSync(r)){let e=j.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=m.extname(t.name).toLowerCase(),n=_(r,t.name);Se.has(e)?c+=q(n):Ce.has(e)&&l++}}let u=_(e,`index.html`),d=0,f=[];if(j.existsSync(u)){let e=q(u);d+=e,f.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=j.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=q(_(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);d+=t,f.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:o,totalCSSBundleSize:s,totalImagesSize:c,totalHTMLSize:d,fontCount:l,pages:f}}function Te(e,t){let n=m.resolve(e,`..`,`.boltdocs`,`reports`);j.existsSync(n)||j.mkdirSync(n,{recursive:!0});let r=_(n,`performance.json`);j.writeFileSync(r,JSON.stringify(t,null,2))}const Ee=Number.parseInt(E)>=5?[`.vite`]:[];function De(e){return Number.parseInt(E)>=8?{rolldownOptions:e}:{rollupOptions:e}}const J=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),Oe=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function ke(e){let t=[];if(!y.existsSync(e))return t;let n=y.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>Oe.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();J.has(r)&&t.push(_(n,e.name))}return t}let Ae=null,je=null;function Me(e,t,n,r){try{let n=[],i=_(e,t);y.existsSync(i)&&n.push(...ke(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=_(e,t);y.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(Ae&&je===a)return Ae;let o=Array(n.length);for(let e=0;e<n.length;e++){let t=y.statSync(n[e]);o[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=_(r,`hash-meta.json`),t=_(r,`client-hash.txt`);try{if(y.existsSync(e)&&y.existsSync(t)){let r=JSON.parse(y.readFileSync(e,`utf-8`)),i=Math.max(...o.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=y.readFileSync(t,`utf-8`).trim();if(e)return Ae=e,je=a,e}}}catch{}}let s=D.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of o)s.update(v(e,t).replace(/\\/g,`/`)),s.update(n.toString()),s.update(r.toString());let c=s.digest(`hex`);if(Ae=c,je=a,r)try{let e=Math.max(...o.map(e=>e.mtime)),t=_(r,`hash-meta.json`);y.mkdirSync(r,{recursive:!0}),y.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return c}catch{return Math.random().toString(36).substring(2,12)}}function Ne(e,t){return`static-loader-data${o(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${t}.json`}function Pe(e,t=`/`){let n=o(e),r=n;if(t!==`/`){let e=o(t).replace(/\/$/,``);!n.startsWith(e+`/`)&&n!==e&&(r=`${e}${n}`)}return r!==`/`&&r.endsWith(`/`)?r.slice(0,-1):r}function Fe(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function Ie(n={},i={}){let a=process.env.MODE||process.env.NODE_ENV||n.mode||`production`;a!==process.env.NODE_ENV&&(process.env.NODE_ENV=a);let c=await w(i,`build`,a,a),l=process.cwd(),u=c.root||l,d=c.build.outDir||`dist`,m=c.base,S=Object.assign({},c.ssgOptions||{},n),T=performance.now(),{script:E=`sync`,mock:O=!1,htmlEntry:k=`index.html`,entry:A=await se(u,k),formatting:j=`none`,includedRoutes:M=Fe,onBeforePageRender:ee,onPageRendered:te,onFinished:ne,onStep:P,dirStyle:F=`flat`,includeAllRoutes:ce=!1,format:L=`esm`,concurrency:ue=20,rootContainerId:de=`root`,routeToSourceFileMap:fe={},cacheDir:pe=`.boltdocs/build`}=S,me=S.beastiesOptions??{},R=S.turbo??!1,he=`docs`,z=Object.values(fe);if(z.length>0){let e=z[0],t=v(u,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(he=t[0])}let B=g(d)?d:_(u,d),V=g(pe)?pe:_(u,pe),H=Me(u,he,d,V),U=H.substring(0,12),W=_(V,`ssr`,R?`turbo-ssr`:U),ge=_(V,`client-hash.txt`),_e=_(V,`template-index.html`),G=!1;try{y.existsSync(ge)&&y.existsSync(_e)&&y.existsSync(B)&&y.existsSync(_(B,`assets`))&&(await y.readFile(ge,`utf-8`)).trim()===H&&(G=!0)}catch{}function xe(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=x(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||xe(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{xe(e)||Ce(e,t)},G)P?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await y.ensureDir(B),await y.copy(_e,_(B,k));else{let e=performance.now();await b(C(i,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...De({input:{app:_(u,k||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){d=e.build.outDir||`dist`}}]})),P?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await y.ensureDir(V),await y.copy(_(B,k),_e),await y.writeFile(ge,H,`utf-8`)}let q=()=>{};if(O){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);q=e()}let J=await be(c,A);if((R||G)&&y.existsSync(W)&&y.readdirSync(W).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)P?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{y.existsSync(W)&&await y.remove(W),process.env.VITE_SSG=`true`;let e=performance.now();await b(C(i,{logLevel:`warn`,build:{ssr:J,manifest:!0,outDir:W,minify:!1,cssCodeSplit:!1,...De({output:L===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode})),P?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Oe=L===`esm`&&process.platform===`win32`?`file://`:``,ke=L===`esm`?`.mjs`:`.cjs`,Ae=J.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),je=Oe+_(W,(J.includes(`/`)||J.includes(`\\`)?J.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(ke,``):Ae)+ke).replace(/\\/g,`/`),Ie=JSON.parse(await y.readFile(_(W,...Ee,`manifest.json`),`utf-8`)),ze=N===void 0?s(import.meta.url):N,{createRoot:Be,includedRoutes:Ve}=L===`esm`?await import(je):ze(je),He=Ve||M,{routes:Ue}=await Be(!1),{paths:We}=await ye(Ue),Y=ce?We:await He(We,Ue||[]);Y=Fe(Y,Ue||[]),Y=Array.from(new Set(Y));let X;R&&(X=await ie(),X||f(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ge=me!==!1&&!X?await I(d,{publicPath:m,...me}):void 0,Ke=``;if(X){let e=_(B,`assets`);if(y.existsSync(e)){let t=y.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Ke+=y.readFileSync(_(e,n),`utf-8`)+`
|
|
2
2
|
`}}let qe=performance.now(),Je=JSON.parse(await y.readFile(_(B,...Ee,`ssr-manifest.json`),`utf-8`)),Ye=JSON.parse(await y.readFile(_(B,...Ee,`manifest.json`),`utf-8`)),Xe=await y.readFile(_(B,k),`utf-8`);y.rmSync(_(B,k)),Xe=Le(Xe,E);let Ze=(await import(`p-queue`)).default||await import(`p-queue`),Qe=new Ze({concurrency:ue}),$e=new Ze({concurrency:Math.min(p.cpus().length,4)}),et={},tt=0,nt=new Map,rt=0,it=0,at=0,ot=_(V,`ssg-cache.json`),Z=_(V,`ssg-pages`),Q={};if(!R)try{y.existsSync(ot)&&(Q=await y.readJson(ot))}catch{}let st={...Q},ct=new Set;ct.add(Z);for(let e of Y){let t=F===`nested`?_(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;ct.add(_(B,h(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;ct.add(_(B,`static-loader-data`,h(n)))}ct.add(_(B,`static-loader-data`)),await Promise.all([...ct].map(e=>y.ensureDir(e)));for(let n of Y){let i=D.createHash(`md5`).update(n).digest(`hex`),a=_(Z,`${i}.html`),s=_(Z,`${i}.json`),c=`${(n.endsWith(`/`)?`${n}index`:n).replace(/^\//g,``)}.html`,l=F===`nested`?_(n.replace(/^\//g,``),`index.html`):c,u=_(B,l),d=o(n).replace(/\/$/,``),p=fe[d]||fe[n],h=!1,g=0;if(!R&&G&&p&&y.existsSync(p))try{if(g=Math.round(y.statSync(p).mtimeMs),y.existsSync(a)){let e=Q[d]||Q[n];e&&Math.round(e.mtime)===g&&(h=!0)}}catch{}if(h){Qe.add(async()=>{try{if(G)await y.copy(a,u);else{let e=await y.readFile(a,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${U}'`),await y.writeFile(u,e,`utf-8`)}let e=Q[d]||Q[n];if(e?.loaderDataFilePath&&y.existsSync(s)){let t=G?e.loaderDataFilePath:Ne(n,U);await y.copy(s,_(B,t)),et[Pe(n,m)]=t,tt++}it++}catch(e){throw Error(`Error on cached page: ${n}\n${e.stack}`)}});continue}Qe.add(async()=>{try{let i=await Be(!1,n),{base:c,routes:u,triggerOnSSRAppRendered:d,transformState:h=r,app:v,routerType:b}=i,x=await ee?.(n,Xe,i)||Xe,S=`${t(c)}${e(n)}`,C=ve(i),w;if(!v&&b===`remix`){let e=nt.get(n);e?w=e:(w=await re({routes:[...u],locationArg:S,base:c,serverManifest:Ie,manifest:Ye,ssrManifest:Je}),nt.set(n,w))}else w=new Set;let{appHTML:T,bodyAttributes:E,htmlAttributes:D,metaAttributes:O,styleTag:k,routerContext:A}=await C.render(n),M=A?.loaderData,N;if(M&&Object.keys(M).length>0){let e=Ne(n,U);N=e,await y.writeFile(_(B,e),JSON.stringify(M)),et[Pe(n,m)]=e,tt++}await d?.(n,T,i);let ne=await oe({rootContainerId:de,appHTML:T,indexHTML:x,metaAttributes:O,bodyAttributes:E,htmlAttributes:D,initialState:null}),P=le(w),F=ne.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);P&&(F=F.replace(`<head>`,`<head>${P}`));let I=await te?.(n,F,i)||F,ie=``;if(M&&Object.keys(M).length>0){let e=JSON.stringify(M).replace(/</g,`\\u003c`);ie=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${Pe(n,m)}': ${e} };`}let se=``;if(A){let e={loaderData:A.loaderData??{},actionData:A.actionData??null,errors:A.errors??null};se=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let ce=`<script>window.__VITE_REACT_SSG_HASH__ = '${U}';${ie}${se}<\/script>`;if(I=I.replace(`<head>`,`<head>${ce}`),I=I.replace(`<script>${ae}<\/script>`,``),X){try{Ke&&(I=await X.processHtml(I,Ke))}catch(e){f(`[zig-critters] Failed to inline CSS for "${n}": ${e instanceof Error?e.message:String(e)}`)}I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ge&&(I=await $e.add(()=>Ge.process(I)),I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));k&&(I=I.replace(`<head>`,`<head>${k}`));let L=await Re(I,j);if(await y.writeFile(_(B,l),L,`utf-8`),!R&&p&&y.existsSync(p)){await y.writeFile(a,L,`utf-8`);let e=o(n).replace(/\/$/,``),t=Math.round(g);M&&Object.keys(M).length>0&&N?(await y.writeFile(s,JSON.stringify(M),`utf-8`),st[e]={mtime:t,loaderDataFilePath:N}):st[e]={mtime:t}}rt++,at+=L.length}catch(e){throw Error(`Error on page: ${n}\n${e.stack}`)}})}await Qe.start().onIdle();let lt=rt+it,ut=(at/1024/1024).toFixed(2),dt=0;if(!R)try{if(await y.ensureDir(h(ot)),await y.writeJson(ot,st),y.existsSync(Z)){let e=await y.readdir(Z),t=new Set;for(let e of Object.keys(st)){let n=D.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}for(let n of e)(n.endsWith(`.html`)||n.endsWith(`.json`))&&(t.has(n)||(await y.remove(_(Z,n)),dt++))}}catch{}P?.({name:`Render pages`,duration:performance.now()-qe,success:!0,details:`${lt} pages (${rt} new, ${it} cached, ${ut} MB)`,metrics:{renderedCount:rt,cachedCount:it,renderedSize:at,totalPages:lt,prunedCount:dt}});let ft=performance.now(),pt=JSON.stringify(et,null,0);await y.writeFile(_(B,`static-loader-data-manifest-${U}.json`),pt),G||await y.remove(_(V,`ssr`)),q();let mt=c.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;mt&&!mt.disabled&&mt.generateSW&&await mt.generateSW();let ht=Math.round(performance.now()-T),$=await we(B,ht);Te(B,$),P?.({name:`Static loader data`,duration:performance.now()-ft,success:!0,details:`${tt} loader data files`,metrics:{loaderDataFileCount:tt}}),P?.({name:`Build metrics`,duration:0,success:!0,details:`Build time: ${(ht/1e3).toFixed(1)}s, JS: ${($.totalJSBundleSize/1024).toFixed(0)} kB, CSS: ${($.totalCSSBundleSize/1024).toFixed(0)} kB`,metrics:{buildTime:ht,totalPages:$.pages.length,jsSize:$.totalJSBundleSize,cssSize:$.totalCSSBundleSize}}),await ne?.(d),setTimeout(()=>{f(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function Le(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function Re(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return d(`Error formatting html: ${t?.message}`),e}return e}function ze(e,t,n){if(e.url)try{let t=e.url,n=t.indexOf(`?`),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n):``;if(/%[0-9A-Fa-f]{2}/.test(r)){let t=decodeURI(r);if(t!==r){let n=t+i;e.url=n,e.originalUrl&&=n}}}catch{}n()}function Be({template:e,ssrEntry:t,onBeforePageRender:r,entry:a,rootContainerId:o,onPageRendered:s}){return{name:`vite-react-ssg:dev-server`,configureServer(c){let l=async(l,u,f)=>{try{let d=l.originalUrl,f=await(await c.ssrLoadModule(t).then(e=>e.createRoot))(!1,d),p=ve(f),{app:m,base:h}=f,[g,_]=d.split(`?`),v=new URLSearchParams(_);if(!m&&v.has(`_data`))return p.handleLoader(l,u);let y=await c.transformIndexHtml(d,e),b=await r?.(d,y,f)||y,{appHTML:x,bodyAttributes:S,htmlAttributes:C,metaAttributes:w,styleTag:E}=await p.render(i(g,h));w.push(E);let D=await Promise.all([t,a].map(async e=>await c.moduleGraph.getModuleByUrl(e))),O=new Set,k=new Set,A=async e=>{if(!e||!e?.ssrTransformResult||k.has(e))return;k.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))O.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await c.moduleGraph.getModuleByUrl(e);t&&await A(t)}};await Promise.all(D.map(async e=>A(e)));let j=[...O].map(e=>ce(n(c.config.base,e)));w.push(...j);let M=await oe({rootContainerId:o,appHTML:x,indexHTML:b,metaAttributes:w,bodyAttributes:S,htmlAttributes:C,initialState:null}),N=await s?.(d,M,f)||M;u.statusCode=200,u.setHeader(`Content-Type`,`text/html`),T(l,u,N,`html`,{headers:`pluginContainer`in c?c.config.server.headers:c.config.preview.headers})}catch(e){c.ssrFixStacktrace(e),d(`SSR render error`,e),u.statusCode=500,u.end(e.stack)}};return c.middlewares.use(ze),()=>{c.middlewares.use(l)}}}}async function Ve(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await w(e,`serve`,n,n),i=process.cwd(),a=r.root||i,o={...r.ssgOptions,...t},{htmlEntry:s=`index.html`,onBeforePageRender:c,onPageRendered:l,rootContainerId:u=`root`,mock:d=!1}=o,f=o.entry||await se(a,s),[p,m]=await Promise.all([be(r,f),M.readFile(_(a,s),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,d){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);e()}return await S({...e,plugins:[...e.plugins??[],Be({template:m,ssrEntry:p,onBeforePageRender:c,onPageRendered:l,entry:f,rootContainerId:u})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function He(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await Ve(t,e);return await r.listen(),Ue(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){d(`failed to start server: ${e?.message??e}`),process.exit(1)}}function Ue(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,r=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);r+=` ready in ${u.reset(u.bold(`${e}ms`))}`}n(`\n ${u.cyan(` VITE-REACT-SSG v${G} `)}`,{clear:!e.config.logger.hasWarned}),n(`${u.cyan(`\n VITE v${E}`)+u.dim(r)}\n`),n(u.green(` dev server running at:`)),e.printUrls()}export{Ie as build,Ve as createServer,He as dev};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bdocs/ssg",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.1",
|
|
5
5
|
"description": "A Vite plugin for static site generation (SSG) with React.",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"publishConfig": {
|
|
@@ -88,7 +88,9 @@
|
|
|
88
88
|
"jsdom": "^24.1.3",
|
|
89
89
|
"p-queue": "^9.1.2",
|
|
90
90
|
"react-helmet-async": "^2.0.1",
|
|
91
|
-
"yargs": "^17.7.2"
|
|
91
|
+
"yargs": "^17.7.2"
|
|
92
|
+
},
|
|
93
|
+
"optionalDependencies": {
|
|
92
94
|
"@bdocs/zig-critters": "0.2.0"
|
|
93
95
|
},
|
|
94
96
|
"devDependencies": {
|