@lomray/vite-ssr-boost 7.1.0 → 8.0.0-beta.2
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/README.md +18 -1
- package/adapters/body.d.ts +5 -0
- package/adapters/body.js +2 -0
- package/adapters/body.js.map +1 -0
- package/adapters/compression.d.ts +11 -0
- package/adapters/compression.js +2 -0
- package/adapters/compression.js.map +1 -0
- package/adapters/edge.d.ts +11 -0
- package/adapters/edge.js +2 -0
- package/adapters/edge.js.map +1 -0
- package/adapters/express/create-request.d.ts +11 -0
- package/adapters/express/create-request.js +2 -0
- package/adapters/express/create-request.js.map +1 -0
- package/adapters/express/entry.d.ts +55 -0
- package/adapters/express/entry.js.map +1 -0
- package/{services → adapters/express}/prepare-server.d.ts +15 -40
- package/adapters/express/prepare-server.js +2 -0
- package/adapters/express/prepare-server.js.map +1 -0
- package/adapters/express/render.d.ts +63 -0
- package/adapters/express/render.js +2 -0
- package/adapters/express/render.js.map +1 -0
- package/adapters/express/server.d.ts +15 -0
- package/adapters/express/server.js +2 -0
- package/adapters/express/server.js.map +1 -0
- package/adapters/express.d.ts +11 -0
- package/adapters/express.js +2 -0
- package/adapters/express.js.map +1 -0
- package/adapters/fastify.d.ts +23 -0
- package/adapters/fastify.js +2 -0
- package/adapters/fastify.js.map +1 -0
- package/adapters/hono.d.ts +13 -0
- package/adapters/hono.js +2 -0
- package/adapters/hono.js.map +1 -0
- package/adapters/node.d.ts +19 -0
- package/adapters/node.js +2 -0
- package/adapters/node.js.map +1 -0
- package/browser/entry.d.ts +9 -9
- package/browser/entry.js +1 -1
- package/browser/entry.js.map +1 -1
- package/cli/build.d.ts +2 -2
- package/cli/build.js.map +1 -1
- package/cli/helpers/keyboard-input.d.ts +1 -1
- package/cli/helpers/keyboard-input.js +1 -1
- package/cli/helpers/keyboard-input.js.map +1 -1
- package/cli/helpers/vite-reset-cache.d.ts +1 -1
- package/cli/helpers/vite-reset-cache.js.map +1 -1
- package/cli/interfaces/actions.d.ts +8 -9
- package/cli/run-amplify-build.d.ts +1 -1
- package/cli/run-amplify-build.js.map +1 -1
- package/cli/run-dev.d.ts +3 -4
- package/cli/run-dev.js +1 -1
- package/cli/run-dev.js.map +1 -1
- package/cli/run-docker-build.d.ts +2 -2
- package/cli/run-docker-build.js.map +1 -1
- package/cli/run-prod.d.ts +5 -6
- package/cli/run-prod.js +1 -1
- package/cli/run-prod.js.map +1 -1
- package/cli/run-serverless.d.ts +3 -3
- package/cli/run-serverless.js +1 -1
- package/cli/run-serverless.js.map +1 -1
- package/cli/run-vercel-build.d.ts +1 -1
- package/cli/run-vercel-build.js.map +1 -1
- package/cli.js +1 -1
- package/cli.js.map +1 -1
- package/components/navigate.d.ts +3 -3
- package/components/navigate.js.map +1 -1
- package/components/only-client.d.ts +2 -2
- package/components/only-client.js +1 -1
- package/components/only-client.js.map +1 -1
- package/components/render-client.d.ts +4 -4
- package/components/render-client.js +1 -1
- package/components/render-client.js.map +1 -1
- package/components/response-status.d.ts +2 -2
- package/components/response-status.js +1 -1
- package/components/response-status.js.map +1 -1
- package/components/scroll-to-top.d.ts +2 -2
- package/components/scroll-to-top.js +1 -1
- package/components/scroll-to-top.js.map +1 -1
- package/components/with-suspense.d.ts +3 -3
- package/components/with-suspense.js.map +1 -1
- package/constants/cli-actions.d.ts +1 -1
- package/constants/cli-actions.js.map +1 -1
- package/constants/cli-context.d.ts +4 -5
- package/constants/cli-context.js.map +1 -1
- package/constants/cli-name.d.ts +1 -1
- package/constants/cli-name.js.map +1 -1
- package/constants/cli-shortcuts.d.ts +2 -2
- package/constants/cli-shortcuts.js +1 -1
- package/constants/cli-shortcuts.js.map +1 -1
- package/constants/common.js.map +1 -1
- package/constants/plugin-name.d.ts +1 -1
- package/constants/plugin-name.js.map +1 -1
- package/constants/stream-error.d.ts +1 -1
- package/constants/stream-error.js.map +1 -1
- package/context/server.d.ts +3 -4
- package/context/server.js.map +1 -1
- package/core/compose-html.d.ts +5 -0
- package/core/compose-html.js +2 -0
- package/core/compose-html.js.map +1 -0
- package/core/early-hints.d.ts +6 -0
- package/core/early-hints.js +2 -0
- package/core/early-hints.js.map +1 -0
- package/core/handler.d.ts +30 -0
- package/core/handler.js +2 -0
- package/core/handler.js.map +1 -0
- package/core/head-response.d.ts +5 -0
- package/core/head-response.js +2 -0
- package/core/head-response.js.map +1 -0
- package/core/headers.d.ts +12 -0
- package/core/headers.js +2 -0
- package/core/headers.js.map +1 -0
- package/core/render.d.ts +101 -0
- package/core/render.js +2 -0
- package/core/render.js.map +1 -0
- package/core/transform-html.d.ts +7 -0
- package/core/transform-html.js +2 -0
- package/core/transform-html.js.map +1 -0
- package/core/types.d.ts +7 -0
- package/core/types.js +2 -0
- package/core/types.js.map +1 -0
- package/edge/render-to-stream.d.ts +6 -0
- package/edge/render-to-stream.js +2 -0
- package/edge/render-to-stream.js.map +1 -0
- package/helpers/build-custom-state.d.ts +2 -3
- package/helpers/build-custom-state.js +1 -1
- package/helpers/build-custom-state.js.map +1 -1
- package/helpers/build-router-state.d.ts +2 -2
- package/helpers/build-router-state.js.map +1 -1
- package/helpers/create-focus-only.d.ts +3 -3
- package/helpers/create-focus-only.js.map +1 -1
- package/helpers/dev-marker.d.ts +1 -1
- package/helpers/dev-marker.js.map +1 -1
- package/helpers/get-server-state.d.ts +1 -1
- package/helpers/get-server-state.js.map +1 -1
- package/helpers/html-escape.d.ts +1 -1
- package/helpers/html-escape.js +1 -1
- package/helpers/html-escape.js.map +1 -1
- package/helpers/import-route.d.ts +7 -7
- package/helpers/import-route.js +1 -1
- package/helpers/import-route.js.map +1 -1
- package/helpers/is-route-file.d.ts +1 -1
- package/helpers/is-route-file.js.map +1 -1
- package/helpers/obtain-stream-error.d.ts +3 -3
- package/helpers/obtain-stream-error.js +1 -1
- package/helpers/obtain-stream-error.js.map +1 -1
- package/helpers/plugin-config.d.ts +5 -5
- package/helpers/plugin-config.js +1 -1
- package/helpers/plugin-config.js.map +1 -1
- package/helpers/print-server-info.d.ts +3 -4
- package/helpers/print-server-info.js +1 -1
- package/helpers/print-server-info.js.map +1 -1
- package/helpers/print-server-urls.d.ts +2 -2
- package/helpers/print-server-urls.js +1 -1
- package/helpers/print-server-urls.js.map +1 -1
- package/helpers/process-stop.d.ts +1 -1
- package/helpers/process-stop.js.map +1 -1
- package/helpers/resolve-server-urls.d.ts +3 -4
- package/helpers/resolve-server-urls.js +1 -1
- package/helpers/resolve-server-urls.js.map +1 -1
- package/helpers/serialize-errors.d.ts +2 -2
- package/helpers/serialize-errors.js.map +1 -1
- package/helpers/vite-aliases.d.ts +2 -2
- package/helpers/vite-aliases.js +1 -1
- package/helpers/vite-aliases.js.map +1 -1
- package/interfaces/fc-route.d.ts +4 -4
- package/interfaces/fc-route.js.map +1 -1
- package/interfaces/fc.d.ts +3 -4
- package/interfaces/route-object.d.ts +6 -6
- package/node/compress-response.d.ts +6 -0
- package/node/compress-response.js +2 -0
- package/node/compress-response.js.map +1 -0
- package/node/create-headers.d.ts +6 -0
- package/node/create-headers.js +2 -0
- package/node/create-headers.js.map +1 -0
- package/node/create-request.d.ts +13 -0
- package/node/create-request.js +2 -0
- package/node/create-request.js.map +1 -0
- package/node/http.d.ts +4 -0
- package/node/http.js +2 -0
- package/node/http.js.map +1 -0
- package/node/render-to-stream.d.ts +6 -0
- package/node/render-to-stream.js +2 -0
- package/node/render-to-stream.js.map +1 -0
- package/node/request-signal.d.ts +10 -0
- package/node/request-signal.js +2 -0
- package/node/request-signal.js.map +1 -0
- package/node/split-link-header.d.ts +5 -0
- package/node/split-link-header.js +2 -0
- package/node/split-link-header.js.map +1 -0
- package/node/write-early-hints.d.ts +6 -0
- package/node/write-early-hints.js +2 -0
- package/node/write-early-hints.js.map +1 -0
- package/node/write-fetch-response.d.ts +11 -0
- package/node/write-fetch-response.js +2 -0
- package/node/write-fetch-response.js.map +1 -0
- package/package.json +89 -27
- package/plugin.d.ts +7 -7
- package/plugin.js.map +1 -1
- package/plugins/create-spa-index.d.ts +3 -3
- package/plugins/create-spa-index.js.map +1 -1
- package/plugins/handle-custom-entrypoint.d.ts +4 -4
- package/plugins/handle-custom-entrypoint.js +1 -1
- package/plugins/handle-custom-entrypoint.js.map +1 -1
- package/plugins/make-aliases.d.ts +3 -3
- package/plugins/make-aliases.js +1 -1
- package/plugins/make-aliases.js.map +1 -1
- package/plugins/normalize-route.d.ts +3 -3
- package/plugins/normalize-route.js.map +1 -1
- package/services/build.d.ts +5 -51
- package/services/build.js +1 -1
- package/services/build.js.map +1 -1
- package/services/logger.d.ts +2 -30
- package/services/logger.js.map +1 -1
- package/services/parse-routes.d.ts +5 -42
- package/services/parse-routes.js +1 -1
- package/services/parse-routes.js.map +1 -1
- package/services/path-normalize.d.ts +3 -18
- package/services/path-normalize.js +1 -1
- package/services/path-normalize.js.map +1 -1
- package/services/server-api.d.ts +1 -7
- package/services/server-api.js.map +1 -1
- package/services/server-config.d.ts +7 -52
- package/services/server-config.js +1 -1
- package/services/server-config.js.map +1 -1
- package/services/ssr-manifest.d.ts +20 -60
- package/services/ssr-manifest.js +1 -1
- package/services/ssr-manifest.js.map +1 -1
- package/workflow/Dockerfile +1 -1
- package/helpers/handle-response.d.ts +0 -7
- package/helpers/handle-response.js +0 -2
- package/helpers/handle-response.js.map +0 -1
- package/node/create-fetch-request.d.ts +0 -7
- package/node/create-fetch-request.js +0 -2
- package/node/create-fetch-request.js.map +0 -1
- package/node/entry.d.ts +0 -63
- package/node/entry.js.map +0 -1
- package/node/render.d.ts +0 -64
- package/node/render.js +0 -2
- package/node/render.js.map +0 -1
- package/node/server.d.ts +0 -16
- package/node/server.js +0 -2
- package/node/server.js.map +0 -1
- package/node/write-response.d.ts +0 -14
- package/node/write-response.js +0 -2
- package/node/write-response.js.map +0 -1
- package/services/prepare-server.js +0 -2
- package/services/prepare-server.js.map +0 -1
- /package/{node → adapters/express}/entry.js +0 -0
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import { TRoutesTree } from "./parse-routes.js";
|
|
7
|
-
import PathNormalize from "./path-normalize.js";
|
|
8
|
-
import ServerConfig from "./server-config.js";
|
|
1
|
+
import type { RouterState, StaticHandlerContext } from 'react-router';
|
|
2
|
+
import type { Alias, ModuleNode, RenderBuiltAssetUrl } from 'vite';
|
|
3
|
+
import type { TRoutesTree } from './parse-routes.js';
|
|
4
|
+
import PathNormalize from './path-normalize.js';
|
|
5
|
+
import type ServerConfig from './server-config.js';
|
|
9
6
|
interface ISsrManifestParams {
|
|
10
7
|
buildDir?: string;
|
|
11
8
|
viteAliases?: Alias[];
|
|
@@ -38,6 +35,12 @@ interface IAsset {
|
|
|
38
35
|
type TAssets = {
|
|
39
36
|
[id: string]: IAsset;
|
|
40
37
|
};
|
|
38
|
+
interface IInjectAssetsContext {
|
|
39
|
+
html: {
|
|
40
|
+
header: string;
|
|
41
|
+
};
|
|
42
|
+
routerContext?: StaticHandlerContext;
|
|
43
|
+
}
|
|
41
44
|
/**
|
|
42
45
|
* Working with SSR Manifest file
|
|
43
46
|
*/
|
|
@@ -86,79 +89,46 @@ declare class SsrManifest {
|
|
|
86
89
|
* Loaded assets manifest file
|
|
87
90
|
*/
|
|
88
91
|
protected routesAssets: Record<string, IAsset[]> | null;
|
|
89
|
-
/**
|
|
90
|
-
* @constructor
|
|
91
|
-
*/
|
|
92
92
|
/**
|
|
93
93
|
* @constructor
|
|
94
94
|
*/
|
|
95
95
|
protected constructor(config: ServerConfig, { buildDir, viteAliases, basename, renderBuiltUrl }?: ISsrManifestParams);
|
|
96
|
-
/**
|
|
97
|
-
* Get singleton instance
|
|
98
|
-
*/
|
|
99
96
|
/**
|
|
100
97
|
* Get singleton instance
|
|
101
98
|
*/
|
|
102
99
|
static get(config: ServerConfig, params?: ISsrManifestParams): SsrManifest;
|
|
103
|
-
/**
|
|
104
|
-
* Get output dir
|
|
105
|
-
*/
|
|
106
100
|
/**
|
|
107
101
|
* Get output dir
|
|
108
102
|
*/
|
|
109
103
|
protected getOutDir(): string;
|
|
110
|
-
/**
|
|
111
|
-
* Get assets manifest file name
|
|
112
|
-
*/
|
|
113
104
|
/**
|
|
114
105
|
* Get assets manifest file name
|
|
115
106
|
*/
|
|
116
107
|
protected getAssetsManifestFile(): string;
|
|
117
|
-
/**
|
|
118
|
-
* Load client ssr manifest
|
|
119
|
-
*/
|
|
120
108
|
/**
|
|
121
109
|
* Load client ssr manifest
|
|
122
110
|
*/
|
|
123
111
|
protected loadClientManifest(): IManifest;
|
|
124
|
-
/**
|
|
125
|
-
* Load assets manifest
|
|
126
|
-
*/
|
|
127
112
|
/**
|
|
128
113
|
* Load assets manifest
|
|
129
114
|
*/
|
|
130
115
|
protected loadAssetsManifest(): Record<string, IAsset[]>;
|
|
131
|
-
/**
|
|
132
|
-
* Same as 'getAsyncRoutesIds' but for routes tree from 'ParseRoutes'
|
|
133
|
-
*/
|
|
134
116
|
/**
|
|
135
117
|
* Same as 'getAsyncRoutesIds' but for routes tree from 'ParseRoutes'
|
|
136
118
|
*/
|
|
137
119
|
protected getRoutesTreeIds(routes: TRoutesTree[], index?: string): Record<string, string | undefined>;
|
|
138
|
-
/**
|
|
139
|
-
* Sort assets
|
|
140
|
-
*/
|
|
141
120
|
/**
|
|
142
121
|
* Sort assets
|
|
143
122
|
*/
|
|
144
123
|
protected sortAssets(assets: IAsset[]): IAsset[];
|
|
145
|
-
/**
|
|
146
|
-
* Get recursive module assets
|
|
147
|
-
*/
|
|
148
124
|
/**
|
|
149
125
|
* Get recursive module assets
|
|
150
126
|
*/
|
|
151
127
|
protected getRouteAssets(manifest: IManifest, module: IManifest[string], isNested?: boolean): Record<string, IAsset>;
|
|
152
|
-
/**
|
|
153
|
-
* Build routes manifest file
|
|
154
|
-
*/
|
|
155
128
|
/**
|
|
156
129
|
* Build routes manifest file
|
|
157
130
|
*/
|
|
158
131
|
buildRoutesManifest(): void;
|
|
159
|
-
/**
|
|
160
|
-
* Get route assets
|
|
161
|
-
*/
|
|
162
132
|
/**
|
|
163
133
|
* Get route assets
|
|
164
134
|
*/
|
|
@@ -166,44 +136,34 @@ declare class SsrManifest {
|
|
|
166
136
|
/**
|
|
167
137
|
* Get development route assets
|
|
168
138
|
*/
|
|
139
|
+
protected getDevModules(routes?: RouterState['matches']): ModuleNode[];
|
|
169
140
|
/**
|
|
170
|
-
*
|
|
141
|
+
* Compile SSR graph styles before the browser has populated the client graph.
|
|
171
142
|
*/
|
|
172
|
-
|
|
143
|
+
prepareDevAssets(routes?: RouterState['matches']): Promise<void>;
|
|
173
144
|
/**
|
|
174
|
-
*
|
|
145
|
+
* Collect development assets from the current server and client module graphs.
|
|
175
146
|
*/
|
|
147
|
+
protected getAssetsDev(routes?: RouterState['matches']): IAsset[];
|
|
176
148
|
/**
|
|
177
149
|
* Get module assets
|
|
178
150
|
*/
|
|
179
151
|
protected getModuleAssets(module?: ModuleNode, skipModules?: Set<string>): TAssets;
|
|
180
|
-
/**
|
|
181
|
-
* Get asset weight
|
|
182
|
-
*/
|
|
183
152
|
/**
|
|
184
153
|
* Get asset weight
|
|
185
154
|
*/
|
|
186
155
|
protected getAssetWeight(asset: string): number;
|
|
187
|
-
/**
|
|
188
|
-
* Get asset type
|
|
189
|
-
*/
|
|
190
156
|
/**
|
|
191
157
|
* Get asset type
|
|
192
158
|
*/
|
|
193
159
|
protected getAssetType(asset: string): AssetType | null;
|
|
194
160
|
/**
|
|
195
|
-
*
|
|
196
|
-
*/
|
|
197
|
-
/**
|
|
198
|
-
* Write 103 Early Hits header
|
|
199
|
-
*/
|
|
200
|
-
writeEarlyHits(assets: IAsset[], socket: Socket): void;
|
|
201
|
-
/**
|
|
202
|
-
* Inject route assets to head html
|
|
161
|
+
* Build preload hints without depending on a particular HTTP transport.
|
|
203
162
|
*/
|
|
163
|
+
getEarlyHints(assets: IAsset[]): Headers;
|
|
204
164
|
/**
|
|
205
165
|
* Inject route assets to head html
|
|
206
166
|
*/
|
|
207
|
-
injectAssets({ routerContext, html
|
|
167
|
+
injectAssets({ routerContext, html }: IInjectAssetsContext): Headers;
|
|
208
168
|
}
|
|
209
|
-
export
|
|
169
|
+
export default SsrManifest;
|
package/services/ssr-manifest.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import
|
|
1
|
+
import e from"node:fs";import s from"node:path";import t from"chalk";import i from"./parse-routes.js";import r from"./path-normalize.js";var n;!function(e){e.style="style",e.script="script",e.image="image",e.font="font"}(n||(n={}));class o{static instance=null;config;pathNormalize;root;buildDir;manifestName="manifest.json";assetsManifest="assets-manifest.json";viteAliases;basename;renderBuiltUrl;routesAssets=null;constructor(e,{buildDir:s,viteAliases:t,basename:i,renderBuiltUrl:n}={}){this.config=e,this.root=e.getParams().root,this.buildDir=s,this.viteAliases=t??e.getVite()?.config?.resolve.alias,this.pathNormalize=new r(e,t),this.basename=i,this.renderBuiltUrl=n}static get(e,s={}){return null===o.instance&&(o.instance=new o(e,s)),o.instance}getOutDir(){return s.resolve(this.root,this.buildDir||"")}getAssetsManifestFile(){return`${this.getOutDir()}/server/${this.assetsManifest}`}loadClientManifest(){const t=s.resolve(this.root,`${this.buildDir||""}/client/.vite`),i=`${t}/${this.manifestName}`;if(!e.existsSync(i))return{};const r=JSON.parse(e.readFileSync(i,{encoding:"utf-8"}));return e.rmSync(i),0===e.readdirSync(t).length&&e.rmSync(t,{recursive:!0}),r}loadAssetsManifest(){if(null!==this.routesAssets)return this.routesAssets;const s=this.getAssetsManifestFile();return e.existsSync(s)?(this.routesAssets=JSON.parse(e.readFileSync(s,{encoding:"utf-8"})),this.routesAssets):{}}getRoutesTreeIds(e,s){const t={};return e.forEach((e,i)=>{const r=[s,String(i)].filter(Boolean).join("-");e.import&&(t[r]=this.pathNormalize.getAppPath(e.import)),e.children.length>0&&Object.assign(t,this.getRoutesTreeIds(e.children,r))}),t}sortAssets(e){return e.sort((e,s)=>e.weight===s.weight?Number(e.isNested)-Number(s.isNested):e.weight-s.weight)}getRouteAssets(e,t,i=!1){const r=[...t?.assets??[],...t?.css??[],t?.file].reduce((e,r)=>{if(r){const n=this.getAssetType(r),o=t.isEntry&&t.file===r;if(n){const t=s.posix.normalize(`${this.basename}/${r}`),a=this.renderBuiltUrl?.(t,{type:"asset",ssr:!0,hostId:"",hostType:t.split(".").at(-1)?.toLowerCase()});e[r]={url:"string"==typeof a?a:t,weight:o?1.9:this.getAssetWeight(r),type:n,isNested:i,isPreload:!o}}}return e},{});return t?.imports?.length&&t.imports.forEach(s=>{const t=e[s];t&&Object.assign(r,this.getRouteAssets(e,t,!0))}),r}buildRoutesManifest(){const s=this.loadClientManifest(),t=new i(this.config,this.viteAliases),r=this.getRoutesTreeIds(t.parse()),n=this.pathNormalize.getImportPostfix(),o={};Object.entries(r).forEach(([e,t])=>{const i=n.find(e=>void 0!==s[`${t}${e}`]),r=s[`${t}${i||""}`];o[e]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))}),e.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(o,null,2),{encoding:"utf-8"})}getAssets(e){if(this.config.getVite())return this.getAssetsDev(e);const s=e?.map(({route:e})=>e.id).filter(Boolean)??[];if(!s.length)return[];const t=this.loadAssetsManifest();return this.sortAssets(s.map(e=>t[e]).flat().filter(Boolean))}getDevModules(e){const t=e?.map(({route:e})=>this.pathNormalize.getAppPath(e?.pathId,!0)).filter(Boolean)??[],i=this.pathNormalize.getImportPostfix(),r=this.config.getPluginConfig(),n=[r?.clientFile??"client.ts",r?.serverFile??"server.ts"].map(e=>s.resolve(this.root,e)),o=[];return[...n,...t].forEach(e=>{for(const s of i){const t=this.config.getVite()?.moduleGraph.getModuleById(`${e}${s}`);if(t){o.push(t);break}}}),o}async prepareDevAssets(e){const s=this.config.getVite();if(!s)return;const t=new Set,i=async e=>{t.has(e.url)||(t.add(e.url),e.file&&/\.(?:css|less|s[ac]ss|styl(?:us)?|pcss|postcss)$/.test(e.file)&&await s.transformRequest(e.url),await Promise.all([...e.importedModules].map(i)))};await Promise.all(this.getDevModules(e).map(i))}getAssetsDev(e){const s=Object.assign({},...this.getDevModules(e).map(e=>this.getModuleAssets(e)));return Object.values(s)}getModuleAssets(e,s=new Set){const i=e?.importedModules??e?.clientImportedModules;if(!i?.size||s.has(e.file))return{};let r={};return s.add(e.file),i.forEach(e=>{const{file:i,transformResult:o}=e,a=i?.split(".").at(-1);if(i&&a&&["css","scss","sass","less","styl","stylus","pcss","postcss"].includes(a)){const e=o?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(e)try{r[i]={type:n.style,url:i,weight:this.getAssetWeight(i),content:JSON.parse(`{"style": "${e}"}`).style,isNested:Boolean(s.size),isPreload:!1}}catch{console.warn(t.yellowBright("Failed to parse style: ",i))}}else r={...r,...this.getModuleAssets(e,s)}}),r}getAssetWeight(e){switch(this.getAssetType(e)){case n.style:return 1;case n.script:return 2;default:return 3}}getAssetType(e){const s=e.split(".").at(-1)?.toLowerCase();switch(s){case"css":case"scss":return n.style;case"js":return n.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return n.image;case"ttf":case"otf":case"woff":case"woff2":return n.font;default:return null}}getEarlyHints(e){const s=new Headers;return e.forEach(({type:e,url:t})=>{e&&["style","script"].includes(e)&&s.append("Link",`<${t}>; rel=preload; as=${e}`)}),s}injectAssets({routerContext:e,html:s}){const t=this.getAssets(e?.matches),i=t.map(({type:e,url:s,isPreload:t,content:i=""})=>{switch(e){case n.style:return this.config.getVite()?`<style data-vite-dev-id="${s}">${i}</style>`:`<link rel="stylesheet" href="${s}">`;case n.script:return t?this.config.isModulePreload?`<link rel="modulepreload" as="script" crossorigin href="${s}">`:null:`<script async type="module" crossorigin src="${s}"><\/script>`}return null}).filter(Boolean);return s.header=s.header.replace("</head>",`${i.join("\n")}</head>`),this.getEarlyHints(t)}}export{o as default};
|
|
2
2
|
//# sourceMappingURL=ssr-manifest.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Socket } from 'node:net';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport type { RouterState } from 'react-router';\nimport type { Alias, ModuleNode, RenderBuiltAssetUrl } from 'vite';\nimport type { IAsyncRoute } from '@helpers/import-route';\nimport type { IRequestContext } from '@node/render';\nimport type { TRoutesTree } from '@services/parse-routes';\nimport ParseRoutes from '@services/parse-routes';\nimport PathNormalize from '@services/path-normalize';\nimport type ServerConfig from '@services/server-config';\n\ninterface ISsrManifestParams {\n buildDir?: string;\n viteAliases?: Alias[];\n basename?: string;\n renderBuiltUrl?: RenderBuiltAssetUrl;\n}\n\ninterface IManifest {\n [path: string]: {\n assets: string[];\n css: string[];\n file: string;\n isEntry?: boolean;\n imports: string[];\n };\n}\n\nenum AssetType {\n style = 'style',\n script = 'script',\n image = 'image',\n font = 'font',\n}\n\ninterface IAsset {\n type: AssetType;\n url: string;\n weight: number;\n isNested: boolean;\n isPreload: boolean;\n content?: string;\n}\n\ntype TAssets = { [id: string]: IAsset };\n\nconst CRLF = '\\r\\n';\n\n/**\n * Working with SSR Manifest file\n */\nclass SsrManifest {\n /**\n * Singleton\n */\n protected static instance: SsrManifest | null = null;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * Path normalize service\n */\n protected readonly pathNormalize: PathNormalize;\n\n /**\n * Project root path\n */\n protected readonly root: string;\n\n /**\n * Build dir\n */\n protected readonly buildDir?: string;\n\n /**\n * Client manifest file name\n */\n protected readonly manifestName = 'manifest.json';\n\n /**\n * Assets manifest file name\n */\n protected readonly assetsManifest = 'assets-manifest.json';\n\n /**\n * Vite resolve aliases\n */\n protected readonly viteAliases?: Alias[];\n\n /**\n * Vite base\n */\n protected readonly basename?: string;\n\n /**\n * Vite renderBuiltUrl config func\n */\n protected readonly renderBuiltUrl?: RenderBuiltAssetUrl;\n\n /**\n * Loaded assets manifest file\n */\n protected routesAssets: Record<string, IAsset[]> | null = null;\n\n /**\n * @constructor\n */\n protected constructor(\n config: ServerConfig,\n { buildDir, viteAliases, basename, renderBuiltUrl }: ISsrManifestParams = {},\n ) {\n this.config = config;\n this.root = config.getParams().root;\n this.buildDir = buildDir;\n this.viteAliases = viteAliases ?? config.getVite()?.config?.resolve.alias;\n this.pathNormalize = new PathNormalize(config, viteAliases);\n this.basename = basename;\n this.renderBuiltUrl = renderBuiltUrl;\n }\n\n /**\n * Get singleton instance\n */\n public static get(config: ServerConfig, params: ISsrManifestParams = {}): SsrManifest {\n if (SsrManifest.instance === null) {\n SsrManifest.instance = new SsrManifest(config, params);\n }\n\n return SsrManifest.instance;\n }\n\n /**\n * Get output dir\n */\n protected getOutDir() {\n return path.resolve(this.root, this.buildDir || '');\n }\n\n /**\n * Get assets manifest file name\n */\n protected getAssetsManifestFile(): string {\n return `${this.getOutDir()}/server/${this.assetsManifest}`;\n }\n\n /**\n * Load client ssr manifest\n */\n protected loadClientManifest(): IManifest {\n const clientManifestDir = path.resolve(this.root, `${this.buildDir || ''}/client/.vite`);\n const clientSsrManifest = `${clientManifestDir}/${this.manifestName}`;\n\n if (!fs.existsSync(clientSsrManifest)) {\n return {};\n }\n\n const result = JSON.parse(\n fs.readFileSync(clientSsrManifest, { encoding: 'utf-8' }),\n ) as IManifest;\n\n fs.rmSync(clientSsrManifest);\n\n // try to remove empty .vite dir\n if (fs.readdirSync(clientManifestDir).length === 0) {\n fs.rmSync(clientManifestDir, { recursive: true });\n }\n\n return result;\n }\n\n /**\n * Load assets manifest\n */\n protected loadAssetsManifest(): Record<string, IAsset[]> {\n if (this.routesAssets !== null) {\n return this.routesAssets;\n }\n\n const manifestFile = this.getAssetsManifestFile();\n\n if (!fs.existsSync(manifestFile)) {\n return {};\n }\n\n this.routesAssets = JSON.parse(fs.readFileSync(manifestFile, { encoding: 'utf-8' })) as Record<\n string,\n IAsset[]\n >;\n\n return this.routesAssets;\n }\n\n /**\n * Same as 'getAsyncRoutesIds' but for routes tree from 'ParseRoutes'\n */\n protected getRoutesTreeIds(\n routes: TRoutesTree[],\n index?: string,\n ): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n\n routes.forEach((route, routeIndex) => {\n const routeId = [index, String(routeIndex)].filter(Boolean).join('-');\n\n if (route.import) {\n result[routeId] = this.pathNormalize.getAppPath(route.import);\n }\n\n if (route.children.length > 0) {\n Object.assign(result, this.getRoutesTreeIds(route.children, routeId));\n }\n });\n\n return result;\n }\n\n /**\n * Sort assets\n */\n protected sortAssets(assets: IAsset[]): IAsset[] {\n return assets.sort((a, b) =>\n a.weight === b.weight ? Number(a.isNested) - Number(b.isNested) : a.weight - b.weight,\n );\n }\n\n /**\n * Get recursive module assets\n */\n protected getRouteAssets(\n manifest: IManifest,\n module: IManifest[string],\n isNested = false,\n ): Record<string, IAsset> {\n const rootAssets = [...(module?.assets ?? []), ...(module?.css ?? []), module?.file];\n\n const assets = rootAssets.reduce(\n (res, asset) => {\n if (asset) {\n const type = this.getAssetType(asset);\n const isEntry = module.isEntry && module.file === asset;\n\n // keep only js,css,image,fonts files\n if (type) {\n const filename = path.posix.normalize(`${this.basename}/${asset}`);\n const modifiedFilename = this.renderBuiltUrl?.(filename, {\n type: 'asset',\n ssr: true,\n hostId: '',\n hostType: filename.split('.').at(-1)?.toLowerCase() as 'js',\n });\n\n res[asset] = {\n url: typeof modifiedFilename === 'string' ? modifiedFilename : filename,\n weight: isEntry ? 1.9 : this.getAssetWeight(asset),\n type,\n isNested,\n isPreload: !isEntry,\n };\n }\n }\n\n return res;\n },\n {} as Record<string, IAsset>,\n );\n\n // nested assets\n if (module?.imports?.length) {\n module.imports.forEach((nestedAsset) => {\n const nestedModule = manifest[nestedAsset];\n\n if (nestedModule) {\n Object.assign(assets, this.getRouteAssets(manifest, nestedModule, true));\n }\n });\n }\n\n return assets;\n }\n\n /**\n * Build routes manifest file\n */\n public buildRoutesManifest(): void {\n const manifest = this.loadClientManifest();\n const routesService = new ParseRoutes(this.config, this.viteAliases);\n const routesPaths = this.getRoutesTreeIds(routesService.parse());\n\n const postfixes = this.pathNormalize.getImportPostfix();\n const result: Record<string, IAsset[]> = {};\n\n // find route assets\n Object.entries(routesPaths).forEach(([routeId, routePath]) => {\n const routePostfix = postfixes.find((postfix) => {\n const filePath = `${routePath}${postfix}`;\n\n return manifest[filePath] !== undefined;\n });\n const routeFile = `${routePath}${routePostfix || ''}`;\n const routeMeta = manifest[routeFile];\n\n result[routeId] = this.sortAssets(Object.values(this.getRouteAssets(manifest, routeMeta)));\n });\n\n fs.writeFileSync(this.getAssetsManifestFile(), JSON.stringify(result, null, 2), {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Get route assets\n */\n protected getAssets(routes?: RouterState['matches']): IAsset[] {\n if (this.config.getVite()) {\n return this.getAssetsDev(routes);\n }\n\n const routeIds = routes?.map(({ route }) => route.id).filter(Boolean) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n const routesAssets = this.loadAssetsManifest();\n\n return this.sortAssets(\n routeIds\n .map((routeId) => routesAssets[routeId])\n .flat()\n .filter(Boolean),\n );\n }\n\n /**\n * Get development route assets\n */\n protected getAssetsDev(routes?: RouterState['matches']): IAsset[] {\n const routeIds =\n (routes\n ?.map(({ route }) => this.pathNormalize.getAppPath((route as IAsyncRoute)?.pathId, true))\n .filter(Boolean) as string[]) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n let assets: TAssets = {};\n const postfixes = this.pathNormalize.getImportPostfix();\n const rootId = path.resolve(\n this.root,\n this.config.getPluginConfig()?.clientFile ?? 'client.ts',\n );\n\n [rootId, ...routeIds].forEach((moduleId) => {\n for (const ext of postfixes) {\n const module = this.config.getVite()?.moduleGraph.getModuleById(`${moduleId}${ext}`);\n\n if (module) {\n assets = { ...assets, ...this.getModuleAssets(module) };\n break;\n }\n }\n });\n\n return Object.values(assets);\n }\n\n /**\n * Get module assets\n */\n protected getModuleAssets(module?: ModuleNode, skipModules: Set<string> = new Set()): TAssets {\n if (!module?.clientImportedModules.size || skipModules.has(module.file!)) {\n return {};\n }\n\n let assets: TAssets = {};\n\n skipModules.add(module.file!);\n\n module.clientImportedModules.forEach((subModule) => {\n const { file, clientImportedModules, transformResult } = subModule;\n const ext = file?.split('.').at(-1);\n\n if (file && ext && ['css', 'scss'].includes(ext)) {\n // @TODO investigate better method?\n const code = transformResult?.code.match(/__vite__css\\s+=\\s+\"(?<css>.+)\"/)?.groups?.css;\n\n if (code) {\n try {\n assets[file] = {\n type: AssetType.style,\n url: file,\n weight: this.getAssetWeight(file),\n content: (JSON.parse(`{\"style\": \"${code}\"}`) as { style: string }).style,\n isNested: Boolean(skipModules.size),\n isPreload: false,\n };\n } catch {\n console.warn(chalk.yellowBright('Failed to parse style: ', file));\n }\n }\n } else if (clientImportedModules.size) {\n assets = {\n ...assets,\n ...this.getModuleAssets(subModule, skipModules),\n };\n }\n });\n\n return assets;\n }\n\n /**\n * Get asset weight\n */\n protected getAssetWeight(asset: string): number {\n const type = this.getAssetType(asset);\n\n switch (type) {\n case AssetType.style:\n return 1;\n\n case AssetType.script:\n return 2;\n\n default:\n return 3;\n }\n }\n\n /**\n * Get asset type\n */\n protected getAssetType(asset: string): AssetType | null {\n const ext = asset.split('.').at(-1)?.toLowerCase();\n\n switch (ext) {\n case 'css':\n case 'scss':\n return AssetType.style;\n\n case 'js':\n return AssetType.script;\n\n case 'svg':\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'webp':\n case 'gif':\n case 'ico':\n return AssetType.image;\n\n case 'ttf':\n case 'otf':\n case 'woff':\n case 'woff2':\n return AssetType.font;\n\n default:\n return null;\n }\n }\n\n /**\n * Write 103 Early Hits header\n */\n public writeEarlyHits(assets: IAsset[], socket: Socket): void {\n socket.write(`HTTP/1.1 103 Early Hints${CRLF}`);\n assets.forEach(({ type, url }) => {\n if (!type || !['style', 'script'].includes(type)) {\n return;\n }\n\n socket.write(`Link: <${url}>; rel=preload; as=${type}${CRLF}`);\n });\n socket.write(CRLF);\n }\n\n /**\n * Inject route assets to head html\n */\n public injectAssets({ routerContext, html, res, hasEarlyHints = false }: IRequestContext): void {\n const assets = this.getAssets(routerContext?.matches);\n const htmlAssets = assets\n .map(({ type, url, isPreload, content = '' }) => {\n switch (type) {\n case AssetType.style:\n return this.config.getVite()\n ? `<style data-vite-dev-id=\"${url}\">${content}</style>`\n : `<link rel=\"stylesheet\" href=\"${url}\">`;\n\n case AssetType.script:\n return isPreload\n ? this.config.isModulePreload\n ? // can reduce lighthouse performance\n `<link rel=\"modulepreload\" as=\"script\" crossorigin href=\"${url}\">`\n : null\n : `<script async type=\"module\" crossorigin src=\"${url}\"></script>`;\n }\n\n return null;\n })\n .filter(Boolean);\n\n html.header = html.header.replace('</head>', `${htmlAssets.join('\\n')}</head>`);\n\n if (hasEarlyHints && htmlAssets.length && res.socket) {\n this.writeEarlyHits(assets, res.socket);\n }\n }\n}\n\nexport default SsrManifest;\n"],"names":["AssetType","CRLF","SsrManifest","static","config","pathNormalize","root","buildDir","manifestName","assetsManifest","viteAliases","basename","renderBuiltUrl","routesAssets","constructor","this","getParams","getVite","resolve","alias","PathNormalize","params","instance","getOutDir","path","getAssetsManifestFile","loadClientManifest","clientManifestDir","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","readdirSync","length","recursive","loadAssetsManifest","manifestFile","getRoutesTreeIds","routes","index","forEach","route","routeIndex","routeId","String","filter","Boolean","join","import","getAppPath","children","Object","assign","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","filename","posix","normalize","modifiedFilename","ssr","hostId","hostType","split","at","toLowerCase","url","getAssetWeight","isPreload","imports","nestedAsset","nestedModule","buildRoutesManifest","routesService","ParseRoutes","routesPaths","postfixes","getImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAssets","getAssetsDev","routeIds","map","id","flat","pathId","getPluginConfig","clientFile","moduleId","ext","moduleGraph","getModuleById","getModuleAssets","skipModules","Set","clientImportedModules","size","has","add","subModule","transformResult","includes","code","match","groups","style","content","console","warn","chalk","yellowBright","script","image","font","writeEarlyHits","socket","write","injectAssets","routerContext","html","hasEarlyHints","matches","htmlAssets","isModulePreload","header","replace"],"mappings":"yIA8BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,KAAA,MACD,CALD,CAAKA,IAAAA,EAAS,CAAA,IAkBd,MAAMC,EAAO,OAKb,MAAMC,EAIMC,gBAAsC,KAK7BC,OAKAC,cAKAC,KAKAC,SAKAC,aAAe,gBAKfC,eAAiB,uBAKjBC,YAKAC,SAKAC,eAKTC,aAAgD,KAK1DC,YACEV,GACAG,SAAEA,EAAQG,YAAEA,EAAWC,SAAEA,EAAQC,eAAEA,GAAuC,IAE1EG,KAAKX,OAASA,EACdW,KAAKT,KAAOF,EAAOY,YAAYV,KAC/BS,KAAKR,SAAWA,EAChBQ,KAAKL,YAAcA,GAAeN,EAAOa,WAAWb,QAAQc,QAAQC,MACpEJ,KAAKV,cAAgB,IAAIe,EAAchB,EAAQM,GAC/CK,KAAKJ,SAAWA,EAChBI,KAAKH,eAAiBA,CACxB,CAKOT,WAAWC,EAAsBiB,EAA6B,IAKnE,OAJ6B,OAAzBnB,EAAYoB,WACdpB,EAAYoB,SAAW,IAAIpB,EAAYE,EAAQiB,IAG1CnB,EAAYoB,QACrB,CAKUC,YACR,OAAOC,EAAKN,QAAQH,KAAKT,KAAMS,KAAKR,UAAY,GAClD,CAKUkB,wBACR,MAAO,GAAGV,KAAKQ,sBAAsBR,KAAKN,gBAC5C,CAKUiB,qBACR,MAAMC,EAAoBH,EAAKN,QAAQH,KAAKT,KAAM,GAAGS,KAAKR,UAAY,mBAChEqB,EAAoB,GAAGD,KAAqBZ,KAAKP,eAEvD,IAAKqB,EAAGC,WAAWF,GACjB,MAAO,CAAA,EAGT,MAAMG,EAASC,KA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,UACf,4BAA4BsE,MAAQiD,YACpC,gCAAgCjD,MAEtC,KAAKvF,EAAU6I,OACb,OAAOpD,EACH1E,KAAKX,OAAOqJ,gBAEV,2DAA2DlE,MAC3D,KACF,gDAAgDA,gBAGxD,OAAO,IAAI,IAEZrC,OAAOC,SAEVkG,EAAKK,OAASL,EAAKK,OAAOC,QAAQ,UAAW,GAAGH,EAAWpG,KAAK,gBAE5DkG,GAAiBE,EAAWlH,QAAUkC,EAAIyE,QAC5ClI,KAAKiI,eAAerF,EAAQa,EAAIyE,OAEpC"}
|
|
1
|
+
{"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":[null],"names":["AssetType","SsrManifest","static","config","pathNormalize","root","buildDir","manifestName","assetsManifest","viteAliases","basename","renderBuiltUrl","routesAssets","constructor","this","getParams","getVite","resolve","alias","PathNormalize","get","params","instance","getOutDir","path","getAssetsManifestFile","loadClientManifest","clientManifestDir","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","readdirSync","length","recursive","loadAssetsManifest","manifestFile","getRoutesTreeIds","routes","index","forEach","route","routeIndex","routeId","String","filter","Boolean","join","import","getAppPath","children","Object","assign","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","filename","posix","normalize","modifiedFilename","ssr","hostId","hostType","split","at","toLowerCase","url","getAssetWeight","isPreload","imports","nestedAsset","nestedModule","buildRoutesManifest","routesService","ParseRoutes","routesPaths","postfixes","getImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAssets","getAssetsDev","routeIds","map","id","flat","getDevModules","pathId","pluginConfig","getPluginConfig","rootIds","clientFile","serverFile","modules","moduleId","ext","moduleGraph","getModuleById","push","prepareDevAssets","vite","visited","Set","visit","async","has","add","test","transformRequest","Promise","all","importedModules","getModuleAssets","skipModules","clientImportedModules","size","subModule","transformResult","includes","code","match","groups","style","content","console","warn","chalk","yellowBright","script","image","font","getEarlyHints","headers","Headers","append","injectAssets","routerContext","html","matches","htmlAssets","isModulePreload","header","replace"],"mappings":"yIA4BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,KAAA,MACD,CALD,CAAKA,IAAAA,EAAS,CAAA,IA4Bd,MAAMC,EAIMC,gBAAsC,KAK7BC,OAKAC,cAKAC,KAKAC,SAKAC,aAAe,gBAKfC,eAAiB,uBAKjBC,YAKAC,SAKAC,eAKTC,aAAgD,KAK1D,WAAAC,CACEV,GACAG,SAAEA,EAAQG,YAAEA,EAAWC,SAAEA,EAAQC,eAAEA,GAAuC,IAE1EG,KAAKX,OAASA,EACdW,KAAKT,KAAOF,EAAOY,YAAYV,KAC/BS,KAAKR,SAAWA,EAChBQ,KAAKL,YAAcA,GAAeN,EAAOa,WAAWb,QAAQc,QAAQC,MACpEJ,KAAKV,cAAgB,IAAIe,EAAchB,EAAQM,GAC/CK,KAAKJ,SAAWA,EAChBI,KAAKH,eAAiBA,CACxB,CAKO,UAAOS,CAAIjB,EAAsBkB,EAA6B,IAKnE,OAJ6B,OAAzBpB,EAAYqB,WACdrB,EAAYqB,SAAW,IAAIrB,EAAYE,EAAQkB,IAG1CpB,EAAYqB,QACrB,CAKU,SAAAC,GACR,OAAOC,EAAKP,QAAQH,KAAKT,KAAMS,KAAKR,UAAY,GAClD,CAKU,qBAAAmB,GACR,MAAO,GAAGX,KAAKS,sBAAsBT,KAAKN,gBAC5C,CAKU,kBAAAkB,GACR,MAAMC,EAAoBH,EAAKP,QAAQH,KAAKT,KAAM,GAAGS,KAAKR,UAAY,mBAChEsB,EAAoB,GAAGD,KAAqBb,KAAKP,eAEvD,IAAKsB,EAAGC,WAAWF,GACjB,MAAO,CAAA,EAGT,MAAMG,EAASC,KAAKC,MAClBJ,EAAGK,aAAaN,EAAmB,CAAEO,SAAU,WAUjD,OAPAN,EAAGO,OAAO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K,MACL,IAAK,MACL,IAAK,OACL,IAAK,QACH,OAAO9J,EAAU+J,KAEnB,QACE,OAAO,KAEb,CAKO,aAAAC,CAAcrG,GACnB,MAAMsG,EAAU,IAAIC,QAUpB,OARAvG,EAAOd,QAAQ,EAAG6B,OAAMa,UACjBb,GAAS,CAAC,QAAS,UAAUyE,SAASzE,IAI3CuF,EAAQE,OAAO,OAAQ,IAAI5E,uBAAyBb,OAG/CuF,CACT,CAKO,YAAAG,EAAaC,cAAEA,EAAaC,KAAEA,IACnC,MAAM3G,EAAS7C,KAAK+F,UAAUwD,GAAeE,SACvCC,EAAa7G,EAChBqD,IAAI,EAAGtC,OAAMa,MAAKE,YAAW+D,UAAU,OACtC,OAAQ9E,GACN,KAAK1E,EAAUuJ,MACb,OAAOzI,KAAKX,OAAOa,UACf,4BAA4BuE,MAAQiE,YACpC,gCAAgCjE,MAEtC,KAAKvF,EAAU6J,OACb,OAAOpE,EACH3E,KAAKX,OAAOsK,gBAEV,2DAA2DlF,MAC3D,KACF,gDAAgDA,gBAGxD,OAAO,OAERrC,OAAOC,SAIV,OAFAmH,EAAKI,OAASJ,EAAKI,OAAOC,QAAQ,UAAW,GAAGH,EAAWpH,KAAK,gBAEzDtC,KAAKkJ,cAAcrG,EAC5B"}
|
package/workflow/Dockerfile
CHANGED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { Response as ExpressResponse } from 'express';
|
|
2
|
-
import { StaticHandlerContext } from 'react-router';
|
|
3
|
-
/**
|
|
4
|
-
* Handle router or server context response
|
|
5
|
-
*/
|
|
6
|
-
declare const handleResponse: (res: ExpressResponse, response: Response | StaticHandlerContext | null, defaultStatus?: number) => number | undefined;
|
|
7
|
-
export { handleResponse as default };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handle-response.js","sources":["../../src/helpers/handle-response.ts"],"sourcesContent":["import type { Response as ExpressResponse } from 'express';\nimport type { StaticHandlerContext } from 'react-router';\n\n/**\n * Handle router or server context response\n */\nconst handleResponse = (\n res: ExpressResponse,\n response: Response | StaticHandlerContext | null,\n defaultStatus = 200,\n): number | undefined => {\n if (!(response instanceof Response)) {\n return defaultStatus;\n }\n\n // redirect\n if (response.status >= 300 && response.status < 400) {\n res.redirect(response.status, response.headers.get('Location')!);\n\n return;\n }\n\n return response.status ?? defaultStatus;\n};\n\nexport default handleResponse;\n"],"names":["handleResponse","res","response","defaultStatus","Response","status","redirect","headers","get"],"mappings":"AAMA,MAAMA,EAAiB,CACrBC,EACAC,EACAC,EAAgB,MAEVD,aAAoBE,SAKtBF,EAASG,QAAU,KAAOH,EAASG,OAAS,SAC9CJ,EAAIK,SAASJ,EAASG,OAAQH,EAASK,QAAQC,IAAI,aAK9CN,EAASG,QAAUF,EAVjBA"}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { Request as ExpressRequest } from 'express';
|
|
2
|
-
/**
|
|
3
|
-
* Convert the incoming Express request into a Fetch request, which is what the static handler methods operate on.
|
|
4
|
-
* @see https://reactrouter.com/en/main/guides/ssr
|
|
5
|
-
*/
|
|
6
|
-
declare function createFetchRequest(req: ExpressRequest): Request;
|
|
7
|
-
export { createFetchRequest as default };
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){const o=`${e.protocol}://${e.get("host")}`,t=new URL(e.originalUrl||e.url,o),r=new AbortController;e.on("close",(()=>r.abort()));const n=new Headers;for(const[o,t]of Object.entries(e.headers))if(t)if(Array.isArray(t))for(const e of t)n.append(o,e);else n.set(o,t);const s={method:e.method,headers:n,signal:r.signal,body:void 0};return"GET"!==e.method&&"HEAD"!==e.method&&(s.body=e.body),new Request(t.href,s)}export{e as default};
|
|
2
|
-
//# sourceMappingURL=create-fetch-request.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"create-fetch-request.js","sources":["../../src/node/create-fetch-request.ts"],"sourcesContent":["import type { Request as ExpressRequest } from 'express';\n\n/**\n * Convert the incoming Express request into a Fetch request, which is what the static handler methods operate on.\n * @see https://reactrouter.com/en/main/guides/ssr\n */\nfunction createFetchRequest(req: ExpressRequest): Request {\n const origin = `${req.protocol}://${req.get('host') as string}`;\n // Note: This had to take originalUrl into account for presumably vite's proxying\n const url = new URL(req.originalUrl || req.url, origin);\n const controller = new AbortController();\n\n req.on('close', () => controller.abort());\n\n const headers = new Headers();\n\n for (const [key, values] of Object.entries(req.headers)) {\n if (values) {\n if (Array.isArray(values)) {\n for (const value of values) {\n headers.append(key, value);\n }\n } else {\n headers.set(key, values);\n }\n }\n }\n\n const init: RequestInit = {\n method: req.method,\n headers,\n signal: controller.signal,\n body: undefined,\n };\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n init.body = req.body as BodyInit;\n }\n\n return new Request(url.href, init);\n}\n\nexport default createFetchRequest;\n"],"names":["createFetchRequest","req","origin","protocol","get","url","URL","originalUrl","controller","AbortController","on","abort","headers","Headers","key","values","Object","entries","Array","isArray","value","append","set","init","method","signal","body","undefined","Request","href"],"mappings":"AAMA,SAASA,EAAmBC,GAC1B,MAAMC,EAAS,GAAGD,EAAIE,cAAcF,EAAIG,IAAI,UAEtCC,EAAM,IAAIC,IAAIL,EAAIM,aAAeN,EAAII,IAAKH,GAC1CM,EAAa,IAAIC,gBAEvBR,EAAIS,GAAG,SAAS,IAAMF,EAAWG,UAEjC,MAAMC,EAAU,IAAIC,QAEpB,IAAK,MAAOC,EAAKC,KAAWC,OAAOC,QAAQhB,EAAIW,SAC7C,GAAIG,EACF,GAAIG,MAAMC,QAAQJ,GAChB,IAAK,MAAMK,KAASL,EAClBH,EAAQS,OAAOP,EAAKM,QAGtBR,EAAQU,IAAIR,EAAKC,GAKvB,MAAMQ,EAAoB,CACxBC,OAAQvB,EAAIuB,OACZZ,UACAa,OAAQjB,EAAWiB,OACnBC,UAAMC,GAOR,MAJmB,QAAf1B,EAAIuB,QAAmC,SAAfvB,EAAIuB,SAC9BD,EAAKG,KAAOzB,EAAIyB,MAGX,IAAIE,QAAQvB,EAAIwB,KAAMN,EAC/B"}
|
package/node/entry.d.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { Server } from 'node:net';
|
|
3
|
-
import { CompressionOptions } from 'compression';
|
|
4
|
-
import { Express, Request } from 'express';
|
|
5
|
-
import { Response as ExpressResponse } from "express";
|
|
6
|
-
import { FC, PropsWithChildren } from 'react';
|
|
7
|
-
import { createStaticHandler } from 'react-router';
|
|
8
|
-
import { ServeStaticOptions } from 'serve-static';
|
|
9
|
-
import { Logger } from 'vite';
|
|
10
|
-
import { TRouteObject } from "../interfaces/route-object.js";
|
|
11
|
-
import { IRenderOptions, TRender } from "./render.js";
|
|
12
|
-
import ServerApi from "../services/server-api.js";
|
|
13
|
-
import ServerConfig from "../services/server-config.js";
|
|
14
|
-
interface IInitServerRequestOut<T = Record<string, any>> {
|
|
15
|
-
appProps?: T;
|
|
16
|
-
hasEarlyHints?: boolean;
|
|
17
|
-
shouldSkip?: boolean;
|
|
18
|
-
shouldCancel?: boolean;
|
|
19
|
-
}
|
|
20
|
-
interface IEntrypointOptions<TAppProps = Record<string, any>> {
|
|
21
|
-
onServerCreated?: (app: Express, serverApi: ServerApi) => Promise<void> | void;
|
|
22
|
-
onServerStarted?: (app: Express, serverApi: ServerApi, server: Server) => Promise<void> | void;
|
|
23
|
-
onRequest?: (req: Request, res: ExpressResponse) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;
|
|
24
|
-
onRouterReady?: IRenderOptions<TAppProps>['onRouterReady'];
|
|
25
|
-
onShellReady?: IRenderOptions<TAppProps>['onShellReady'];
|
|
26
|
-
onShellError?: IRenderOptions<TAppProps>['onShellError'];
|
|
27
|
-
onResponse?: IRenderOptions<TAppProps>['onResponse'];
|
|
28
|
-
onError?: IRenderOptions<TAppProps>['onError'];
|
|
29
|
-
getState?: IRenderOptions<TAppProps>['getState'];
|
|
30
|
-
}
|
|
31
|
-
interface IPrepareRenderOut<TAppProps = Record<string, any>> {
|
|
32
|
-
render: TRender;
|
|
33
|
-
init: IEntryServerOptions<TAppProps>['init'];
|
|
34
|
-
routes: TRouteObject[];
|
|
35
|
-
abortDelay?: number;
|
|
36
|
-
loggerProd?: Logger;
|
|
37
|
-
loggerDev?: Logger;
|
|
38
|
-
middlewares?: {
|
|
39
|
-
compression?: CompressionOptions | false;
|
|
40
|
-
expressStatic?: (ServeStaticOptions & {
|
|
41
|
-
basename?: string;
|
|
42
|
-
}) | false;
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
interface IAppServerProps<T = Record<string, any>> {
|
|
46
|
-
server: T;
|
|
47
|
-
}
|
|
48
|
-
type TApp<T> = FC<PropsWithChildren<Record<string, any> & IAppServerProps<T>>>;
|
|
49
|
-
interface IEntryServerOptions<TAppProps = Record<string, any>> {
|
|
50
|
-
abortDelay?: number;
|
|
51
|
-
init?: (params: {
|
|
52
|
-
config: ServerConfig;
|
|
53
|
-
}) => IEntrypointOptions<TAppProps> | Promise<IEntrypointOptions<TAppProps>>;
|
|
54
|
-
loggerProd?: IPrepareRenderOut['loggerProd'];
|
|
55
|
-
loggerDev?: IPrepareRenderOut['loggerDev'];
|
|
56
|
-
middlewares?: IPrepareRenderOut['middlewares'];
|
|
57
|
-
routerOptions?: Parameters<typeof createStaticHandler>[1];
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Render server side application
|
|
61
|
-
*/
|
|
62
|
-
declare function entry<TAppProps>(App: TApp<TAppProps>, routes: TRouteObject[], { init, routerOptions, ...rest }?: IEntryServerOptions<TAppProps>): IPrepareRenderOut<TAppProps>;
|
|
63
|
-
export { entry as default, IInitServerRequestOut, IEntrypointOptions, IPrepareRenderOut, IAppServerProps, TApp, IEntryServerOptions };
|
package/node/entry.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"entry.js","sources":["../../src/node/entry.tsx"],"sourcesContent":["import type { Server } from 'node:net';\nimport type { CompressionOptions } from 'compression';\nimport type { Express, Request, Response as ExpressResponse } from 'express';\nimport type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router';\nimport { createStaticHandler } from 'react-router';\nimport type { ServeStaticOptions } from 'serve-static';\nimport type { Logger } from 'vite';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IRenderOptions, IRenderParams, TRender } from '@node/render';\nimport render from '@node/render';\nimport type ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface IInitServerRequestOut<T = Record<string, any>> {\n appProps?: T;\n hasEarlyHints?: boolean;\n shouldSkip?: boolean;\n shouldCancel?: boolean;\n}\n\nexport interface IEntrypointOptions<TAppProps = Record<string, any>> {\n onServerCreated?: (app: Express, serverApi: ServerApi) => Promise<void> | void;\n onServerStarted?: (app: Express, serverApi: ServerApi, server: Server) => Promise<void> | void;\n onRequest?: (\n req: Request,\n res: ExpressResponse,\n ) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;\n onRouterReady?: IRenderOptions<TAppProps>['onRouterReady'];\n onShellReady?: IRenderOptions<TAppProps>['onShellReady'];\n onShellError?: IRenderOptions<TAppProps>['onShellError'];\n onResponse?: IRenderOptions<TAppProps>['onResponse'];\n onError?: IRenderOptions<TAppProps>['onError'];\n getState?: IRenderOptions<TAppProps>['getState'];\n}\n\nexport interface IPrepareRenderOut<TAppProps = Record<string, any>> {\n render: TRender;\n init: IEntryServerOptions<TAppProps>['init'];\n routes: TRouteObject[];\n abortDelay?: number;\n loggerProd?: Logger;\n loggerDev?: Logger;\n middlewares?: {\n compression?: CompressionOptions | false;\n // basename should be same as vite 'base' config\n expressStatic?: (ServeStaticOptions & { basename?: string }) | false;\n };\n}\n\nexport interface IAppServerProps<T = Record<string, any>> {\n server: T;\n}\n\nexport type TApp<T> = FC<PropsWithChildren<Record<string, any> & IAppServerProps<T>>>;\n\nexport interface IEntryServerOptions<TAppProps = Record<string, any>> {\n abortDelay?: number;\n init?: (params: {\n config: ServerConfig;\n }) => IEntrypointOptions<TAppProps> | Promise<IEntrypointOptions<TAppProps>>;\n loggerProd?: IPrepareRenderOut['loggerProd'];\n loggerDev?: IPrepareRenderOut['loggerDev'];\n middlewares?: IPrepareRenderOut['middlewares'];\n routerOptions?: Parameters<typeof createStaticHandler>[1];\n}\n\n/**\n * Render server side application\n */\nfunction entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init, routerOptions, ...rest }: IEntryServerOptions<TAppProps> = {},\n): IPrepareRenderOut<TAppProps> {\n const handler = createStaticHandler(routes as RouteObject[], routerOptions);\n\n return {\n render: render.bind(null, { handler, App } as IRenderParams<TAppProps>) as TRender,\n init,\n routes,\n ...rest,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","routerOptions","rest","handler","createStaticHandler","render","bind"],"mappings":"8EAsEA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,KAAkBC,GAAyC,IAEnE,MAAMC,EAAUC,EAAoBL,EAAyBE,GAE7D,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASL,QACrCE,OACAD,YACGG,EAEP"}
|
package/node/render.d.ts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { Request } from 'express';
|
|
2
|
-
import { Response as ExpressResponse } from "express";
|
|
3
|
-
import { StaticHandlerContext, StaticHandler } from 'react-router';
|
|
4
|
-
import StreamError from "../constants/stream-error.js";
|
|
5
|
-
import { IServerContext } from "../context/server.js";
|
|
6
|
-
import { IObtainStreamErrorOut } from "../helpers/obtain-stream-error.js";
|
|
7
|
-
import { TApp } from "./entry.js";
|
|
8
|
-
import ServerConfig from "../services/server-config.js";
|
|
9
|
-
interface IRequestContext<TAppProps = Record<any, any>> {
|
|
10
|
-
req: Request;
|
|
11
|
-
res: ExpressResponse;
|
|
12
|
-
appProps: NonNullable<TAppProps>;
|
|
13
|
-
html: {
|
|
14
|
-
header: string;
|
|
15
|
-
footer: string;
|
|
16
|
-
};
|
|
17
|
-
routerContext?: StaticHandlerContext;
|
|
18
|
-
serverContext?: IServerContext;
|
|
19
|
-
isStream?: boolean;
|
|
20
|
-
hasEarlyHints?: boolean;
|
|
21
|
-
didError?: StreamError;
|
|
22
|
-
}
|
|
23
|
-
type TRender<TAppProps = Record<any, any>> = (config: ServerConfig, context: IRequestContext<TAppProps>, options: IRenderOptions) => Promise<void>;
|
|
24
|
-
interface IRenderParams<TAppProps = Record<string, any>> {
|
|
25
|
-
App: TApp<TAppProps>;
|
|
26
|
-
handler: StaticHandler;
|
|
27
|
-
}
|
|
28
|
-
interface IRenderOptions<TAppProps = Record<string, any>> {
|
|
29
|
-
abortDelay?: number;
|
|
30
|
-
onRouterReady?: (params: {
|
|
31
|
-
context: IRequestContext<TAppProps>;
|
|
32
|
-
}) => Promise<IRouterReadyOut> | IRouterReadyOut;
|
|
33
|
-
onShellReady?: (params: {
|
|
34
|
-
context: IRequestContext<TAppProps>;
|
|
35
|
-
}) => IShellReadyOut;
|
|
36
|
-
onShellError?: (params: {
|
|
37
|
-
context: IRequestContext<TAppProps>;
|
|
38
|
-
error: Error;
|
|
39
|
-
}) => string | undefined | void;
|
|
40
|
-
onError?: (params: {
|
|
41
|
-
context: IRequestContext<TAppProps>;
|
|
42
|
-
error: IObtainStreamErrorOut;
|
|
43
|
-
}) => void;
|
|
44
|
-
onResponse?: (params: {
|
|
45
|
-
context: IRequestContext<TAppProps>;
|
|
46
|
-
html: string;
|
|
47
|
-
}) => string | undefined | void;
|
|
48
|
-
getState?: (params: {
|
|
49
|
-
context: IRequestContext<TAppProps>;
|
|
50
|
-
}) => Record<string, Record<string, any>> | undefined | void;
|
|
51
|
-
}
|
|
52
|
-
interface IRouterReadyOut {
|
|
53
|
-
isStream?: boolean;
|
|
54
|
-
}
|
|
55
|
-
interface IShellReadyOut {
|
|
56
|
-
header?: string;
|
|
57
|
-
footer?: string;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Render application
|
|
61
|
-
*/
|
|
62
|
-
declare function render({ App, handler }: IRenderParams, // @see entry (bind)
|
|
63
|
-
config: ServerConfig, context: IRequestContext, { onRouterReady, onShellReady, onResponse, onShellError, onError, getState, abortDelay, }: IRenderOptions): Promise<void>;
|
|
64
|
-
export { render as default, IRequestContext, TRender, IRenderParams, IRenderOptions, IRouterReadyOut, IShellReadyOut };
|
package/node/render.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"chalk";import r from"react";import{renderToPipeableStream as t}from"react-dom/server";import{createStaticRouter as o,StaticRouterProvider as n}from"react-router";import s from"../constants/stream-error.js";import{ServerProvider as a}from"../context/server.js";import m from"../helpers/handle-response.js";import i from"../helpers/obtain-stream-error.js";import c from"./create-fetch-request.js";import d from"./write-response.js";import l from"../services/ssr-manifest.js";async function p({App:p,handler:u},f,h,{onRouterReady:x,onShellReady:S,onResponse:R,onShellError:g,onError:y,getState:C,abortDelay:E=15e3}){const{req:j,res:b}=h,v=c(j);h.routerContext=await u.query(v,{requestContext:h});const w=m(b,h.routerContext);if(!w)return;l.get(f).injectAssets(h);const{isStream:q=!0}=await(x?.({context:h}))??{};h.isStream=q,h.serverContext={response:null,isServer:!0,basename:h.routerContext?.basename};const T=o(u.dataRoutes,h.routerContext),A=b.write.bind(b),B=f.getLogger();let $;b.write=(e,...r)=>{const t="string"==typeof e,o=t?e:Buffer.from(e).toString(),n=R?.({context:h,html:o});return n?A(t?n:Buffer.from(n),...r):A(e,...r)};const{serverContext:k,routerContext:D,appProps:H}=h,{pipe:L,abort:P}=t(r.createElement(a,{context:k},r.createElement(p,{server:{...H,req:j}},r.createElement(n,{router:T,context:D,hydrate:!1}))),{onShellReady(){q&&d(h,{pipe:L,statusCode:w,onShellReady:S,getState:C})},onAllReady(){clearTimeout($),q||d(h,{pipe:L,statusCode:w,onShellReady:S,getState:C})},onShellError(e){const r=g?.({context:h,error:e})||`<!doctype html><p>Something went wrong: ${e.message}</p>`;b.status(500),b.setHeader("content-type","text/html"),b.send(r)},onError(r){clearTimeout($);const t=i(r),{code:o,message:n}=t,{didError:a}=h;h.didError=a??o,y?.({context:h,error:t}),B.info(e.red(`Stream error. Code: ${o}`)),[s.RenderAborted,s.RenderTimeout,s.RenderCancel].includes(o)?B.info(e.dim(n)):B.error(r)}});$=setTimeout((()=>{h.didError=s.RenderTimeout,P()}),E),j.on("close",(()=>{h.didError=s.RenderCancel,P()}))}export{p as default};
|
|
2
|
-
//# sourceMappingURL=render.js.map
|
package/node/render.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","sources":["../../src/node/render.tsx"],"sourcesContent":["import chalk from 'chalk';\nimport type { Request, Response as ExpressResponse } from 'express';\nimport React from 'react';\nimport { renderToPipeableStream } from 'react-dom/server';\nimport type { StaticHandlerContext, StaticHandler } from 'react-router';\nimport { createStaticRouter, StaticRouterProvider } from 'react-router';\nimport StreamError from '@constants/stream-error';\nimport type { IServerContext } from '@context/server';\nimport { ServerProvider } from '@context/server';\nimport handleResponse from '@helpers/handle-response';\nimport type { IObtainStreamErrorOut } from '@helpers/obtain-stream-error';\nimport obtainStreamError from '@helpers/obtain-stream-error';\nimport createFetchRequest from '@node/create-fetch-request';\nimport type { TApp } from '@node/entry';\nimport writeResponse from '@node/write-response';\nimport type ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\nexport interface IRequestContext<TAppProps = Record<any, any>> {\n req: Request;\n res: ExpressResponse;\n appProps: NonNullable<TAppProps>;\n html: { header: string; footer: string };\n routerContext?: StaticHandlerContext;\n serverContext?: IServerContext;\n isStream?: boolean;\n hasEarlyHints?: boolean;\n didError?: StreamError;\n}\n\nexport type TRender<TAppProps = Record<any, any>> = (\n config: ServerConfig,\n context: IRequestContext<TAppProps>,\n options: IRenderOptions,\n) => Promise<void>;\n\nexport interface IRenderParams<TAppProps = Record<string, any>> {\n App: TApp<TAppProps>;\n handler: StaticHandler;\n}\n\nexport interface IRenderOptions<TAppProps = Record<string, any>> {\n abortDelay?: number;\n onRouterReady?: (params: {\n context: IRequestContext<TAppProps>;\n }) => Promise<IRouterReadyOut> | IRouterReadyOut;\n onShellReady?: (params: { context: IRequestContext<TAppProps> }) => IShellReadyOut;\n onShellError?: (params: {\n context: IRequestContext<TAppProps>;\n error: Error;\n }) => string | undefined | void; // return html or undefined\n onError?: (params: { context: IRequestContext<TAppProps>; error: IObtainStreamErrorOut }) => void;\n onResponse?: (params: {\n context: IRequestContext<TAppProps>;\n html: string;\n }) => string | undefined | void;\n getState?: (params: {\n context: IRequestContext<TAppProps>;\n }) => Record<string, Record<string, any>> | undefined | void;\n}\n\nexport interface IRouterReadyOut {\n isStream?: boolean;\n}\n\nexport interface IShellReadyOut {\n header?: string;\n footer?: string;\n}\n\n/**\n * Render application\n */\nasync function render(\n { App, handler }: IRenderParams, // @see entry (bind)\n config: ServerConfig,\n context: IRequestContext,\n {\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n abortDelay = 15000,\n }: IRenderOptions,\n): Promise<void> {\n const { req, res } = context;\n const fetchRequest = createFetchRequest(req);\n\n context.routerContext = (await handler.query(fetchRequest, {\n requestContext: context,\n })) as StaticHandlerContext;\n\n /**\n * Handle response from page loader, router context can be Response\n */\n const statusCode = handleResponse(res, context.routerContext);\n\n if (!statusCode) {\n return;\n }\n\n SsrManifest.get(config).injectAssets(context);\n\n const { isStream = true } = (await onRouterReady?.({ context })) ?? {};\n\n context.isStream = isStream;\n context.serverContext = {\n response: null,\n isServer: true,\n basename: context.routerContext?.basename,\n };\n\n const router = createStaticRouter(handler.dataRoutes, context.routerContext);\n const write = res.write.bind(res) as (...args: unknown[]) => boolean;\n const Logger = config.getLogger();\n let abortTimer: NodeJS.Timeout | undefined = undefined;\n\n /**\n * Listen response and stream to add possibility modify html on fly\n * E.g. listen stream and append some data\n */\n res.write = (data: string | Uint8Array, ...args): boolean => {\n const isString = typeof data === 'string';\n const html = isString ? data : Buffer.from(data).toString();\n const modifiedHtml = onResponse?.({ context, html });\n\n if (modifiedHtml) {\n return write(isString ? modifiedHtml : Buffer.from(modifiedHtml), ...args);\n }\n\n return write(data, ...args);\n };\n\n const { serverContext, routerContext, appProps } = context;\n\n const { pipe, abort } = renderToPipeableStream(\n <ServerProvider context={serverContext}>\n <App server={{ ...appProps, req }}>\n <StaticRouterProvider router={router} context={routerContext} hydrate={false} />\n </App>\n </ServerProvider>,\n {\n onShellReady(): void {\n if (!isStream) {\n return;\n }\n\n writeResponse(context, {\n pipe,\n statusCode,\n onShellReady,\n getState,\n });\n },\n onAllReady(): void {\n clearTimeout(abortTimer);\n\n if (isStream) {\n return;\n }\n\n writeResponse(context, {\n pipe,\n statusCode,\n onShellReady,\n getState,\n });\n },\n onShellError(e: Error): void {\n const htmlError =\n onShellError?.({ context, error: e }) ||\n `<!doctype html><p>Something went wrong: ${e.message}</p>`;\n\n res.status(500);\n res.setHeader('content-type', 'text/html');\n res.send(htmlError);\n },\n onError(err): void {\n clearTimeout(abortTimer);\n\n const error = obtainStreamError(err);\n const { code, message } = error;\n const { didError } = context;\n\n context.didError = didError ?? code;\n\n onError?.({ context, error });\n Logger.info(chalk.red(`Stream error. Code: ${code}`));\n\n if (\n [StreamError.RenderAborted, StreamError.RenderTimeout, StreamError.RenderCancel].includes(\n code,\n )\n ) {\n Logger.info(chalk.dim(message));\n\n return;\n }\n\n Logger.error(err as string);\n },\n },\n );\n\n // Abandon and switch to client rendering if enough time passes.\n abortTimer = setTimeout(() => {\n context.didError = StreamError.RenderTimeout;\n abort();\n }, abortDelay);\n\n // Detect cancel request\n req.on('close', () => {\n context.didError = StreamError.RenderCancel;\n abort();\n });\n}\n\nexport default render;\n"],"names":["async","render","App","handler","config","context","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","abortDelay","req","res","fetchRequest","createFetchRequest","routerContext","query","requestContext","statusCode","handleResponse","SsrManifest","get","injectAssets","isStream","serverContext","response","isServer","basename","router","createStaticRouter","dataRoutes","write","bind","Logger","getLogger","abortTimer","data","args","isString","html","Buffer","from","toString","modifiedHtml","appProps","pipe","abort","renderToPipeableStream","React","createElement","ServerProvider","server","StaticRouterProvider","hydrate","writeResponse","onAllReady","clearTimeout","e","htmlError","error","message","status","setHeader","send","err","obtainStreamError","code","didError","info","chalk","red","StreamError","RenderAborted","RenderTimeout","RenderCancel","includes","dim","setTimeout","on"],"mappings":"ueAyEAA,eAAeC,GACbC,IAAEA,EAAGC,QAAEA,GACPC,EACAC,GACAC,cACEA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOC,SACPA,EAAQC,WACRA,EAAa,OAGf,MAAMC,IAAEA,EAAGC,IAAEA,GAAQT,EACfU,EAAeC,EAAmBH,GAExCR,EAAQY,oBAAuBd,EAAQe,MAAMH,EAAc,CACzDI,eAAgBd,IAMlB,MAAMe,EAAaC,EAAeP,EAAKT,EAAQY,eAE/C,IAAKG,EACH,OAGFE,EAAYC,IAAInB,GAAQoB,aAAanB,GAErC,MAAMoB,SAAEA,GAAW,SAAgBnB,IAAgB,CAAED,cAAe,CAAA,EAEpEA,EAAQoB,SAAWA,EACnBpB,EAAQqB,cAAgB,CACtBC,SAAU,KACVC,UAAU,EACVC,SAAUxB,EAAQY,eAAeY,UAGnC,MAAMC,EAASC,EAAmB5B,EAAQ6B,WAAY3B,EAAQY,eACxDgB,EAAQnB,EAAImB,MAAMC,KAAKpB,GACvBqB,EAAS/B,EAAOgC,YACtB,IAAIC,EAMJvB,EAAImB,MAAQ,CAACK,KAA8BC,KACzC,MAAMC,EAA2B,iBAATF,EAClBG,EAAOD,EAAWF,EAAOI,OAAOC,KAAKL,GAAMM,WAC3CC,EAAerC,IAAa,CAAEH,UAASoC,SAE7C,OAAII,EACKZ,EAAMO,EAAWK,EAAeH,OAAOC,KAAKE,MAAkBN,GAGhEN,EAAMK,KAASC,EAAK,EAG7B,MAAMb,cAAEA,EAAaT,cAAEA,EAAa6B,SAAEA,GAAazC,GAE7C0C,KAAEA,EAAIC,MAAEA,GAAUC,EACtBC,EAAAC,cAACC,EAAc,CAAC/C,QAASqB,GACvBwB,EAAAC,cAACjD,GAAImD,OAAQ,IAAKP,EAAUjC,QAC1BqC,EAAAC,cAACG,EAAoB,CAACxB,OAAQA,EAAQzB,QAASY,EAAesC,SAAS,MAG3E,CACEhD,eACOkB,GAIL+B,EAAcnD,EAAS,CACrB0C,OACA3B,aACAb,eACAI,YAEJ,EACA8C,aACEC,aAAarB,GAETZ,GAIJ+B,EAAcnD,EAAS,CACrB0C,OACA3B,aACAb,eACAI,YAEJ,EACAF,aAAakD,GACX,MAAMC,EACJnD,IAAe,CAAEJ,UAASwD,MAAOF,KACjC,2CAA2CA,EAAEG,cAE/ChD,EAAIiD,OAAO,KACXjD,EAAIkD,UAAU,eAAgB,aAC9BlD,EAAImD,KAAKL,EACX,EACAlD,QAAQwD,GACNR,aAAarB,GAEb,MAAMwB,EAAQM,EAAkBD,IAC1BE,KAAEA,EAAIN,QAAEA,GAAYD,GACpBQ,SAAEA,GAAahE,EAErBA,EAAQgE,SAAWA,GAAYD,EAE/B1D,IAAU,CAAEL,UAASwD,UACrB1B,EAAOmC,KAAKC,EAAMC,IAAI,uBAAuBJ,MAG3C,CAACK,EAAYC,cAAeD,EAAYE,cAAeF,EAAYG,cAAcC,SAC/ET,GAGFjC,EAAOmC,KAAKC,EAAMO,IAAIhB,IAKxB3B,EAAO0B,MAAMK,EACf,IAKJ7B,EAAa0C,YAAW,KACtB1E,EAAQgE,SAAWI,EAAYE,cAC/B3B,GAAO,GACNpC,GAGHC,EAAImE,GAAG,SAAS,KACd3E,EAAQgE,SAAWI,EAAYG,aAC/B5B,GAAO,GAEX"}
|
package/node/server.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { Server } from 'node:net';
|
|
3
|
-
import { Express } from 'express';
|
|
4
|
-
import ServerConfig from "../services/server-config.js";
|
|
5
|
-
interface ICreateServerOut {
|
|
6
|
-
run: (options?: {
|
|
7
|
-
version?: string;
|
|
8
|
-
isPrintInfo?: boolean;
|
|
9
|
-
}) => Server;
|
|
10
|
-
app: Express;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Create SSR server
|
|
14
|
-
*/
|
|
15
|
-
declare function createServer(config: ServerConfig): Promise<ICreateServerOut>;
|
|
16
|
-
export { createServer as default, ICreateServerOut };
|
package/node/server.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"node:http";import r from"node:https";import t from"path";import s from"compression";import o from"express";import i from"../helpers/print-server-info.js";import a from"../services/prepare-server.js";import n from"../services/server-api.js";async function p(p){const c=o().disable("x-powered-by"),d=new n;p.setApp(c);const m=a.init(p,d);if(!p.isProd){const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:p.mode});c.use(e.middlewares),p.setVite(e)}const{isSPA:l}=p.getParams();if(l||await m.onAppCreated(),p.isProd){const{root:e,publicDir:r}=p.getParams(),{compression:i,expressStatic:a}=m.getMiddlewaresConfig();if(i&&c.use(s(i)),l||c.use(((e,r,t)=>{"/index.html"!==e.url||d.hasAccessIndexHtml()||(e.url="/index-not-found.html"),t()})),a){const{basename:s,...i}=a;c.use(s,o.static(t.resolve(`${e}/${r}`),{...i,index:!!l&&void 0}))}}return l?c.use(/(.*)/,((e,r,t)=>{(async()=>{try{const t=(await m.loadHtml(e)).join("");r.send(t)}catch(e){p.getLogger().error(`Failed to handle request: ${e?.message}`,{error:e}),t()}})()})):c.use(/(.*)/,((e,r,t)=>{(async()=>{try{const[{render:s,onRequest:o,...i},a]=await Promise.all([m.loadEntrypoint(),m.loadHtml(e)]),{appProps:n,hasEarlyHints:c,shouldSkip:d,shouldCancel:l}=await(o?.(e,r))??{},[u,f]=a;if(l)return;if(d)return t();const h={req:e,res:r,hasEarlyHints:c,appProps:n??{},html:{header:u,footer:f}};await s(p,h,i)}catch(e){p.getLogger().error(`Failed to handle request: ${e?.message}`,{error:e}),t()}})()})),{run:({version:t,isPrintInfo:s=!0}={})=>{const{port:o,host:a}=p.getParams(),n=Boolean(p.getVite()?.config?.server?.https);p.isHost&&!p.isProd&&(p.getVite().config.server.host=a);const l=(n?r.createServer(p.getVite().config.server.https,c):e.createServer(c)).listen(o,a,(()=>{m.onServerStarted?.(c,d,l),s&&i(p,{version:t,server:l})}));return l},app:c}}export{p as default};
|
|
2
|
-
//# sourceMappingURL=server.js.map
|
package/node/server.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n const prepareServer = PrepareServer.init(config, serverApi);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n }\n\n const { isSPA } = config.getParams();\n\n if (!isSPA) {\n await prepareServer.onAppCreated();\n }\n\n if (config.isProd) {\n const { root, publicDir } = config.getParams();\n const { compression: compressionConfig, expressStatic } = prepareServer.getMiddlewaresConfig();\n\n if (compressionConfig) {\n app.use(compression(compressionConfig));\n }\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n if (expressStatic) {\n const { basename, ...expressStaticOpts } = expressStatic;\n\n app.use(\n basename!,\n express.static(path.resolve(`${root}/${publicDir}`), {\n ...expressStaticOpts,\n index: isSPA ? undefined : false,\n }),\n );\n }\n }\n\n // SSR mode\n if (!isSPA) {\n app.use(/(.*)/, (req, res, next) => {\n void (async () => {\n try {\n const [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints, shouldSkip, shouldCancel } =\n (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n if (shouldCancel) {\n return;\n }\n\n if (shouldSkip) {\n return next();\n }\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use(/(.*)/, (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n void prepareServer.onServerStarted?.(app, serverApi, server);\n\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","prepareServer","PrepareServer","init","isProd","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","use","middlewares","setVite","isSPA","getParams","onAppCreated","root","publicDir","compression","compressionConfig","expressStatic","getMiddlewaresConfig","req","_","next","url","hasAccessIndexHtml","basename","expressStaticOpts","static","path","resolve","index","undefined","res","html","loadHtml","join","send","e","getLogger","error","message","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","shouldSkip","shouldCancel","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","onServerStarted","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAEtBL,EAAOM,OAAOL,GAEd,MAAMM,EAAgBC,EAAcC,KAAKT,EAAQI,GAEjD,IAAKJ,EAAOU,OAAQ,CAIlB,MAAMC,cACEC,OAAO,SACbb,aAAa,CACbc,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAMnB,EAAOmB,OAIflB,EAAImB,IAAIT,EAAKU,aAEbrB,EAAOsB,QAAQX,EACjB,CAEA,MAAMY,MAAEA,GAAUvB,EAAOwB,YAMzB,GAJKD,SACGhB,EAAckB,eAGlBzB,EAAOU,OAAQ,CACjB,MAAMgB,KAAEA,EAAIC,UAAEA,GAAc3B,EAAOwB,aAC3BI,YAAaC,EAAiBC,cAAEA,GAAkBvB,EAAcwB,uBAiBxE,GAfIF,GACF5B,EAAImB,IAAIQ,EAAYC,IAGjBN,GAEHtB,EAAImB,K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AAQzE,EAAO0E,WAAW1E,QAAQa,QAAQ8D,OAGtD3E,EAAO4E,SAAW5E,EAAOU,SAC3BV,EAAO0E,UAAW1E,OAAOa,OAAO0D,KAAOA,GAGzC,MAAM1D,GACJ2D,EACIG,EAAM5E,aAAaC,EAAO0E,UAAW1E,OAAOa,OAAO8D,MAAQ1E,GAC3D4E,EAAK9E,aAAaE,IACtB6E,OAAOR,EAAMC,GAAM,KACdhE,EAAcwE,kBAAkB9E,EAAKG,EAAWS,GAEhDwD,GAIAW,EAAgBhF,EAAQ,CAAEoE,UAASvD,UAAS,IAGnD,OAAOA,CAAM,EAEfZ,MAEJ"}
|
package/node/write-response.d.ts
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/// <reference types="react-dom" />
|
|
2
|
-
import { PipeableStream } from 'react-dom/server';
|
|
3
|
-
import { IRenderOptions, IRequestContext } from "./render.js";
|
|
4
|
-
interface IWriteResponseParams {
|
|
5
|
-
pipe: PipeableStream['pipe'];
|
|
6
|
-
onShellReady: IRenderOptions['onShellReady'];
|
|
7
|
-
getState: IRenderOptions['getState'];
|
|
8
|
-
statusCode?: number;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Send response to client
|
|
12
|
-
*/
|
|
13
|
-
declare const writeResponse: (context: IRequestContext, params: IWriteResponseParams) => void;
|
|
14
|
-
export { writeResponse as default };
|
package/node/write-response.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"../helpers/build-custom-state.js";import t from"../helpers/build-router-state.js";import r from"../helpers/handle-response.js";const o=(o,s)=>{const{res:n,didError:d,serverContext:i,routerContext:a,html:l}=o,{pipe:p,onShellReady:f,getState:h}=s;let{statusCode:m}=s;if(m=r(n,i.response,m),!m)return;if(d){const e=n.end.bind(n);n.end=(...t)=>(n.write(c||l.footer),e(...t))}n.status(m),n.setHeader("content-type","text/html");const{header:u,footer:c}=f?.({context:o})??{},x=t(a),b=e(h?.({context:o}));l.footer=x+b+l.footer,n.write(u||l.header),p(n),d||n.write(c||l.footer)};export{o as default};
|
|
2
|
-
//# sourceMappingURL=write-response.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"write-response.js","sources":["../../src/node/write-response.ts"],"sourcesContent":["import type { Response as ExpressResponse } from 'express';\nimport type { PipeableStream } from 'react-dom/server';\nimport buildCustomState from '@helpers/build-custom-state';\nimport buildRouterState from '@helpers/build-router-state';\nimport handleResponse from '@helpers/handle-response';\nimport type { IRenderOptions, IRequestContext } from '@node/render';\n\ninterface IWriteResponseParams {\n pipe: PipeableStream['pipe'];\n onShellReady: IRenderOptions['onShellReady'];\n getState: IRenderOptions['getState'];\n statusCode?: number; // default status\n}\n\n/**\n * Send response to client\n */\nconst writeResponse = (context: IRequestContext, params: IWriteResponseParams): void => {\n const { res, didError, serverContext, routerContext, html } = context;\n const { pipe, onShellReady, getState } = params;\n let { statusCode } = params;\n\n // handle response from server components (navigate, status)\n statusCode = handleResponse(res, serverContext!.response, statusCode);\n\n if (!statusCode) {\n return;\n }\n\n // catch close connection from React and write footer\n if (didError) {\n const end = res.end.bind(res) as ExpressResponse['end'];\n\n res.end = (...args: unknown[]): ExpressResponse => {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n\n // @ts-ignore\n return end(...args);\n };\n }\n\n res.status(statusCode);\n res.setHeader('content-type', 'text/html');\n\n const { header: modifiedHeader, footer: modifiedFooter } = onShellReady?.({ context }) ?? {};\n const routerState = buildRouterState(routerContext!);\n const customState = buildCustomState(getState?.({ context }));\n\n html.footer = routerState + customState + html.footer;\n\n // send first part of app shell\n res.write(modifiedHeader || html.header);\n // start streaming app\n pipe(res);\n\n if (!didError) {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n }\n};\n\nexport default writeResponse;\n"],"names":["writeResponse","context","params","res","didError","serverContext","routerContext","html","pipe","onShellReady","getState","statusCode","handleResponse","response","end","bind","args","write","modifiedFooter","footer","status","setHeader","header","modifiedHeader","routerState","buildRouterState","customState","buildCustomState"],"mappings":"6IAiBA,MAAMA,EAAgB,CAACC,EAA0BC,KAC/C,MAAMC,IAAEA,EAAGC,SAAEA,EAAQC,cAAEA,EAAaC,cAAEA,EAAaC,KAAEA,GAASN,GACxDO,KAAEA,EAAIC,aAAEA,EAAYC,SAAEA,GAAaR,EACzC,IAAIS,WAAEA,GAAeT,EAKrB,GAFAS,EAAaC,EAAeT,EAAKE,EAAeQ,SAAUF,IAErDA,EACH,OAIF,GAAIP,EAAU,CACZ,MAAMU,EAAMX,EAAIW,IAAIC,KAAKZ,GAEzBA,EAAIW,IAAM,IAAIE,KAEZb,EAAIc,MAAMC,GAAkBX,EAAKY,QAG1BL,KAAOE,GAElB,CAEAb,EAAIiB,OAAOT,GACXR,EAAIkB,UAAU,eAAgB,aAE9B,MAAQC,OAAQC,EAAgBJ,OAAQD,GAAmBT,IAAe,CAAER,aAAc,CAAA,EACpFuB,EAAcC,EAAiBnB,GAC/BoB,EAAcC,EAAiBjB,IAAW,CAAET,aAElDM,EAAKY,OAASK,EAAcE,EAAcnB,EAAKY,OAG/ChB,EAAIc,MAAMM,GAAkBhB,EAAKe,QAEjCd,EAAKL,GAEAC,GAEHD,EAAIc,MAAMC,GAAkBX,EAAKY,OACnC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"fs";import t from"node:path";import r from"node:process";import{pathToFileURL as i}from"node:url";import o from"chalk";import s from"./server-api.js";class n{config;serverApi;entrypoint;onServerCreated;onServerStarted;html;middlewaresConfigs;constructor(e,t){this.config=e,this.serverApi=t??new s}static init(e,t){return new n(e,t)}async loadEntrypoint(e=!0){if(this.entrypoint&&this.config.isProd)return this.entrypoint;const{root:s,isProd:n,serverFile:a}=this.config.getParams(),l=t.resolve(`${s}/${a}`);let d;try{d=n?(await import(i(l).toString())).default:(await this.config.getVite().ssrLoadModule(l,{fixStacktrace:!0})).default}catch(e){if(e instanceof Error&&e.message.includes("Cannot find module")&&e.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")}`)),r.exit(1);throw e}!e&&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,onServerStarted:v,...w}=await(g?.({config:this.config}))??{};return this.entrypoint={render:c,routes:h,abortDelay:f,...w},this.onServerCreated=y,this.onServerStarted=v,this.entrypoint}async loadHtml(r){const{isProd:i,root:o,indexFile:s,clientFile:n}=this.config.getParams();this.html&&i||(this.html=e.readFileSync(t.resolve(`${o}/${s}`),"utf-8"));let a=this.html;if(!i){const e=t.posix.normalize(`${this.config.getVite()?.config.base}/${n}`);a=(await this.config.getVite().transformIndexHtml(r.originalUrl,this.html,s)).replace(new RegExp(`<script[^>]*?\\bsrc=["']/?${e}([^"']*)["'][^>]*?\\sasync\\b`,"g"),(e=>e.replace(/\sasync\b/,"")))}return a.split("\x3c!--ssr-outlet--\x3e")}async onAppCreated(){return await this.loadEntrypoint(),await(this.onServerCreated?.(this.config.getApp(),this.serverApi)),this}getMiddlewaresConfig(){const{compression:e,expressStatic:t}=this.middlewaresConfigs??{};return{compression:!1!==e&&{...e??{}},expressStatic:!1!==t&&{...t??{},basename:t?.basename??"/"}}}}export{n as default};
|
|
2
|
-
//# sourceMappingURL=prepare-server.js.map
|