@lomray/vite-ssr-boost 3.0.0-beta.2 → 3.0.0-beta.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "3.0.0-beta.2",
3
+ "version": "3.0.0-beta.4",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,2 +1,2 @@
1
- import n from"node:fs";import e from"node:path";import o from"node:process";import r from"../constants/plugin-name.js";const t=`${r}-handle-custom-entrypoint`,i=()=>o.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME,l=n=>{o.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME=n},s=(n,e=i())=>{if(!n.length||!e)return null;for(const o of n)if(o.name===e&&!o.serverFile)return o;return null};function u(o){const{entrypoint:i}=o;let l="",s="";return{name:t,enforce:"pre",apply:(n,{command:e,isSsrBuild:o})=>"build"===e&&!o&&Boolean(i),config(n){const{indexFile:o}=i,r=n.build??{},t=o?e.resolve(n.root??"",o):void 0;return{...n,build:{...r,rollupOptions:{...r.rollupOptions??{},input:t}}}},configResolved(n){const o=n.plugins.find((n=>n.name===r));l=e.resolve(n.root,n.build.outDir),s=o.pluginOptions.clientFile},transform(n,o){if(o.endsWith(".html")){const{clientFile:o}=i;if(o)return n.replace(e.basename(s),o)}return n},closeBundle(){const{indexFile:o}=i;if(!o)return;const r=e.resolve(l,e.basename(o));n.existsSync(r)&&n.renameSync(r,e.resolve(l,"index.html"))}}}export{u as ViteHandleCustomEntrypointPlugin,s as getCurrentEntrypoint,i as getCurrentEntrypointName,l as setCurrentEntrypointName};
1
+ import e from"node:fs";import n from"node:path";import r from"node:process";import o from"../constants/plugin-name.js";const t=`${o}-handle-custom-entrypoint`,i=()=>r.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME,l=e=>{r.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME=e},s=(e,n=i())=>{if(!e.length||!n)return null;for(const r of e)if(r.name===n&&!r.serverFile)return r;return null};function c(r){const{entrypoint:i}=r;let l="",s="";return{name:t,enforce:"pre",apply:(e,{isSsrBuild:n})=>!n&&Boolean(i),config(e){const{indexFile:r}=i,o=e.build??{},t=r?n.resolve(e.root??"",r):void 0;return{...e,build:{...o,rollupOptions:{...o.rollupOptions??{},input:t}}}},configResolved(e){const r=e.plugins.find((e=>e.name===o));l=n.resolve(e.root,e.build.outDir),s=r.pluginOptions.clientFile},transform(e,n){if(n.endsWith(".html")){const{clientFile:n}=i;if(n)return e.replace(s,n)}return e},transformIndexHtml(e,{originalUrl:n,server:r}){const{clientFile:o}=i;return o&&"serve"===r?.config.command&&n?.endsWith(".html")?e.replace(s,o):e},closeBundle(){const{indexFile:r}=i;if(!r)return;const o=n.resolve(l,n.basename(r));e.existsSync(o)&&e.renameSync(o,n.resolve(l,"index.html"))}}}export{c as ViteHandleCustomEntrypointPlugin,s as getCurrentEntrypoint,i as getCurrentEntrypointName,l as setCurrentEntrypointName};
2
2
  //# sourceMappingURL=handle-custom-entrypoint.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"handle-custom-entrypoint.js","sources":["../../src/plugins/handle-custom-entrypoint.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n entrypoint: IBuildEntrypoint;\n}\n\nconst pluginName = `${PLUGIN_NAME}-handle-custom-entrypoint`;\n\n/**\n * Get current entrypoint name\n */\nconst getCurrentEntrypointName = (): string | undefined =>\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME;\n\n/**\n * Set current entrypoint name\n */\nconst setCurrentEntrypointName = (name: string): void => {\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME = name;\n};\n\n/**\n * Find current entrypoint by env\n */\nconst getCurrentEntrypoint = (\n entrypoint: IBuildEntrypoint[],\n currentEntrypointName = getCurrentEntrypointName(),\n): IBuildEntrypoint | null => {\n if (!entrypoint.length || !currentEntrypointName) {\n return null;\n }\n\n for (const entry of entrypoint) {\n if (entry.name === currentEntrypointName && !entry.serverFile) {\n return entry;\n }\n }\n\n return null;\n};\n\n/**\n * Return custom entrypoint instead default (index.html).\n *\n * E.g. for build multiple entrypoint\n * @constructor\n */\nfunction ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin {\n const { entrypoint } = options;\n let outPath = '';\n let origClientFile = '';\n\n return {\n name: pluginName,\n enforce: 'pre',\n /**\n * Apply only on build but not for SSR and only for custom entrypoint\n */\n apply(_, { command, isSsrBuild }): boolean {\n return command === 'build' && !isSsrBuild && Boolean(entrypoint);\n },\n config(config) {\n const { indexFile } = entrypoint;\n const buildConfig = config.build ?? {};\n const indexFilePath = indexFile ? path.resolve(config.root ?? '', indexFile) : undefined;\n\n return {\n ...config,\n build: {\n ...buildConfig,\n rollupOptions: {\n ...(buildConfig.rollupOptions ?? {}),\n input: indexFilePath,\n },\n },\n };\n },\n configResolved(config) {\n const pluginConfig = config.plugins.find((plugin) => plugin.name === PLUGIN_NAME);\n\n outPath = path.resolve(config.root, config.build.outDir);\n // @ts-expect-error pluginOptions is custom param\n origClientFile = (pluginConfig.pluginOptions as Record<string, any>).clientFile as string;\n },\n transform(code, id): string {\n if (id.endsWith('.html')) {\n const { clientFile } = entrypoint;\n\n if (clientFile) {\n return code.replace(path.basename(origClientFile), clientFile);\n }\n }\n\n return code;\n },\n closeBundle() {\n const { indexFile } = entrypoint;\n\n if (!indexFile) {\n return;\n }\n\n const indexFilePath = path.resolve(outPath, path.basename(indexFile));\n\n if (fs.existsSync(indexFilePath)) {\n fs.renameSync(indexFilePath, path.resolve(outPath, 'index.html'));\n }\n },\n };\n}\n\nexport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n getCurrentEntrypointName,\n setCurrentEntrypointName,\n};\n"],"names":["pluginName","PLUGIN_NAME","getCurrentEntrypointName","process","env","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","setCurrentEntrypointName","name","getCurrentEntrypoint","entrypoint","currentEntrypointName","length","entry","serverFile","ViteHandleCustomEntrypointPlugin","options","outPath","origClientFile","enforce","apply","_","command","isSsrBuild","Boolean","config","indexFile","buildConfig","build","indexFilePath","path","resolve","root","undefined","rollupOptions","input","configResolved","pluginConfig","plugins","find","plugin","outDir","pluginOptions","clientFile","transform","code","id","endsWith","replace","basename","closeBundle","fs","existsSync","renameSync"],"mappings":"uHAWA,MAAMA,EAAa,GAAGC,6BAKhBC,EAA2B,IAC/BC,EAAQC,IAAIC,uCAKRC,EAA4BC,IAChCJ,EAAQC,IAAIC,uCAAyCE,CAAI,EAMrDC,EAAuB,CAC3BC,EACAC,EAAwBR,OAExB,IAAKO,EAAWE,SAAWD,EACzB,OAAO,KAGT,IAAK,MAAME,KAASH,EAClB,GAAIG,EAAML,OAASG,IAA0BE,EAAMC,WACjD,OAAOD,EAIX,OAAO,IAAI,EASb,SAASE,EAAiCC,GACxC,MAAMN,WAAEA,GAAeM,EACvB,IAAIC,EAAU,GACVC,EAAiB,GAErB,MAAO,CACLV,KAAMP,EACNkB,QAAS,MAITC,MAAK,CAACC,GAAGC,QAAEA,EAAOC,WAAEA,KACC,UAAZD,IAAwBC,GAAcC,QAAQd,GAEvDe,OAAOA,GACL,MAAMC,UAAEA,GAAchB,EAChBiB,EAAcF,EAAOG,OAAS,GAC9BC,EAAgBH,EAAYI,EAAKC,QAAQN,EAAOO,MAAQ,GAAIN,QAAaO,EAE/E,MAAO,IACFR,EACHG,MAAO,IACFD,EACHO,cAAe,IACTP,EAAYO,eAAiB,CAAE,EACnCC,MAAON,IAId,EACDO,eAAeX,GACb,MAAMY,EAAeZ,EAAOa,QAAQC,MAAMC,GAAWA,EAAOhC,OAASN,IAErEe,EAAUa,EAAKC,QAAQN,EAAOO,KAAMP,EAAOG,MAAMa,QAEjDvB,EAAkBmB,EAAaK,cAAsCC,UACtE,EACDC,UAAUC,EAAMC,GACd,GAAIA,EAAGC,SAAS,SAAU,CACxB,MAAMJ,WAAEA,GAAejC,EAEvB,GAAIiC,EACF,OAAOE,EAAKG,QAAQlB,EAAKmB,SAAS/B,GAAiByB,EAEtD,CAED,OAAOE,CACR,EACDK,cACE,MAAMxB,UAAEA,GAAchB,EAEtB,IAAKgB,EACH,OAGF,MAAMG,EAAgBC,EAAKC,QAAQd,EAASa,EAAKmB,SAASvB,IAEtDyB,EAAGC,WAAWvB,IAChBsB,EAAGE,WAAWxB,EAAeC,EAAKC,QAAQd,EAAS,cAEtD,EAEL"}
1
+ {"version":3,"file":"handle-custom-entrypoint.js","sources":["../../src/plugins/handle-custom-entrypoint.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n entrypoint: IBuildEntrypoint;\n}\n\nconst pluginName = `${PLUGIN_NAME}-handle-custom-entrypoint`;\n\n/**\n * Get current entrypoint name\n */\nconst getCurrentEntrypointName = (): string | undefined =>\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME;\n\n/**\n * Set current entrypoint name\n */\nconst setCurrentEntrypointName = (name: string): void => {\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME = name;\n};\n\n/**\n * Find current entrypoint by env\n */\nconst getCurrentEntrypoint = (\n entrypoint: IBuildEntrypoint[],\n currentEntrypointName = getCurrentEntrypointName(),\n): IBuildEntrypoint | null => {\n if (!entrypoint.length || !currentEntrypointName) {\n return null;\n }\n\n for (const entry of entrypoint) {\n if (entry.name === currentEntrypointName && !entry.serverFile) {\n return entry;\n }\n }\n\n return null;\n};\n\n/**\n * Return custom entrypoint instead default (index.html).\n *\n * E.g. for build multiple entrypoint\n * @constructor\n */\nfunction ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin {\n const { entrypoint } = options;\n let outPath = '';\n let origClientFile = '';\n\n return {\n name: pluginName,\n enforce: 'pre',\n /**\n * Apply only on build but not for SSR and only for custom entrypoint\n */\n apply(_, { isSsrBuild }): boolean {\n return !isSsrBuild && Boolean(entrypoint);\n },\n config(config) {\n const { indexFile } = entrypoint;\n const buildConfig = config.build ?? {};\n const indexFilePath = indexFile ? path.resolve(config.root ?? '', indexFile) : undefined;\n\n return {\n ...config,\n build: {\n ...buildConfig,\n rollupOptions: {\n ...(buildConfig.rollupOptions ?? {}),\n input: indexFilePath,\n },\n },\n };\n },\n configResolved(config) {\n const pluginConfig = config.plugins.find((plugin) => plugin.name === PLUGIN_NAME);\n\n outPath = path.resolve(config.root, config.build.outDir);\n // @ts-expect-error pluginOptions is custom param\n origClientFile = (pluginConfig.pluginOptions as Record<string, any>).clientFile as string;\n },\n transform(code, id): string {\n if (id.endsWith('.html')) {\n const { clientFile } = entrypoint;\n\n if (clientFile) {\n return code.replace(origClientFile, clientFile);\n }\n }\n\n return code;\n },\n /**\n * Development mode\n */\n transformIndexHtml(html, { originalUrl, server }): string {\n const { clientFile } = entrypoint;\n\n if (clientFile && server?.config.command === 'serve' && originalUrl?.endsWith('.html')) {\n return html.replace(origClientFile, clientFile);\n }\n\n return html;\n },\n closeBundle() {\n const { indexFile } = entrypoint;\n\n if (!indexFile) {\n return;\n }\n\n const indexFilePath = path.resolve(outPath, path.basename(indexFile));\n\n if (fs.existsSync(indexFilePath)) {\n fs.renameSync(indexFilePath, path.resolve(outPath, 'index.html'));\n }\n },\n };\n}\n\nexport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n getCurrentEntrypointName,\n setCurrentEntrypointName,\n};\n"],"names":["pluginName","PLUGIN_NAME","getCurrentEntrypointName","process","env","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","setCurrentEntrypointName","name","getCurrentEntrypoint","entrypoint","currentEntrypointName","length","entry","serverFile","ViteHandleCustomEntrypointPlugin","options","outPath","origClientFile","enforce","apply","_","isSsrBuild","Boolean","config","indexFile","buildConfig","build","indexFilePath","path","resolve","root","undefined","rollupOptions","input","configResolved","pluginConfig","plugins","find","plugin","outDir","pluginOptions","clientFile","transform","code","id","endsWith","replace","transformIndexHtml","html","originalUrl","server","command","closeBundle","basename","fs","existsSync","renameSync"],"mappings":"uHAWA,MAAMA,EAAa,GAAGC,6BAKhBC,EAA2B,IAC/BC,EAAQC,IAAIC,uCAKRC,EAA4BC,IAChCJ,EAAQC,IAAIC,uCAAyCE,CAAI,EAMrDC,EAAuB,CAC3BC,EACAC,EAAwBR,OAExB,IAAKO,EAAWE,SAAWD,EACzB,OAAO,KAGT,IAAK,MAAME,KAASH,EAClB,GAAIG,EAAML,OAASG,IAA0BE,EAAMC,WACjD,OAAOD,EAIX,OAAO,IAAI,EASb,SAASE,EAAiCC,GACxC,MAAMN,WAAEA,GAAeM,EACvB,IAAIC,EAAU,GACVC,EAAiB,GAErB,MAAO,CACLV,KAAMP,EACNkB,QAAS,MAITC,MAAK,CAACC,GAAGC,WAAEA,MACDA,GAAcC,QAAQb,GAEhCc,OAAOA,GACL,MAAMC,UAAEA,GAAcf,EAChBgB,EAAcF,EAAOG,OAAS,GAC9BC,EAAgBH,EAAYI,EAAKC,QAAQN,EAAOO,MAAQ,GAAIN,QAAaO,EAE/E,MAAO,IACFR,EACHG,MAAO,IACFD,EACHO,cAAe,IACTP,EAAYO,eAAiB,CAAE,EACnCC,MAAON,IAId,EACDO,eAAeX,GACb,MAAMY,EAAeZ,EAAOa,QAAQC,MAAMC,GAAWA,EAAO/B,OAASN,IAErEe,EAAUY,EAAKC,QAAQN,EAAOO,KAAMP,EAAOG,MAAMa,QAEjDtB,EAAkBkB,EAAaK,cAAsCC,UACtE,EACDC,UAAUC,EAAMC,GACd,GAAIA,EAAGC,SAAS,SAAU,CACxB,MAAMJ,WAAEA,GAAehC,EAEvB,GAAIgC,EACF,OAAOE,EAAKG,QAAQ7B,EAAgBwB,EAEvC,CAED,OAAOE,CACR,EAIDI,mBAAmBC,GAAMC,YAAEA,EAAWC,OAAEA,IACtC,MAAMT,WAAEA,GAAehC,EAEvB,OAAIgC,GAAyC,UAA3BS,GAAQ3B,OAAO4B,SAAuBF,GAAaJ,SAAS,SACrEG,EAAKF,QAAQ7B,EAAgBwB,GAG/BO,CACR,EACDI,cACE,MAAM5B,UAAEA,GAAcf,EAEtB,IAAKe,EACH,OAGF,MAAMG,EAAgBC,EAAKC,QAAQb,EAASY,EAAKyB,SAAS7B,IAEtD8B,EAAGC,WAAW5B,IAChB2B,EAAGE,WAAW7B,EAAeC,EAAKC,QAAQb,EAAS,cAEtD,EAEL"}
@@ -1,2 +1,2 @@
1
- import t from"fs";import e from"node:process";import{pathToFileURL as r}from"node:url";import i from"path";import o from"chalk";import s from"./server-api.js";class n{config;serverApi;entrypoint;onServerCreated;html;middlewaresConfigs;constructor(t,e){this.config=t,this.serverApi=e??new s}static init(t,e){return new n(t,e)}async loadEntrypoint(t=!0){if(this.entrypoint&&this.config.isProd)return this.entrypoint;const{root:s,isProd:n,serverFile:a}=this.config.getParams(),l=i.resolve(`${s}/${a}`);let d;try{d=n?(await import(r(l).toString())).default:(await this.config.getVite().ssrLoadModule(l,{fixStacktrace:!0})).default}catch(t){if(t instanceof Error&&t.message.includes("Cannot find module")&&t.message.includes("/build/"))return this.config.getLogger().error(o.red(`Before starting the server, you need to create a build: ${o.yellow("ssr-boost build")} or provide path to build dir: ${o.yellow("ssr-boost start --build-dir build")}`)),e.exit(1);throw t}!t&&d.init&&delete d.init;const{render:c,init:g,routes:h,abortDelay:f,loggerProd:p,loggerDev:m,middlewares:u}=d;this.middlewaresConfigs=u,p&&n?this.config.setLogger(p):m&&!n&&this.config.setLogger(m);const{onServerCreated:y,...w}=await(g?.({config:this.config}))??{};return this.entrypoint={render:c,routes:h,abortDelay:f,...w},this.onServerCreated=y,this.entrypoint}async loadHtml(e){const{isProd:r,root:o,indexFile:s}=this.config.getParams();this.html&&r||(this.html=t.readFileSync(i.resolve(`${o}/${s}`),"utf-8"));let n=this.html;return r||(n=(await this.config.getVite().transformIndexHtml(e.originalUrl,this.html)).replace(/(<script.+)(>[\s\S]+injectIntoGlobalHook.+)/,"$1async$2")),n.split("\x3c!--ssr-outlet--\x3e")}async onAppCreated(){return await this.loadEntrypoint(),await(this.onServerCreated?.(this.config.getApp(),this.serverApi)),this}getMiddlewaresConfig(){const{compression:t,expressStatic:e}=this.middlewaresConfigs??{};return{compression:!1!==t&&{...t??{}},expressStatic:!1!==e&&{...e??{}}}}}export{n as default};
1
+ import t from"fs";import e from"node:process";import{pathToFileURL as r}from"node:url";import i from"path";import o from"chalk";import s from"./server-api.js";class n{config;serverApi;entrypoint;onServerCreated;html;middlewaresConfigs;constructor(t,e){this.config=t,this.serverApi=e??new s}static init(t,e){return new n(t,e)}async loadEntrypoint(t=!0){if(this.entrypoint&&this.config.isProd)return this.entrypoint;const{root:s,isProd:n,serverFile:a}=this.config.getParams(),l=i.resolve(`${s}/${a}`);let d;try{d=n?(await import(r(l).toString())).default:(await this.config.getVite().ssrLoadModule(l,{fixStacktrace:!0})).default}catch(t){if(t instanceof Error&&t.message.includes("Cannot find module")&&t.message.includes("/build/"))return this.config.getLogger().error(o.red(`Before starting the server, you need to create a build: ${o.yellow("ssr-boost build")} or provide path to build dir: ${o.yellow("ssr-boost start --build-dir build")}`)),e.exit(1);throw t}!t&&d.init&&delete d.init;const{render:c,init:g,routes:h,abortDelay:f,loggerProd:p,loggerDev:m,middlewares:u}=d;this.middlewaresConfigs=u,p&&n?this.config.setLogger(p):m&&!n&&this.config.setLogger(m);const{onServerCreated:y,...w}=await(g?.({config:this.config}))??{};return this.entrypoint={render:c,routes:h,abortDelay:f,...w},this.onServerCreated=y,this.entrypoint}async loadHtml(e){const{isProd:r,root:o,indexFile:s}=this.config.getParams();this.html&&r||(this.html=t.readFileSync(i.resolve(`${o}/${s}`),"utf-8"));let n=this.html;return r||(n=(await this.config.getVite().transformIndexHtml(e.originalUrl,this.html,s)).replace(/(<script.+)(>[\s\S]+injectIntoGlobalHook.+)/,"$1async$2")),n.split("\x3c!--ssr-outlet--\x3e")}async onAppCreated(){return await this.loadEntrypoint(),await(this.onServerCreated?.(this.config.getApp(),this.serverApi)),this}getMiddlewaresConfig(){const{compression:t,expressStatic:e}=this.middlewaresConfigs??{};return{compression:!1!==t&&{...t??{}},expressStatic:!1!==e&&{...e??{}}}}}export{n as default};
2
2
  //# sourceMappingURL=prepare-server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepare-server.js","sources":["../../src/services/prepare-server.ts"],"sourcesContent":["import fs from 'fs';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport path from 'path';\nimport chalk from 'chalk';\nimport type { Request } from 'express';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IEntrypointOptions, IPrepareRenderOut } from '@node/entry';\nimport type { TRender } from '@node/render';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrepareServerEntrypointLoadOut<TAppProps = Record<string, any>> {\n render: TRender;\n routes: TRouteObject[];\n abortDelay?: number;\n onRequest?: IEntrypointOptions<TAppProps>['onRequest'];\n onRouterReady?: IEntrypointOptions<TAppProps>['onRouterReady'];\n onShellReady?: IEntrypointOptions<TAppProps>['onShellReady'];\n onShellError?: IEntrypointOptions<TAppProps>['onShellError'];\n onResponse?: IEntrypointOptions<TAppProps>['onResponse'];\n onError?: IEntrypointOptions<TAppProps>['onError'];\n getState?: IEntrypointOptions<TAppProps>['getState'];\n}\n\n/**\n * Load server entrypoint and template\n * DEV MODE: refresh entrypoint and template\n */\nclass PrepareServer {\n /**\n * Server configuration\n */\n protected readonly config: ServerConfig;\n\n /**\n * Server API\n */\n protected readonly serverApi: ServerApi;\n\n /**\n * Entrypoint resolved params\n */\n protected entrypoint?: IPrepareServerEntrypointLoadOut;\n\n /**\n * Hook which calls after express server created\n */\n protected onServerCreated?: IEntrypointOptions['onServerCreated'];\n\n /**\n * Html shell\n */\n protected html: string;\n\n /**\n * Middlewares configs\n */\n protected middlewaresConfigs?: IPrepareRenderOut['middlewares'];\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, serverApi?: ServerApi) {\n this.config = config;\n this.serverApi = serverApi ?? new ServerApi();\n }\n\n /**\n * Init service\n */\n public static init(config: ServerConfig, serverApi?: ServerApi): PrepareServer {\n return new PrepareServer(config, serverApi);\n }\n\n /**\n * Resolve and return entrypoint params\n */\n public async loadEntrypoint(shouldInit = true): Promise<IPrepareServerEntrypointLoadOut> {\n // load server entrypoint each time only in development mode (for fast refresh)\n if (this.entrypoint && this.config.isProd) {\n return this.entrypoint;\n }\n\n const { root, isProd, serverFile } = this.config.getParams();\n const entrypointPath = path.resolve(`${root}/${serverFile}`);\n\n let resolvedEntrypoint: IPrepareRenderOut;\n\n try {\n if (!isProd) {\n resolvedEntrypoint = (\n await this.config.getVite()!.ssrLoadModule(entrypointPath, {\n fixStacktrace: true,\n })\n ).default as IPrepareRenderOut;\n } else {\n resolvedEntrypoint = (\n (await import(pathToFileURL(entrypointPath).toString())) as { default: IPrepareRenderOut }\n ).default;\n }\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes('Cannot find module') &&\n e.message.includes('/build/')\n ) {\n this.config\n .getLogger()\n .error(\n chalk.red(\n `Before starting the server, you need to create a build: ${chalk.yellow(\n 'ssr-boost build',\n )} or provide path to build dir: ${chalk.yellow(\n 'ssr-boost start --build-dir build',\n )}`,\n ),\n );\n\n return process.exit(1);\n }\n\n throw e;\n }\n\n if (!shouldInit && resolvedEntrypoint.init) {\n delete resolvedEntrypoint.init;\n }\n\n const { render, init, routes, abortDelay, loggerProd, loggerDev, middlewares } =\n resolvedEntrypoint;\n\n this.middlewaresConfigs = middlewares;\n\n if (loggerProd && isProd) {\n this.config.setLogger(loggerProd);\n } else if (loggerDev && !isProd) {\n this.config.setLogger(loggerDev);\n }\n\n const { onServerCreated, ...renderParams } =\n (await init?.({\n config: this.config,\n })) ?? {};\n\n this.entrypoint = {\n render,\n routes,\n abortDelay,\n ...renderParams,\n };\n this.onServerCreated = onServerCreated;\n\n return this.entrypoint;\n }\n\n /**\n * Load and return html shell\n */\n public async loadHtml(req: Request): Promise<[string, string]> {\n const { isProd, root, indexFile } = this.config.getParams();\n\n if (!this.html || !isProd) {\n this.html = fs.readFileSync(path.resolve(`${root}/${indexFile}`), 'utf-8');\n }\n\n let modifiedHtml = this.html;\n\n if (!isProd) {\n // Apply Vite HTML transforms. This injects the Vite HMR client,\n // and also applies HTML transforms from Vite plugins, e.g. global\n // preambles from @vitejs/plugin-react\n modifiedHtml = (await this.config.getVite()!.transformIndexHtml(req.originalUrl, this.html))\n // Make vite script 'async'\n .replace(/(<script.+)(>[\\s\\S]+injectIntoGlobalHook.+)/, '$1async$2');\n }\n\n return modifiedHtml.split('<!--ssr-outlet-->') as [string, string];\n }\n\n /**\n * Run server created hook\n */\n public async onAppCreated(): Promise<PrepareServer> {\n await this.loadEntrypoint();\n await this.onServerCreated?.(this.config.getApp()!, this.serverApi);\n\n return this;\n }\n\n /**\n * Return SSR express middlewares configs\n */\n public getMiddlewaresConfig(): NonNullable<PrepareServer['middlewaresConfigs']> {\n const { compression, expressStatic } = this.middlewaresConfigs ?? {};\n\n return {\n compression:\n compression !== false\n ? {\n ...(compression ?? {}),\n }\n : false,\n expressStatic:\n expressStatic !== false\n ? {\n ...(expressStatic ?? {}),\n }\n : false,\n };\n }\n}\n\nexport default PrepareServer;\n"],"names":["PrepareServer","config","serverApi","entrypoint","onServerCreated","html","middlewaresConfigs","constructor","this","ServerApi","static","async","shouldInit","isProd","root","serverFile","getParams","entrypointPath","path","resolve","resolvedEntrypoint","import","pathToFileURL","toString","default","getVite","ssrLoadModule","fixStacktrace","e","Error","message","includes","getLogger","error","chalk","red","yellow","process","exit","init","render","routes","abortDelay","loggerProd","loggerDev","middlewares","setLogger","renderParams","req","indexFile","fs","readFileSync","modifiedHtml","transformIndexHtml","originalUrl","replace","split","loadEntrypoint","getApp","getMiddlewaresConfig","compression","expressStatic"],"mappings":"+JA6BA,MAAMA,EAIeC,OAKAC,UAKTC,WAKAC,gBAKAC,KAKAC,mBAKVC,YAAsBN,EAAsBC,GAC1CM,KAAKP,OAASA,EACdO,KAAKN,UAAYA,GAAa,IAAIO,CACnC,CAKMC,YAAYT,EAAsBC,GACvC,OAAO,IAAIF,EAAcC,EAAQC,EAClC,CAKMS,qBAAqBC,GAAa,GAEvC,GAAIJ,KAAKL,YAAcK,KAAKP,OAAOY,OACjC,OAAOL,KAAKL,WAGd,MAAMW,KAAEA,EAAID,OAAEA,EAAME,WAAEA,GAAeP,KAAKP,OAAOe,YAC3CC,EAAiBC,EAAKC,QAAQ,GAAGL,KAAQC,KAE/C,IAAIK,EAEJ,IAQIA,EAPGP,SAQMQ,OAAOC,EAAcL,GAAgBM,aAC5CC,eAPMhB,KAAKP,OAAOwB,UAAWC,cAAcT,EAAgB,CACzDU,eAAe,KAEjBH,OAML,CAAC,MAAOI,GACP,GACEA,aAAaC,OACbD,EAAEE,QAAQC,SAAS,uBACnBH,EAAEE,QAAQC,SAAS,WAcnB,OAZAvB,KAAKP,OACF+B,YACAC,MACCC,EAAMC,IACJ,2DAA2DD,EAAME,OAC/D,oDACiCF,EAAME,OACvC,yCAKDC,EAAQC,KAAK,GAGtB,MAAMV,CACP,EAEIhB,GAAcQ,EAAmBmB,aAC7BnB,EAAmBmB,KAG5B,MAAMC,OAAEA,EAAMD,KAAEA,EAAIE,OAAEA,EAAMC,WAAEA,EAAUC,WAAEA,EAAUC,UAAEA,EAASC,YAAEA,GAC/DzB,EAEFZ,KAAKF,mBAAqBuC,EAEtBF,GAAc9B,EAChBL,KAAKP,OAAO6C,UAAUH,GACbC,IAAc/B,GACvBL,KAAKP,OAAO6C,UAAUF,GAGxB,MAAMxC,gBAAEA,KAAoB2C,SACnBR,IAAO,CACZtC,OAAQO,KAAKP,WACR,CAAA,EAUT,OARAO,KAAKL,WAAa,CAChBqC,SACAC,SACAC,gBACGK,GAELvC,KAAKJ,gBAAkBA,EAEhBI,KAAKL,UACb,CAKMQ,eAAeqC,GACpB,MAAMnC,OAAEA,EAAMC,KAAEA,EAAImC,UAAEA,GAAczC,KAAKP,OAAOe,YAE3CR,KAAKH,MAASQ,IACjBL,KAAKH,KAAO6C,EAAGC,aAAajC,EAAKC,QAAQ,GAAGL,KAAQmC,KAAc,UAGpE,IAAIG,EAAe5C,KAAKH,KAWxB,OATKQ,IAIHuC,SAAsB5C,KAAKP,OAAOwB,UAAW4B,mBAAmBL,EAAIM,YAAa9C,KAAKH,OAEnFkD,QAAQ,8CAA+C,cAGrDH,EAAaI,MAAM,0BAC3B,CAKM7C,qBAIL,aAHMH,KAAKiD,uBACLjD,KAAKJ,kBAAkBI,KAAKP,OAAOyD,SAAWlD,KAAKN,YAElDM,IACR,CAKMmD,uBACL,MAAMC,YAAEA,EAAWC,cAAEA,GAAkBrD,KAAKF,oBAAsB,CAAA,EAElE,MAAO,CACLsD,aACkB,IAAhBA,GACI,IACMA,GAAe,CAAE,GAG7BC,eACoB,IAAlBA,GACI,IACMA,GAAiB,CAAE,GAIlC"}
1
+ {"version":3,"file":"prepare-server.js","sources":["../../src/services/prepare-server.ts"],"sourcesContent":["import fs from 'fs';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport path from 'path';\nimport chalk from 'chalk';\nimport type { Request } from 'express';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IEntrypointOptions, IPrepareRenderOut } from '@node/entry';\nimport type { TRender } from '@node/render';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrepareServerEntrypointLoadOut<TAppProps = Record<string, any>> {\n render: TRender;\n routes: TRouteObject[];\n abortDelay?: number;\n onRequest?: IEntrypointOptions<TAppProps>['onRequest'];\n onRouterReady?: IEntrypointOptions<TAppProps>['onRouterReady'];\n onShellReady?: IEntrypointOptions<TAppProps>['onShellReady'];\n onShellError?: IEntrypointOptions<TAppProps>['onShellError'];\n onResponse?: IEntrypointOptions<TAppProps>['onResponse'];\n onError?: IEntrypointOptions<TAppProps>['onError'];\n getState?: IEntrypointOptions<TAppProps>['getState'];\n}\n\n/**\n * Load server entrypoint and template\n * DEV MODE: refresh entrypoint and template\n */\nclass PrepareServer {\n /**\n * Server configuration\n */\n protected readonly config: ServerConfig;\n\n /**\n * Server API\n */\n protected readonly serverApi: ServerApi;\n\n /**\n * Entrypoint resolved params\n */\n protected entrypoint?: IPrepareServerEntrypointLoadOut;\n\n /**\n * Hook which calls after express server created\n */\n protected onServerCreated?: IEntrypointOptions['onServerCreated'];\n\n /**\n * Html shell\n */\n protected html: string;\n\n /**\n * Middlewares configs\n */\n protected middlewaresConfigs?: IPrepareRenderOut['middlewares'];\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, serverApi?: ServerApi) {\n this.config = config;\n this.serverApi = serverApi ?? new ServerApi();\n }\n\n /**\n * Init service\n */\n public static init(config: ServerConfig, serverApi?: ServerApi): PrepareServer {\n return new PrepareServer(config, serverApi);\n }\n\n /**\n * Resolve and return entrypoint params\n */\n public async loadEntrypoint(shouldInit = true): Promise<IPrepareServerEntrypointLoadOut> {\n // load server entrypoint each time only in development mode (for fast refresh)\n if (this.entrypoint && this.config.isProd) {\n return this.entrypoint;\n }\n\n const { root, isProd, serverFile } = this.config.getParams();\n const entrypointPath = path.resolve(`${root}/${serverFile}`);\n\n let resolvedEntrypoint: IPrepareRenderOut;\n\n try {\n if (!isProd) {\n resolvedEntrypoint = (\n await this.config.getVite()!.ssrLoadModule(entrypointPath, {\n fixStacktrace: true,\n })\n ).default as IPrepareRenderOut;\n } else {\n resolvedEntrypoint = (\n (await import(pathToFileURL(entrypointPath).toString())) as { default: IPrepareRenderOut }\n ).default;\n }\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes('Cannot find module') &&\n e.message.includes('/build/')\n ) {\n this.config\n .getLogger()\n .error(\n chalk.red(\n `Before starting the server, you need to create a build: ${chalk.yellow(\n 'ssr-boost build',\n )} or provide path to build dir: ${chalk.yellow(\n 'ssr-boost start --build-dir build',\n )}`,\n ),\n );\n\n return process.exit(1);\n }\n\n throw e;\n }\n\n if (!shouldInit && resolvedEntrypoint.init) {\n delete resolvedEntrypoint.init;\n }\n\n const { render, init, routes, abortDelay, loggerProd, loggerDev, middlewares } =\n resolvedEntrypoint;\n\n this.middlewaresConfigs = middlewares;\n\n if (loggerProd && isProd) {\n this.config.setLogger(loggerProd);\n } else if (loggerDev && !isProd) {\n this.config.setLogger(loggerDev);\n }\n\n const { onServerCreated, ...renderParams } =\n (await init?.({\n config: this.config,\n })) ?? {};\n\n this.entrypoint = {\n render,\n routes,\n abortDelay,\n ...renderParams,\n };\n this.onServerCreated = onServerCreated;\n\n return this.entrypoint;\n }\n\n /**\n * Load and return html shell\n */\n public async loadHtml(req: Request): Promise<[string, string]> {\n const { isProd, root, indexFile } = this.config.getParams();\n\n if (!this.html || !isProd) {\n this.html = fs.readFileSync(path.resolve(`${root}/${indexFile}`), 'utf-8');\n }\n\n let modifiedHtml = this.html;\n\n if (!isProd) {\n // Apply Vite HTML transforms. This injects the Vite HMR client,\n // and also applies HTML transforms from Vite plugins, e.g. global\n // preambles from @vitejs/plugin-react\n modifiedHtml = (\n await this.config.getVite()!.transformIndexHtml(req.originalUrl, this.html, indexFile)\n )\n // Make vite script 'async'\n .replace(/(<script.+)(>[\\s\\S]+injectIntoGlobalHook.+)/, '$1async$2');\n }\n\n return modifiedHtml.split('<!--ssr-outlet-->') as [string, string];\n }\n\n /**\n * Run server created hook\n */\n public async onAppCreated(): Promise<PrepareServer> {\n await this.loadEntrypoint();\n await this.onServerCreated?.(this.config.getApp()!, this.serverApi);\n\n return this;\n }\n\n /**\n * Return SSR express middlewares configs\n */\n public getMiddlewaresConfig(): NonNullable<PrepareServer['middlewaresConfigs']> {\n const { compression, expressStatic } = this.middlewaresConfigs ?? {};\n\n return {\n compression:\n compression !== false\n ? {\n ...(compression ?? {}),\n }\n : false,\n expressStatic:\n expressStatic !== false\n ? {\n ...(expressStatic ?? {}),\n }\n : false,\n };\n }\n}\n\nexport default PrepareServer;\n"],"names":["PrepareServer","config","serverApi","entrypoint","onServerCreated","html","middlewaresConfigs","constructor","this","ServerApi","static","async","shouldInit","isProd","root","serverFile","getParams","entrypointPath","path","resolve","resolvedEntrypoint","import","pathToFileURL","toString","default","getVite","ssrLoadModule","fixStacktrace","e","Error","message","includes","getLogger","error","chalk","red","yellow","process","exit","init","render","routes","abortDelay","loggerProd","loggerDev","middlewares","setLogger","renderParams","req","indexFile","fs","readFileSync","modifiedHtml","transformIndexHtml","originalUrl","replace","split","loadEntrypoint","getApp","getMiddlewaresConfig","compression","expressStatic"],"mappings":"+JA6BA,MAAMA,EAIeC,OAKAC,UAKTC,WAKAC,gBAKAC,KAKAC,mBAKVC,YAAsBN,EAAsBC,GAC1CM,KAAKP,OAASA,EACdO,KAAKN,UAAYA,GAAa,IAAIO,CACnC,CAKMC,YAAYT,EAAsBC,GACvC,OAAO,IAAIF,EAAcC,EAAQC,EAClC,CAKMS,qBAAqBC,GAAa,GAEvC,GAAIJ,KAAKL,YAAcK,KAAKP,OAAOY,OACjC,OAAOL,KAAKL,WAGd,MAAMW,KAAEA,EAAID,OAAEA,EAAME,WAAEA,GAAeP,KAAKP,OAAOe,YAC3CC,EAAiBC,EAAKC,QAAQ,GAAGL,KAAQC,KAE/C,IAAIK,EAEJ,IAQIA,EAPGP,SAQMQ,OAAOC,EAAcL,GAAgBM,aAC5CC,eAPMhB,KAAKP,OAAOwB,UAAWC,cAAcT,EAAgB,CACzDU,eAAe,KAEjBH,OAML,CAAC,MAAOI,GACP,GACEA,aAAaC,OACbD,EAAEE,QAAQC,SAAS,uBACnBH,EAAEE,QAAQC,SAAS,WAcnB,OA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E,GAIlC"}
@@ -1,2 +1,2 @@
1
- import t from"node:fs";import i from"node:path";import e from"../helpers/plugin-config.js";import r from"./logger.js";class s{isProd;isHost;isModulePreload;mode;entrypointName;vite;app;params;defaultParams;logger;defaultBuildRoots=["./build","./dist"];constructor({entrypointName:t,isProd:i=!1,isHost:e=!1,isOnlyClient:r=!1,isModulePreload:s=!1,mode:o="production"},n){this.isProd=i,this.isHost=e,this.isModulePreload=s,this.mode=o,this.entrypointName=t,this.defaultParams={publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",isSPA:r,...n},this.makeParams()}static init(t={},i={}){return new s(t,i)}getBuildDir(i){for(const e of[i,...this.defaultBuildRoots])if(e&&t.existsSync(e))return e;return i??this.defaultBuildRoots[0]}makeParams(){this.applyEntrypointConfig();const t=this.getPluginConfig()??{},{config:e}=this.vite??{},{root:s,publicDir:o,indexFile:n,clientFile:l,serverFile:a,host:p,isSPA:h}=this.defaultParams,g=new URL(import.meta.url),d=t.pluginPath??i.resolve(i.dirname(g.pathname),"../"),u=this.getEntrypoint(),m="boolean"==typeof e?.server.host||this.isHost?"0.0.0.0":e?.server.host??p,f=Number(e?.env.VITE_PORT??e?.server.port??this.defaultParams.port);this.params={root:e?.root??this.getBuildDir(s),publicDir:e?.publicDir??o,indexFile:t.indexFile??n,clientFile:t.clientFile??l,serverFile:t.serverFile??a,pluginPath:d,host:m,port:f,isSPA:u?"spa"===u.type:h,isProd:this.isProd},this.logger=this.vite?.config.logger??new r}setVite(t){this.vite=t,this.makeParams()}setApp(t){this.app=t}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?e(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}setLogger(t){this.logger=t}applyEntrypointConfig(){const t=this.getPluginConfig();if(!this.vite||!t||!this.entrypointName)return;const i=this.getEntrypoint();i&&["indexFile","clientFile","serverFile"].forEach((e=>{i[e]&&(t[e]=i[e])}))}getEntrypoint(){const t=this.vite?e(this.vite.config):void 0;return t?.entrypoint.find((({name:t})=>t===this.entrypointName))}}export{s as default};
1
+ import t from"node:fs";import i from"node:path";import e from"../helpers/plugin-config.js";import r from"./logger.js";class s{isProd;isHost;isModulePreload;mode;entrypointName;vite;app;params;defaultParams;logger;defaultBuildRoots=["./build","./dist"];constructor({entrypointName:t,isProd:i=!1,isHost:e=!1,isOnlyClient:r=!1,isModulePreload:s=!1,mode:o="production"},n){this.isProd=i,this.isHost=e,this.isModulePreload=s,this.mode=o,this.entrypointName=t,this.defaultParams={publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",isSPA:r,...n},this.makeParams()}static init(t={},i={}){return new s(t,i)}getBuildDir(i){for(const e of[i,...this.defaultBuildRoots])if(e&&t.existsSync(e))return e;return i??this.defaultBuildRoots[0]}makeParams(){this.applyEntrypointConfig();const t=this.getPluginConfig()??{},{config:e}=this.vite??{},{root:s,publicDir:o,indexFile:n,clientFile:l,serverFile:a,host:p,isSPA:h}=this.defaultParams,g=new URL(import.meta.url),d=t.pluginPath??i.resolve(i.dirname(g.pathname),"../"),u=this.getEntrypoint(),m="boolean"==typeof e?.server.host||this.isHost?"0.0.0.0":e?.server.host??p,f=Number(e?.env.VITE_PORT??e?.server.port??this.defaultParams.port);this.params={root:e?.root??this.getBuildDir(s),publicDir:e?.publicDir??o,indexFile:t.indexFile??n,clientFile:t.clientFile??l,serverFile:t.serverFile??a,pluginPath:d,host:m,port:f,isSPA:u?"spa"===u.type:h,isProd:this.isProd},this.logger=this.vite?.config.logger??new r}setVite(t){this.vite=t,this.makeParams()}setApp(t){this.app=t}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?e(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}setLogger(t){this.logger=t}applyEntrypointConfig(){const t=this.getPluginConfig();if(!this.vite||!t||!this.entrypointName)return;const i=this.getEntrypoint();i&&["indexFile","clientFile","serverFile"].forEach((e=>{i[e]&&(t[e]=i[e])}))}getEntrypoint(){const t=this.vite?e(this.vite.config):void 0;return t?.entrypoint?.find((({name:t})=>t===this.entrypointName))}}export{s as default};
2
2
  //# sourceMappingURL=server-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport type { IBuildEntrypoint } from '@services/build';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n isModulePreload?: boolean;\n mode?: string;\n entrypointName?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n clientFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * Add module preload scripts to server output\n */\n public readonly isModulePreload: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Run specified entrypoint\n */\n protected readonly entrypointName?: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default params\n */\n protected defaultParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * Default root dir\n */\n protected defaultBuildRoots = ['./build', './dist'];\n\n /**\n * @constructor\n */\n protected constructor(\n {\n entrypointName,\n isProd = false,\n isHost = false,\n isOnlyClient = false,\n isModulePreload = false,\n mode = 'production',\n }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isModulePreload = isModulePreload;\n this.mode = mode;\n this.entrypointName = entrypointName;\n this.defaultParams = {\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n isSPA: isOnlyClient,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Lookup build folder\n */\n protected getBuildDir(root?: string): string {\n for (const dir of [root, ...this.defaultBuildRoots]) {\n if (dir && fs.existsSync(dir)) {\n return dir;\n }\n }\n\n return root ?? this.defaultBuildRoots[0];\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n this.applyEntrypointConfig();\n\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n const {\n root,\n publicDir,\n indexFile,\n clientFile,\n serverFile,\n host: defaultHost,\n isSPA,\n } = this.defaultParams;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const entrypoint = this.getEntrypoint();\n\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? defaultHost!;\n const port = Number(config?.env.VITE_PORT ?? config?.server.port ?? this.defaultParams.port!);\n\n this.params = {\n root: config?.root ?? this.getBuildDir(root),\n publicDir: config?.publicDir ?? publicDir!,\n indexFile: pluginConfig.indexFile ?? indexFile!,\n clientFile: pluginConfig.clientFile ?? clientFile!,\n serverFile: pluginConfig.serverFile ?? serverFile!,\n pluginPath,\n host,\n port,\n isSPA: entrypoint ? entrypoint.type === 'spa' : isSPA!,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * Return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Set custom logger\n */\n public setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Apply config to specified entrypoint\n */\n protected applyEntrypointConfig(): void {\n const config = this.getPluginConfig();\n\n if (!this.vite || !config || !this.entrypointName) {\n return;\n }\n\n const entrypointConfig = this.getEntrypoint();\n\n // apply specified entrypoint config\n if (entrypointConfig) {\n (['indexFile', 'clientFile', 'serverFile'] as const).forEach((optName) => {\n if (entrypointConfig[optName]) {\n config[optName] = entrypointConfig[optName]!;\n }\n });\n }\n }\n\n /**\n * Get current entrypoint\n */\n protected getEntrypoint(): IBuildEntrypoint | undefined {\n const config = this.vite ? getPluginConfig(this.vite.config) : undefined;\n\n return config?.entrypoint.find(({ name }) => name === this.entrypointName);\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isModulePreload","mode","entrypointName","vite","app","params","defaultParams","logger","defaultBuildRoots","constructor","isOnlyClient","prodParams","this","publicDir","indexFile","serverFile","host","isSPA","makeParams","static","options","prodOptions","getBuildDir","root","dir","fs","existsSync","applyEntrypointConfig","pluginConfig","getPluginConfig","config","clientFile","defaultHost","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","entrypoint","getEntrypoint","server","port","Number","env","VITE_PORT","type","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger","setLogger","entrypoint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,MAAQhC,KAAKN,cAAcsC,MAEvFhC,KAAKP,OAAS,CACZkB,KAAMO,GAAQP,MAAQX,KAAKU,YAAYC,GACvCV,UAAWiB,GAAQjB,WAAaA,EAChCC,UAAWc,EAAad,WAAaA,EACrCiB,WAAYH,EAAaG,YAAcA,EACvChB,WAAYa,EAAab,YAAcA,EACvCqB,aACApB,OACA4B,OACA3B,MAAOwB,EAAiC,QAApBA,EAAWO,KAAiB/B,EAChDnB,OAAQc,KAAKd,QAEfc,KAAKL,OAASK,KAAKT,MAAM2B,OAAOvB,QAAU,IAAI0C,CAC/C,CAKMC,QAAQ/C,GACbS,KAAKT,KAAOA,EAEZS,KAAKM,YACN,CAKMiC,OAAOC,GACZxC,KAAKR,IAAMgD,CACZ,CAMMC,UACL,OAAOzC,KAAKT,IACb,CAKMmD,SACL,OAAO1C,KAAKR,GACb,CAMMyB,kBACL,OAAOjB,KAAKT,KAAO0B,EAAgBjB,KAAKT,KAAK2B,aAAUyB,CACxD,CAKMC,YACL,OAAO5C,KAAKP,MACb,CAKMoD,YACL,OAAO7C,KAAKL,MACb,CAKMmD,UAAUnD,GACfK,KAAKL,OAASA,CACf,CAKSoB,wBACR,MAAMG,EAASlB,KAAKiB,kBAEpB,IAAKjB,KAAKT,OAAS2B,IAAWlB,KAAKV,eACjC,OAGF,MAAMyD,EAAmB/C,KAAK8B,gBAG1BiB,GACD,CAAC,YAAa,aAAc,cAAwBC,SAASC,IACxDF,EAAiBE,KACnB/B,EAAO+B,GAAWF,EAAiBE,GACpC,GAGN,CAKSnB,gBACR,MAAMZ,EAASlB,KAAKT,KAAO0B,EAAgBjB,KAAKT,KAAK2B,aAAUyB,EAE/D,OAAOzB,GAAQW,WAAWqB,MAAK,EAAGC,UAAWA,IAASnD,KAAKV,gBAC5D"}
1
+ {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport type { IBuildEntrypoint } from '@services/build';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n isModulePreload?: boolean;\n mode?: string;\n entrypointName?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n clientFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * Add module preload scripts to server output\n */\n public readonly isModulePreload: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Run specified entrypoint\n */\n protected readonly entrypointName?: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default params\n */\n protected defaultParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * Default root dir\n */\n protected defaultBuildRoots = ['./build', './dist'];\n\n /**\n * @constructor\n */\n protected constructor(\n {\n entrypointName,\n isProd = false,\n isHost = false,\n isOnlyClient = false,\n isModulePreload = false,\n mode = 'production',\n }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isModulePreload = isModulePreload;\n this.mode = mode;\n this.entrypointName = entrypointName;\n this.defaultParams = {\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n isSPA: isOnlyClient,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Lookup build folder\n */\n protected getBuildDir(root?: string): string {\n for (const dir of [root, ...this.defaultBuildRoots]) {\n if (dir && fs.existsSync(dir)) {\n return dir;\n }\n }\n\n return root ?? this.defaultBuildRoots[0];\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n this.applyEntrypointConfig();\n\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n const {\n root,\n publicDir,\n indexFile,\n clientFile,\n serverFile,\n host: defaultHost,\n isSPA,\n } = this.defaultParams;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const entrypoint = this.getEntrypoint();\n\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? defaultHost!;\n const port = Number(config?.env.VITE_PORT ?? config?.server.port ?? this.defaultParams.port!);\n\n this.params = {\n root: config?.root ?? this.getBuildDir(root),\n publicDir: config?.publicDir ?? publicDir!,\n indexFile: pluginConfig.indexFile ?? indexFile!,\n clientFile: pluginConfig.clientFile ?? clientFile!,\n serverFile: pluginConfig.serverFile ?? serverFile!,\n pluginPath,\n host,\n port,\n isSPA: entrypoint ? entrypoint.type === 'spa' : isSPA!,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * Return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Set custom logger\n */\n public setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Apply config to specified entrypoint\n */\n protected applyEntrypointConfig(): void {\n const config = this.getPluginConfig();\n\n if (!this.vite || !config || !this.entrypointName) {\n return;\n }\n\n const entrypointConfig = this.getEntrypoint();\n\n // apply specified entrypoint config\n if (entrypointConfig) {\n (['indexFile', 'clientFile', 'serverFile'] as const).forEach((optName) => {\n if (entrypointConfig[optName]) {\n config[optName] = entrypointConfig[optName]!;\n }\n });\n }\n }\n\n /**\n * Get current entrypoint\n */\n protected getEntrypoint(): IBuildEntrypoint | undefined {\n const config = this.vite ? getPluginConfig(this.vite.config) : undefined;\n\n return config?.entrypoint?.find(({ name }) => name === this.entrypointName);\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isModulePreload","mode","entrypointName","vite","app","params","defaultParams","logger","defaultBuildRoots","constructor","isOnlyClient","prodParams","this","publicDir","indexFile","serverFile","host","isSPA","makeParams","static","options","prodOptions","getBuildDir","root","dir","fs","existsSync","applyEntrypointConfig","pluginConfig","getPluginConfig","config","clientFile","defaultHost","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","entrypoint","getEntrypoint","server","port","Number","env","VITE_PORT","type","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger","setLogger","entrypointConfig","forEach","optName","find","name"],"mappings":"sHAkCA,MAAMA,EAIYC,OAKAC,OAKAC,gBAKAC,KAKGC,eAKTC,KAKAC,IAKAC,OAKAC,cAKAC,OAKAC,kBAAoB,CAAC,UAAW,UAK1CC,aACEP,eACEA,EAAcJ,OACdA,GAAS,EAAKC,OACdA,GAAS,EAAKW,aACdA,GAAe,EAAKV,gBACpBA,GAAkB,EA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