@modern-js/prod-server 1.1.4 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/js/modern/libs/context/context.js +10 -4
  3. package/dist/js/modern/libs/hook-api/route.js +8 -3
  4. package/dist/js/modern/libs/hook-api/template.js +4 -1
  5. package/dist/js/modern/libs/render/cache/page-caches/lru.js +6 -2
  6. package/dist/js/modern/libs/render/cache/spr.js +7 -4
  7. package/dist/js/modern/libs/render/reader.js +4 -1
  8. package/dist/js/modern/libs/route/index.js +6 -2
  9. package/dist/js/modern/libs/route/matcher.js +10 -4
  10. package/dist/js/modern/libs/route/route.js +20 -9
  11. package/dist/js/modern/server/index.js +12 -6
  12. package/dist/js/modern/server/modern-server.js +53 -25
  13. package/dist/js/node/libs/context/context.js +10 -4
  14. package/dist/js/node/libs/hook-api/route.js +8 -3
  15. package/dist/js/node/libs/hook-api/template.js +5 -1
  16. package/dist/js/node/libs/render/cache/page-caches/lru.js +6 -2
  17. package/dist/js/node/libs/render/cache/spr.js +6 -6
  18. package/dist/js/node/libs/render/reader.js +4 -1
  19. package/dist/js/node/libs/route/index.js +6 -2
  20. package/dist/js/node/libs/route/matcher.js +10 -4
  21. package/dist/js/node/libs/route/route.js +20 -9
  22. package/dist/js/node/server/index.js +12 -6
  23. package/dist/js/node/server/modern-server.js +53 -25
  24. package/dist/types/server/modern-server.d.ts +1 -1
  25. package/package.json +30 -8
  26. package/.eslintrc.js +0 -8
  27. package/dist/js/styles/tsconfig.json +0 -12
  28. package/jest.config.js +0 -8
  29. package/modern.config.js +0 -2
  30. package/src/constants.ts +0 -31
  31. package/src/index.ts +0 -19
  32. package/src/libs/context/context.ts +0 -178
  33. package/src/libs/context/index.ts +0 -7
  34. package/src/libs/hook-api/route.ts +0 -42
  35. package/src/libs/hook-api/template.ts +0 -53
  36. package/src/libs/loadConfig.ts +0 -59
  37. package/src/libs/metrics.ts +0 -15
  38. package/src/libs/proxy.ts +0 -44
  39. package/src/libs/render/cache/__tests__/cache.fun.test.ts +0 -94
  40. package/src/libs/render/cache/__tests__/cache.test.ts +0 -240
  41. package/src/libs/render/cache/__tests__/cacheable.ts +0 -44
  42. package/src/libs/render/cache/__tests__/error-configuration.ts +0 -34
  43. package/src/libs/render/cache/__tests__/matched-cache.ts +0 -88
  44. package/src/libs/render/cache/index.ts +0 -73
  45. package/src/libs/render/cache/page-caches/index.ts +0 -11
  46. package/src/libs/render/cache/page-caches/lru.ts +0 -38
  47. package/src/libs/render/cache/spr.ts +0 -300
  48. package/src/libs/render/cache/type.ts +0 -59
  49. package/src/libs/render/cache/util.ts +0 -94
  50. package/src/libs/render/index.ts +0 -79
  51. package/src/libs/render/measure.ts +0 -66
  52. package/src/libs/render/modern/browser-list.ts +0 -7
  53. package/src/libs/render/modern/index.ts +0 -41
  54. package/src/libs/render/modern/module.d.ts +0 -4
  55. package/src/libs/render/reader.ts +0 -119
  56. package/src/libs/render/ssr.ts +0 -69
  57. package/src/libs/render/static.ts +0 -52
  58. package/src/libs/render/type.ts +0 -38
  59. package/src/libs/route/index.ts +0 -76
  60. package/src/libs/route/matcher.ts +0 -108
  61. package/src/libs/route/route.ts +0 -34
  62. package/src/libs/serve-file.ts +0 -34
  63. package/src/server/index.ts +0 -232
  64. package/src/server/modern-server-split.ts +0 -93
  65. package/src/server/modern-server.ts +0 -620
  66. package/src/tsconfig.json +0 -12
  67. package/src/type.ts +0 -95
  68. package/src/utils.ts +0 -116
  69. package/tsconfig.json +0 -11
@@ -1,119 +0,0 @@
1
- import { Buffer } from 'buffer';
2
- import { fs } from '@modern-js/utils';
3
- import LRU from 'lru-cache';
4
-
5
- const Byte = 1;
6
- const KB = 1024 * Byte;
7
- const MB = 1024 * KB;
8
-
9
- type FileCache = {
10
- content: Buffer;
11
- mtime: Date;
12
- };
13
-
14
- const getContentLength = (cache: FileCache) => cache.content.length;
15
-
16
- const createCacheItem = async (filepath: string, mtime: Date) => {
17
- const content = await fs.readFile(filepath);
18
-
19
- return {
20
- content,
21
- mtime,
22
- };
23
- };
24
- export class LruReader {
25
- private readonly cache: LRU<string, FileCache>;
26
-
27
- // private timer?: NodeJS.Timeout;
28
-
29
- constructor() {
30
- this.cache = new LRU({
31
- max: 256 * MB,
32
- length: getContentLength,
33
- maxAge: 5 * 60 * 5000, // 60s
34
- });
35
- }
36
-
37
- public init() {
38
- // this.timeTask();
39
- }
40
-
41
- public close() {
42
- // if (this.timer) {
43
- // clearInterval(this.timer);
44
- // }
45
- }
46
-
47
- public async read(filepath: string) {
48
- if (this.cache.has(filepath)) {
49
- const { content } = this.cache.get(filepath)!;
50
-
51
- return { content };
52
- }
53
-
54
- if (!fs.existsSync(filepath)) {
55
- return null;
56
- }
57
-
58
- const stat = fs.statSync(filepath);
59
- if (stat.isDirectory()) {
60
- return null;
61
- }
62
-
63
- // if file more than 20 MB
64
- if (stat.size > 20 * MB) {
65
- return null;
66
- }
67
-
68
- const item = await createCacheItem(filepath, stat.mtime);
69
- this.cache.set(filepath, item);
70
- return item;
71
- }
72
-
73
- public update() {
74
- const { cache } = this;
75
- const files = cache.keys();
76
-
77
- for (const filepath of files) {
78
- if (!fs.existsSync(filepath)) {
79
- cache.del(filepath);
80
- }
81
-
82
- try {
83
- const item = cache.get(filepath)!;
84
- const stat = fs.statSync(filepath);
85
- const { mtime } = stat;
86
- // file is modify
87
- if (item.mtime < mtime) {
88
- cache.del(filepath);
89
- }
90
- } catch (e) {
91
- // for safe
92
- cache.del(filepath);
93
- }
94
- }
95
- }
96
-
97
- // private timeTask() {
98
- // this.timer = setInterval(() => this.update, 5 * 60 * 1000).unref();
99
- // }
100
- }
101
-
102
- const reader = new LruReader();
103
-
104
- export const readFile = async (filepath: string) => {
105
- const file = await reader.read(filepath);
106
- return file?.content;
107
- };
108
-
109
- export const updateFile = () => {
110
- reader.update();
111
- };
112
-
113
- export const init = () => {
114
- reader.init();
115
- };
116
-
117
- export const close = () => {
118
- reader.close();
119
- };
@@ -1,69 +0,0 @@
1
- import path from 'path';
2
- import { mime, SERVER_RENDER_FUNCTION_NAME } from '@modern-js/utils';
3
- import cookie from 'cookie';
4
- import { ModernServerContext } from '../context';
5
- import { RenderResult, ServerHookRunner } from '../../type';
6
- import cache from './cache';
7
- import { SSRServerContext } from './type';
8
- import { createLogger, createMetrics } from './measure';
9
-
10
- export const render = async (
11
- ctx: ModernServerContext,
12
- renderOptions: {
13
- distDir: string;
14
- bundle: string;
15
- urlPath: string;
16
- template: string;
17
- entryName: string;
18
- staticGenerate: boolean;
19
- },
20
- runner: ServerHookRunner,
21
- ): Promise<RenderResult> => {
22
- const { urlPath, bundle, distDir, template, entryName, staticGenerate } =
23
- renderOptions;
24
- const bundleJS = path.join(distDir, bundle);
25
-
26
- const context: SSRServerContext = {
27
- request: {
28
- baseUrl: urlPath,
29
- params: ctx.params,
30
- pathname: ctx.path,
31
- host: ctx.host,
32
- query: ctx.query as Record<string, string>,
33
- url: ctx.href,
34
- cookieMap: cookie.parse(ctx.headers.cookie || ''),
35
- headers: ctx.headers,
36
- },
37
- redirection: {},
38
- template,
39
- entryName,
40
- distDir,
41
- staticGenerate,
42
- logger: undefined!,
43
- metrics: undefined!,
44
- };
45
- context.logger = createLogger(context, ctx.logger);
46
- context.metrics = createMetrics(context, ctx.metrics);
47
-
48
- runner.extendSSRContext(context);
49
-
50
- const serverRender = require(bundleJS)[SERVER_RENDER_FUNCTION_NAME];
51
-
52
- const html = await cache(serverRender, ctx)(context);
53
-
54
- const { url, status = 302 } = context.redirection;
55
-
56
- if (url) {
57
- return {
58
- content: url,
59
- contentType: '',
60
- statusCode: status,
61
- redirect: true,
62
- };
63
- }
64
-
65
- return {
66
- content: html,
67
- contentType: mime.contentType('html') as string,
68
- };
69
- };
@@ -1,52 +0,0 @@
1
- import path from 'path';
2
- import { mime } from '@modern-js/utils';
3
- import { RenderResult } from '../../type';
4
- import { ModernServerContext } from '../context';
5
- import { readFile } from './reader';
6
-
7
- export async function handleDirectory(
8
- ctx: ModernServerContext,
9
- entryPath: string,
10
- urlPath: string,
11
- ): Promise<RenderResult | null> {
12
- const { path: pathname } = ctx;
13
- const filepath = path.join(entryPath, trimLeft(pathname, urlPath));
14
-
15
- // If can match accurately, always return the one that matches accurately
16
- let content = await readFile(filepath);
17
- let contentType = mime.contentType(path.extname(filepath) || '');
18
-
19
- // automatic addressing
20
- if (!content) {
21
- if (pathname.endsWith('/')) {
22
- content = await readFile(`${filepath}index.html`);
23
- } else if (!pathname.includes('.')) {
24
- content = await readFile(`${filepath}.html`);
25
- if (!content) {
26
- content = await readFile(`${filepath}/index.html`);
27
- }
28
- }
29
-
30
- // set content-type as html
31
- if (content) {
32
- contentType = mime.contentType('html');
33
- }
34
- }
35
-
36
- if (!content) {
37
- return null;
38
- }
39
-
40
- return {
41
- content,
42
- contentType: contentType || '',
43
- };
44
- }
45
-
46
- const trimLeft = (str: string, prefix: string): string => {
47
- if (str.startsWith(prefix)) {
48
- return str.substring(prefix.length);
49
- }
50
-
51
- return str;
52
- };
@@ -1,38 +0,0 @@
1
- import { BaseSSRServerContext } from '@modern-js/types/server';
2
-
3
- type MetaKeyMap = {
4
- header?: string[];
5
- query?: string[];
6
- };
7
- type MetaKeyMatch = {
8
- header?: MatchMap;
9
- query?: MatchMap;
10
- };
11
- type MatchMap = Record<string, Record<string, string>>;
12
-
13
- export type CacheConfig = {
14
- interval: number;
15
- staleLimit: number | boolean;
16
- level: number;
17
- includes?: MetaKeyMap | null;
18
- excludes?: MetaKeyMap | null;
19
- matches?: MetaKeyMatch | null;
20
- };
21
-
22
- export enum RenderLevel {
23
- CLIENT_RENDER,
24
- SERVER_PREFETCH,
25
- SERVER_RENDER,
26
- }
27
-
28
- export type SSRServerContext = BaseSSRServerContext & {
29
- cacheConfig?: CacheConfig;
30
- staticGenerate?: boolean;
31
- };
32
-
33
- export type ModernSSRReactComponent = React.ComponentType<any> & {
34
- init: (context: SSRServerContext) => Promise<void>;
35
- prefetch: (context: SSRServerContext) => Promise<Record<string, any>>;
36
- };
37
-
38
- export type RenderFunction = (context: SSRServerContext) => Promise<string>;
@@ -1,76 +0,0 @@
1
- import { RouteMatcher } from './matcher';
2
- import { ModernRoute, ModernRouteInterface } from './route';
3
-
4
- export class RouteMatchManager {
5
- public matchers: RouteMatcher[];
6
-
7
- private specs: ModernRouteInterface[] = [];
8
-
9
- constructor() {
10
- this.matchers = [];
11
- }
12
-
13
- // get all routes matches pathname
14
- private filter(pathname: string) {
15
- return this.matchers.reduce((matches, matcher) => {
16
- if (matcher.matchUrlPath(pathname)) {
17
- matches.push(matcher);
18
- }
19
- return matches;
20
- }, [] as RouteMatcher[]);
21
- }
22
-
23
- // get best match from a set of matches
24
- private best(pathname: string, matches: RouteMatcher[]) {
25
- let best: RouteMatcher | undefined;
26
- let matchedLen = 0;
27
-
28
- for (const match of matches) {
29
- const len = match.matchLength(pathname);
30
-
31
- if (len === null) {
32
- continue;
33
- }
34
-
35
- if (len > matchedLen) {
36
- best = match;
37
- matchedLen = len;
38
- }
39
- }
40
-
41
- return best;
42
- }
43
-
44
- // reset routes matcher
45
- public reset(specs: ModernRouteInterface[]) {
46
- this.specs = specs;
47
- const matchers = specs.reduce((ms, spec) => {
48
- ms.push(new RouteMatcher(spec));
49
- return ms;
50
- }, [] as RouteMatcher[]);
51
-
52
- this.matchers = matchers;
53
- }
54
-
55
- // get best match from all matcher in manager
56
- public match(pathname: string) {
57
- const matches = this.filter(pathname);
58
- const best = this.best(pathname, matches);
59
- return best;
60
- }
61
-
62
- public matchEntry(entryname: string) {
63
- return this.matchers.find(matcher => matcher.matchEntry(entryname));
64
- }
65
-
66
- public getBundles() {
67
- const bundles = this.specs
68
- .filter(route => route.isSSR)
69
- .map(route => route.bundle);
70
-
71
- return bundles;
72
- }
73
- }
74
-
75
- export type { ModernRouteInterface, ModernRoute };
76
- export { RouteMatcher };
@@ -1,108 +0,0 @@
1
- import { removeTailSlash } from '@modern-js/utils';
2
- import {
3
- MatchFunction,
4
- MatchResult,
5
- match,
6
- pathToRegexp,
7
- } from 'path-to-regexp';
8
- import { toPath } from '../../utils';
9
- import { ModernRoute, ModernRouteInterface } from './route';
10
-
11
- // eslint-disable-next-line no-useless-escape
12
- const regCharsDetector = /[^a-zA-Z\-_0-9\/\.]/;
13
- export class RouteMatcher {
14
- public spec: ModernRouteInterface;
15
-
16
- public urlPath: string = '';
17
-
18
- public urlMatcher?: MatchFunction;
19
-
20
- public urlReg?: RegExp;
21
-
22
- constructor(spec: ModernRouteInterface) {
23
- this.spec = spec;
24
- this.setupUrlPath();
25
- }
26
-
27
- // generate modern route object
28
- public generate(url: string) {
29
- const route = new ModernRoute(this.spec);
30
-
31
- if (this.urlPath) {
32
- const params = this.parseURLParams(url);
33
- route.urlPath = toPath(route.urlPath, params);
34
- route.params = params;
35
- }
36
-
37
- return route;
38
- }
39
-
40
- public parseURLParams(pathname: string) {
41
- if (!this.urlMatcher) {
42
- return {};
43
- } else {
44
- const matchResult = this.urlMatcher(pathname);
45
-
46
- return (matchResult as MatchResult<Record<string, string>>).params;
47
- }
48
- }
49
-
50
- // get match url length
51
- public matchLength(pathname: string): number | null {
52
- if (!this.urlReg) {
53
- return this.urlPath.length;
54
- } else {
55
- const result = this.urlReg.exec(pathname);
56
- return result?.[0]?.length || null;
57
- }
58
- }
59
-
60
- // if match url path
61
- public matchUrlPath(requestUrl: string): boolean {
62
- const urlWithoutSlash =
63
- requestUrl.endsWith('/') && requestUrl !== '/'
64
- ? requestUrl.slice(0, -1)
65
- : requestUrl;
66
-
67
- if (this.urlMatcher) {
68
- return Boolean(this.urlMatcher(urlWithoutSlash));
69
- } else {
70
- if (urlWithoutSlash.startsWith(this.urlPath)) {
71
- // avoid /abcd match /a
72
- if (
73
- this.urlPath !== '/' &&
74
- urlWithoutSlash.length > this.urlPath.length &&
75
- !urlWithoutSlash.startsWith(`${this.urlPath}/`)
76
- ) {
77
- return false;
78
- }
79
-
80
- return true;
81
- }
82
-
83
- return false;
84
- }
85
- }
86
-
87
- public matchEntry(entryName: string): boolean {
88
- return this.spec.entryName === entryName;
89
- }
90
-
91
- // compiler urlPath to regexp if necessary
92
- private setupUrlPath() {
93
- const { urlPath } = this.spec;
94
- this.urlPath = urlPath === '/' ? urlPath : removeTailSlash(urlPath);
95
-
96
- const useReg = regCharsDetector.test(urlPath);
97
- if (useReg) {
98
- this.urlMatcher = match(urlPath, {
99
- end: false,
100
- decode: decodeURIComponent,
101
- });
102
-
103
- this.urlReg = pathToRegexp(urlPath, [], {
104
- end: false,
105
- });
106
- }
107
- }
108
- }
@@ -1,34 +0,0 @@
1
- import { ServerRoute as ModernRouteInterface } from '@modern-js/types';
2
-
3
- export type { ModernRouteInterface };
4
-
5
- export class ModernRoute implements ModernRouteInterface {
6
- public entryName: string;
7
-
8
- public urlPath: string;
9
-
10
- public entryPath: string;
11
-
12
- public bundle: string;
13
-
14
- public isApi: boolean;
15
-
16
- public isSSR: boolean;
17
-
18
- public isSPA: boolean;
19
-
20
- public enableModernMode?: boolean;
21
-
22
- public params: Record<string, any> = {};
23
-
24
- constructor(routeSpec: ModernRouteInterface) {
25
- this.entryName = routeSpec.entryName || '';
26
- this.urlPath = routeSpec.urlPath;
27
- this.entryPath = routeSpec.entryPath || '';
28
- this.isSSR = routeSpec.isSSR || false;
29
- this.isSPA = routeSpec.isSPA || false;
30
- this.isApi = routeSpec.isApi || false;
31
- this.bundle = routeSpec.bundle || '';
32
- this.enableModernMode = routeSpec.enableModernMode ?? false;
33
- }
34
- }
@@ -1,34 +0,0 @@
1
- // Todo 看看是不是能 fork 一份,即使命中也返回
2
- import serve from 'serve-static';
3
- import { isString, isRegExp } from '@modern-js/utils';
4
- import { NextFunction } from '../type';
5
- import { ModernServerContext } from './context';
6
-
7
- type Rule = {
8
- path: string | RegExp;
9
- target: string;
10
- };
11
-
12
- export const createStaticFileHandler =
13
- (rules: Rule[]) =>
14
- // eslint-disable-next-line consistent-return
15
- async (context: ModernServerContext, next: NextFunction) => {
16
- const { url: requestUrl, req, res } = context;
17
-
18
- const hitRule = rules.find(item => {
19
- if (isString(item.path) && requestUrl.startsWith(item.path)) {
20
- return true;
21
- } else if (isRegExp(item.path) && item.path.test(requestUrl)) {
22
- return true;
23
- }
24
- return false;
25
- });
26
-
27
- if (hitRule) {
28
- serve(hitRule.target)(req, res, () => {
29
- next();
30
- });
31
- } else {
32
- return next();
33
- }
34
- };