@nerest/nerest 0.1.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE.md +178 -0
  2. package/README.md +130 -39
  3. package/bin/index.ts +3 -0
  4. package/bin/typegen.ts +35 -0
  5. package/bin/watch.ts +3 -2
  6. package/build/configs/development.ts +63 -0
  7. package/build/configs/production.ts +59 -0
  8. package/build/configs/shared.ts +51 -0
  9. package/build/configs/vite-logger.development.ts +30 -0
  10. package/build/index.ts +53 -76
  11. package/client/index.ts +14 -2
  12. package/dist/bin/index.js +4 -0
  13. package/dist/bin/typegen.d.ts +1 -0
  14. package/dist/bin/typegen.js +31 -0
  15. package/dist/bin/watch.js +1 -2
  16. package/dist/build/configs/development.d.ts +4 -0
  17. package/dist/build/configs/development.js +53 -0
  18. package/dist/build/configs/production.d.ts +4 -0
  19. package/dist/build/configs/production.js +50 -0
  20. package/dist/build/configs/shared.d.ts +10 -0
  21. package/dist/build/configs/shared.js +24 -0
  22. package/dist/build/configs/vite-logger.development.d.ts +2 -0
  23. package/dist/build/configs/vite-logger.development.js +25 -0
  24. package/dist/build/index.js +39 -69
  25. package/dist/client/index.js +9 -2
  26. package/dist/server/development.d.ts +1 -1
  27. package/dist/server/development.js +51 -134
  28. package/dist/server/hooks/logger.d.ts +1 -2
  29. package/dist/server/hooks/logger.js +3 -0
  30. package/dist/server/hooks/props.d.ts +2 -2
  31. package/dist/server/hooks/props.js +2 -2
  32. package/dist/server/hooks/runtime.js +3 -3
  33. package/dist/server/{parts → loaders}/apps.d.ts +2 -1
  34. package/dist/server/loaders/apps.js +36 -0
  35. package/dist/server/loaders/assets.js +25 -2
  36. package/dist/server/loaders/build.d.ts +2 -0
  37. package/dist/server/loaders/build.js +11 -0
  38. package/dist/server/loaders/examples.js +7 -13
  39. package/dist/server/loaders/manifest.d.ts +8 -1
  40. package/dist/server/loaders/manifest.js +12 -4
  41. package/dist/server/loaders/preview.d.ts +4 -0
  42. package/dist/server/loaders/preview.js +11 -0
  43. package/dist/server/loaders/project.d.ts +16 -0
  44. package/dist/server/loaders/project.js +11 -0
  45. package/dist/server/loaders/schema.d.ts +2 -1
  46. package/dist/server/loaders/schema.js +12 -8
  47. package/dist/server/parts/k8s-probes.js +10 -6
  48. package/dist/server/parts/preview.d.ts +2 -1
  49. package/dist/server/parts/preview.js +5 -4
  50. package/dist/server/parts/render.d.ts +5 -3
  51. package/dist/server/parts/render.js +8 -8
  52. package/dist/server/parts/swagger.d.ts +2 -1
  53. package/dist/server/parts/swagger.js +8 -19
  54. package/dist/server/parts/validator.d.ts +3 -1
  55. package/dist/server/parts/validator.js +13 -0
  56. package/dist/server/production.js +17 -83
  57. package/dist/server/shared.d.ts +14 -0
  58. package/dist/server/shared.js +94 -0
  59. package/dist/server/utils.d.ts +1 -0
  60. package/dist/server/utils.js +5 -0
  61. package/package.json +45 -43
  62. package/schemas/nerest-build.schema.d.ts +19 -1
  63. package/schemas/nerest-build.schema.json +21 -1
  64. package/server/development.ts +67 -172
  65. package/server/hooks/logger.ts +3 -0
  66. package/server/hooks/props.ts +5 -5
  67. package/server/hooks/runtime.ts +3 -3
  68. package/server/loaders/apps.ts +58 -0
  69. package/server/loaders/assets.ts +30 -2
  70. package/server/loaders/build.ts +14 -0
  71. package/server/loaders/examples.ts +7 -15
  72. package/server/loaders/manifest.ts +23 -4
  73. package/server/loaders/preview.ts +17 -0
  74. package/server/loaders/project.ts +33 -0
  75. package/server/loaders/schema.ts +12 -10
  76. package/server/parts/k8s-probes.ts +26 -13
  77. package/server/parts/preview.ts +11 -4
  78. package/server/parts/render.ts +13 -9
  79. package/server/parts/swagger.ts +10 -29
  80. package/server/parts/validator.ts +14 -0
  81. package/server/production.ts +22 -110
  82. package/server/shared.ts +150 -0
  83. package/server/utils.ts +6 -0
  84. package/dist/server/parts/apps.js +0 -37
  85. package/dist/server/parts/props-hook.d.ts +0 -1
  86. package/dist/server/parts/props-hook.js +0 -8
  87. package/dist/server/parts/runtime-hook.d.ts +0 -2
  88. package/dist/server/parts/runtime-hook.js +0 -28
  89. package/server/parts/apps.ts +0 -59
package/LICENSE.md ADDED
@@ -0,0 +1,178 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Nerest team
package/README.md CHANGED
@@ -1,43 +1,30 @@
1
- # @nerest/nerest
1
+ # Nerest
2
2
 
3
- React micro frontend framework
3
+ Nerest is an opinionated micro frontend framework/stack for building SSR applications with TypeScript, Fastify, JSON Schema and React. It is available as a single `@nerest/nerest` npm package.
4
4
 
5
- > TODO: purpose, outline, documentation
5
+ [View current documentation](https://nerestjs.github.io/docs/)
6
6
 
7
- ## Installation
7
+ ## Quick Start
8
8
 
9
- TODO: update package
10
-
11
- ```
12
- npm i --save @nerest/nerest react react-dom
13
- ```
14
-
15
- ## Points of Interest
16
-
17
- - SSR server entry:
18
- - Development: [server/development.ts](server/development.ts)
19
- - Production: [server/production.ts](server/production.ts)
20
- - Hydrating client entry: [client/index.ts](client/index.ts)
21
- - CLI entry: [bin/index.ts](bin/index.ts)
22
- - Production build script: [build/index.ts](build/index.ts)
9
+ [Follow the tutorial](https://nerestjs.github.io/docs/tutorial/) to build your first Nerest micro frontend step-by-step, or clone and run [the complete version](https://github.com/nerestjs/tutorial) of that micro frontend locally.
23
10
 
24
11
  ## Conventions
25
12
 
26
- The `apps` directory must contain all of the apps provided by the micro frontend. E.g. `/apps/foo/index.tsx` is the entrypoint component of the `foo` app. It becomes available as the `/api/foo` route of the micro frontend server.
13
+ ### `/apps`
27
14
 
28
- See [nerest-harness](https://gitlab.tcsbank.ru/tj/nerest-harness) for the minimal example of a nerest micro frontend.
15
+ The `/apps` directory must contain all of the apps provided by the micro frontend. E.g. `/apps/foo/index.tsx` is the entrypoint component of the `foo` app. It becomes available as the `/api/foo` route of the micro frontend server.
29
16
 
30
- ### Examples (`/examples/*.json`)
17
+ #### Examples (`/examples/*.json`)
31
18
 
32
19
  The app directory may contain an `examples` subdirectory with example JSON files which can be used as props for the app entrypoint component. E.g. `/apps/foo/examples/example-1.json` becomes available as the `/api/foo/examples/example-1` route of the micro frontend server.
33
20
 
34
- ### Schema (`/schema.json`)
21
+ #### Schema (`/schema.json`)
35
22
 
36
23
  The app directory should contain a `schema.json` file that describes the schema of a request body for this specific app in the [JSON Schema language](https://json-schema.org/). All requests sent to this app, and app examples from the `examples` subdirectory will be validated against this schema. `ajv` and `ajv-formats` are used for validation, so all JSON Schema features implemented by them are supported.
37
24
 
38
25
  OpenAPI specification is compiled automatically based on the provided schemas and becomes available at `/api/json`. It can also be explored through Swagger UI that becomes available at `/api`.
39
26
 
40
- ### Props Hook (`/props.ts`)
27
+ #### Props Hook (`/props.ts`)
41
28
 
42
29
  The app directory may contain a `props.ts` module that exports a default function. If it exists, this function will be executed on the server for every incoming request, receiving the body of the request and a logger as parameters. You can use this hook to modify and return a new object, which will be passed down to the `index.tsx` entrypoint component instead. For example:
43
30
 
@@ -54,17 +41,27 @@ export default function (props: Props, logger: FastifyBaseLogger) {
54
41
  }
55
42
  ```
56
43
 
57
- The exported function may be async, in which case nerest will wait for the Promise to resolve, then pass the result object to the entrypoint component.
44
+ The exported function may be async, in which case Nerest will wait for the Promise to resolve, then pass the result object to the entrypoint component.
45
+
46
+ ### `/package.json`
47
+
48
+ `name`, `description`, `version`, `homepage` and `repository` fields of the root `package.json` file are used to display project info in the header of the generated Swagger page.
49
+
50
+ `name` is also used to disambiguate multiple apps with the same name from different micro frontends. If you have multiple apps with the same name embeded in a single page, make sure that the `name` field of their micro frontends' `package.json` files is unique.
58
51
 
59
52
  ## Configuration
60
53
 
61
- Different aspects of Nerest apps can be configured via environment variables, JSON configuration and runtime hooks written in TypeScript. Examples of all kinds of configuration can be viewed in the [nerest-harness](https://gitlab.tcsbank.ru/tj/nerest-harness) repository.
54
+ Different aspects of Nerest apps can be configured via environment variables, JSON configuration and runtime hooks written in TypeScript.
62
55
 
63
56
  ### Environment Variables
64
57
 
65
58
  #### Buildtime
66
59
 
67
- - `NEREST_STATIC_PATH` is required for production build and must contain the URL of where the client static assets will be deployed. It lets the server-side renderer return their paths in the assets field of the response.
60
+ ##### STATIC_PATH
61
+
62
+ `STATIC_PATH` is required for production build and should contain the URL where the client static assets will be deployed. It enables the server-side renderer to return their paths in the assets field of the response.
63
+
64
+ In development, it is optional and can be used to load example previews' assets from a different address than the default `127.0.0.1:$PORT`. This allows debugging of the micro frontend from another device on the same local network. For example, run `STATIC_PATH=<local_ip>:<port> npm run watch` and access previews from another device on the same network by going to `http://<local_ip>:<port>/api/`
68
65
 
69
66
  #### Runtime
70
67
 
@@ -74,17 +71,19 @@ All environment variables prefixed with `NEREST_` will be bundled with your app
74
71
 
75
72
  ##### Server
76
73
 
77
- Additional environment variables which can be setup for a runtime:
74
+ Environment variables for runtime configuration:
78
75
 
79
- - `ENABLE_K8S_PROBES`: activates additional routes `/livenessProbe` and `/readinessProbe` to check application status
76
+ - `PORT`: Sets the port number for the application. The default port is 3000.
77
+ - `ENABLE_K8S_PROBES`: Enables additional routes `/livenessProbe` and `/readinessProbe` to check the application status, useful for Kubernetes healthchecks.
78
+ - `DISABLE_SCHEMA_VALIDATION`: Disables validation of request body against app schema. Can be used in production to speed up request time.
80
79
 
81
- ### JSON Configuration
80
+ ### Build
82
81
 
83
- You can configure the output of `nerest build` by placing an optional `nerest-build.json` configuration file in the root of the micro frontend. The full schema of this file is located in [schemas/nerest-build.schema.json](schemas/nerest-build.schema.json).
82
+ Customize the build output by placing an optional `nerest/build.json` configuration file in the micro frontend's root directory. Refer to the [schemas/nerest-build.schema.json](schemas/nerest-build.schema.json) for the full schema of this file.
84
83
 
85
84
  #### excludes: `string[]`
86
85
 
87
- Excludes modules from the client build and replaces their imports with imports of an empty module instead. You can use this to exclude either JS or CSS modules from the final build.
86
+ Excludes modules from the production client build and replaces their imports with imports of an empty module instead. You can use this to exclude either JS or CSS modules from the final build.
88
87
 
89
88
  ```
90
89
  "excludes": ["@scope/name"]
@@ -92,7 +91,7 @@ Excludes modules from the client build and replaces their imports with imports o
92
91
 
93
92
  #### externals: `Record<string, string>`
94
93
 
95
- Excludes modules from the client build and maps them to globally available constants instead. You can use this to share common dependencies between different micro frontends by exposing them on the `window` object. For example:
94
+ Excludes modules from the production client build and maps them to globally available constants instead. You can use this to share common dependencies between different micro frontends by exposing them on the `window` object. For example:
96
95
 
97
96
  ```
98
97
  "externals": {
@@ -103,23 +102,50 @@ Excludes modules from the client build and maps them to globally available const
103
102
 
104
103
  Here `react` and `react-dom` imports will be replaced with accessing the respective `window` constants.
105
104
 
106
- ### Runtime Hook
105
+ #### postcss.plugins: `Record<string, PluginOptions>`
106
+
107
+ Include specified PostCSS plugins in the build by providing their full package names as keys and their options as values. Make sure to install these plugins using `npm install` beforehand. Use an empty object for default options. Example:
108
+
109
+ ```json
110
+ "postcss": {
111
+ "plugins": {
112
+ "postcss-extend": {},
113
+ "postcss-short": {
114
+ "features": {
115
+ "position": false
116
+ }
117
+ }
118
+ }
119
+ }
120
+ ```
121
+
122
+ In the above example, `postcss-extend` is added to vite's PostCSS configuration with default options, enabling the use of `@extend` rules in CSS code. `postcss-short` is added with specific options provided.
107
123
 
108
- If the module `nerest-runtime.ts` exists in the root of the micro frontend and exports a default function, this function will be executed when the server starts, and the fastify app instance will be passed to it as its only argument. Example of `nerest-runtime.ts`:
124
+ #### clientSideEffects: `string[]`
125
+
126
+ List of names of apps that have client side-effects, for example have their own self-initialization code that runs on import. Their entries will be loaded when hydration starts to run side-effect code.
127
+
128
+ ```
129
+ "clientSideEffects": ["foo", "bar"]
130
+ ```
131
+
132
+ ### Runtime
133
+
134
+ If the module `nerest/runtime.ts` exists in the micro frontend's root directory and exports a default function, it will be executed when the server starts. The Fastify app instance will be passed as the function's only argument. Example of `nerest/runtime.ts`:
109
135
 
110
136
  ```typescript
111
137
  import type { FastifyInstance } from 'fastify';
112
138
 
113
139
  export default function (app: FastifyInstance) {
114
- console.log('Hello from nerest-runtime.ts');
140
+ console.log('Hello from nerest/runtime.ts');
115
141
  }
116
142
  ```
117
143
 
118
144
  This runtime hook can be used to adjust fastify settings, register additional plugins or add custom routes.
119
145
 
120
- #### Logger Configuration
146
+ #### Logger
121
147
 
122
- Nerest uses the default server-side [fastify logger](https://fastify.dev/docs/latest/Reference/Logging/#logging), enabled by default. To configure or disable it, export a `logger` function from the `nerest-runtime.ts` module. It will be called on server start, and the return value will be passed to fastify as logger configuration.
148
+ Nerest uses the [default server-side fastify logger](https://fastify.dev/docs/latest/Reference/Logging/#logging), enabled by default. To configure or disable it, export a `logger` function from the `nerest/runtime.ts` module. This function will be called on server start, and its return value will be used as the logger configuration for Fastify.
123
149
 
124
150
  ```typescript
125
151
  import type { FastifyServerOptions } from 'fastify';
@@ -131,7 +157,43 @@ export function logger(): FastifyServerOptions['logger'] {
131
157
 
132
158
  To disable the logger, return `false` from the function.
133
159
 
134
- You can also supply your own logger instance. Instead of passing configuration options, pass the instance. The logger you supply must conform to the [Pino](https://github.com/pinojs/pino) interface; that is, it must have the following methods: `info`, `error`, `debug`, `fatal`, `warn`, `trace`, `silent`, `child` and a string property `level`.
160
+ ### Preview
161
+
162
+ For customizing micro frontend previews, create a `nerest/preview-head.html` file in the project's root directory. This file allows you to modify the preview rendering by appending your own HTML markup, such as metadata, external stylesheets, or scripts to the end of the `<head>`. Use it to to enhance the appearance and behavior of previews according to your specific needs.
163
+
164
+ ```html
165
+ <!-- Pull in static files served from the internet -->
166
+ <link rel="preload" href="https://example.com/cdn/fonts/my-font.woff2" />
167
+
168
+ <!-- Or load custom head-tag JavaScript -->
169
+ <script src="https://example.com/sample.js"></script>
170
+ <script>
171
+ Sample.load();
172
+ </script>
173
+ ```
174
+
175
+ ## CLI
176
+
177
+ ### `nerest build`
178
+
179
+ Creates the production build of the micro frontend, generating the necessary files in the build directory.
180
+
181
+ - Serverside entry is outputted to the `build/server.mjs` file.
182
+ - Clientside static files are outputted to the `build/client/assets` directory. These files should be made available [at the `STATIC_PATH` URL](#static_path).
183
+
184
+ ### `nerest typegen`
185
+
186
+ Generates TypeScript type definitions for the micro frontend's app schemas and outputs them to the schema.d.ts file, located next to the corresponding schema file. By default, it searches for schema files in the root directories of app directories.
187
+
188
+ To override this behavior, provide a list of globs to the nerest typegen command. Remember to quote the globs to ensure they are executed by nerest and not your shell. For example:
189
+
190
+ ```
191
+ nerest typegen 'apps/*/schema.json' 'schemas/*.json'
192
+ ```
193
+
194
+ ### `nerest watch`
195
+
196
+ Starts the development server on the default port 3000. The server will automatically reload when changes are made to the app's source code.
135
197
 
136
198
  ## Development
137
199
 
@@ -142,4 +204,33 @@ npm install
142
204
  npm run build
143
205
  ```
144
206
 
145
- Use [nerest-harness](https://gitlab.tcsbank.ru/tj/nerest-harness) to test changes locally.
207
+ - SSR server entry:
208
+ - Development: [server/development.ts](server/development.ts)
209
+ - Production: [server/production.ts](server/production.ts)
210
+ - Hydrating client entry: [client/index.ts](client/index.ts)
211
+ - CLI entry: [bin/index.ts](bin/index.ts)
212
+ - Production build script: [build/index.ts](build/index.ts)
213
+
214
+ ## Testing
215
+
216
+ Nerest uses Vitest for both module and integration tests. Run module tests with:
217
+
218
+ ```bash
219
+ npm run test:module
220
+ ```
221
+
222
+ Integration tests verify the framework as a whole using a test harness micro frontend located in [`tests/integration/harness`](tests/integration/harness). There are two modes:
223
+
224
+ ```bash
225
+ # Development mode - includes browser tests
226
+ npm run test:integration:dev
227
+
228
+ # Production mode - tests production build
229
+ npm run test:integration:prod
230
+ ```
231
+
232
+ Development mode tests include browser-based tests using Playwright to verify client-side hydration and interactivity. Production mode tests verify the production build and server functionality.
233
+
234
+ ## Contributing
235
+
236
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for more information.
package/bin/index.ts CHANGED
@@ -3,12 +3,15 @@
3
3
  import 'dotenv/config';
4
4
 
5
5
  import { build } from './build.js';
6
+ import { typegen } from './typegen.js';
6
7
  import { watch } from './watch.js';
7
8
 
8
9
  // TODO: add CLI help and manual, maybe use a CLI framework like oclif
9
10
  async function cliEntry(args: string[]) {
10
11
  if (args[0] === 'build') {
11
12
  await build();
13
+ } else if (args[0] === 'typegen') {
14
+ await typegen(args.slice(1));
12
15
  } else if (args[0] === 'watch') {
13
16
  await watch();
14
17
  }
package/bin/typegen.ts ADDED
@@ -0,0 +1,35 @@
1
+ import path from 'path';
2
+ import fs from 'fs/promises';
3
+ import fg from 'fast-glob';
4
+ import { compileFromFile } from 'json-schema-to-typescript';
5
+
6
+ // Comment at the start of every type definition file, alerting
7
+ // developers to not modify the file by hand
8
+ const bannerComment = `
9
+ /**
10
+ * This file was automatically generated by Nerest.
11
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source schema.json file,
12
+ * and run "nerest typegen" to regenerate this file.
13
+ */`.trim();
14
+
15
+ // Generates a TypeScript type definition for each JSON Schema in the given globs
16
+ export async function typegen(globs: string[]) {
17
+ // If no globs are provided, default to the schema.json file in each app directory
18
+ if (globs.length === 0) {
19
+ globs = ['apps/*/schema.json'];
20
+ }
21
+
22
+ const paths = await fg.glob(globs, { onlyFiles: true });
23
+ console.log(`Found ${paths.length} schemas, generating types...`);
24
+
25
+ for (const schemaPath of paths) {
26
+ // Turn each schema.json file into schema.d.ts
27
+ const typePath = schemaPath.replace('.json', '.d.ts');
28
+ const type = await compileFromFile(schemaPath, {
29
+ cwd: path.resolve(path.dirname(schemaPath)),
30
+ bannerComment,
31
+ });
32
+ await fs.writeFile(typePath, type, 'utf-8');
33
+ console.log(`${schemaPath} -> ${typePath}`);
34
+ }
35
+ }
package/bin/watch.ts CHANGED
@@ -3,7 +3,8 @@ import { runDevelopmentServer } from '../server/development.js';
3
3
  // Start dev server in watch mode, that restarts on file change
4
4
  // and rebuilds the client static files
5
5
  export async function watch() {
6
- // TODO: will be replaced with nerest logger
7
6
  console.log('Starting Nerest watch...');
8
- await runDevelopmentServer();
7
+ await runDevelopmentServer(
8
+ process.env.PORT ? Number(process.env.PORT) : 3000
9
+ );
9
10
  }
@@ -0,0 +1,63 @@
1
+ import type { InlineConfig } from 'vite';
2
+
3
+ import type { BuildArgs } from './shared.js';
4
+ import { viteConfigShared } from './shared.js';
5
+ import logger from './vite-logger.development.js';
6
+
7
+ export async function viteConfigDevelopmentClient(
8
+ args: BuildArgs
9
+ ): Promise<InlineConfig> {
10
+ return {
11
+ ...(await viteConfigShared(args)),
12
+ build: {
13
+ // Manifest is needed to report used assets in SSR handles
14
+ manifest: true,
15
+ modulePreload: false,
16
+ watch: {},
17
+ rollupOptions: {
18
+ input: '/node_modules/@nerest/nerest/client/index.ts',
19
+ output: {
20
+ dir: 'build/client/assets',
21
+ entryFileNames: `[name].js`,
22
+ chunkFileNames: `[name].js`,
23
+ assetFileNames: `[name].[ext]`,
24
+ },
25
+ },
26
+ },
27
+ customLogger: logger,
28
+ };
29
+ }
30
+
31
+ export async function viteConfigDevelopmentServer(
32
+ args: BuildArgs
33
+ ): Promise<InlineConfig> {
34
+ return {
35
+ ...(await viteConfigShared(args)),
36
+ server: {
37
+ // Middleware lets vite compile on the fly, providing
38
+ // hot reload of certain modules
39
+ middlewareMode: true,
40
+ // Origin to serve imported assets from (like images)
41
+ origin: new URL(args.base).origin,
42
+ // Run HMR WebSocket server on random port to prevent conflicts
43
+ // between multiple projects running simultaneously
44
+ hmr: { port: randomPort() },
45
+ // Allow requests from all hosts in development
46
+ allowedHosts: true,
47
+ },
48
+ // optimizeDeps is only necessary with index.html entrypoint,
49
+ // which we don't have
50
+ optimizeDeps: {
51
+ noDiscovery: true,
52
+ include: [],
53
+ },
54
+ customLogger: logger,
55
+ };
56
+ }
57
+
58
+ // Returns a random high-number port to prevent conflicts
59
+ function randomPort() {
60
+ // 49152-65535 is the ephemeral port range
61
+ // https://datatracker.ietf.org/doc/html/rfc6335#section-6
62
+ return 49152 + Math.floor(Math.random() * (65535 - 49152));
63
+ }
@@ -0,0 +1,59 @@
1
+ import type { InlineConfig } from 'vite';
2
+ import { viteExternalsPlugin } from 'vite-plugin-externals';
3
+
4
+ import type { BuildArgs } from './shared.js';
5
+ import { viteConfigShared } from './shared.js';
6
+ import { excludes } from '../excludes/index.js';
7
+
8
+ export async function viteConfigProductionClient(
9
+ args: BuildArgs
10
+ ): Promise<InlineConfig> {
11
+ return {
12
+ ...(await viteConfigShared(args)),
13
+ build: {
14
+ // Manifest is needed to report used assets in SSR handles
15
+ manifest: true,
16
+ modulePreload: false,
17
+ rollupOptions: {
18
+ input: '/node_modules/@nerest/nerest/client/index.ts',
19
+ output: {
20
+ dir: 'build/client/assets',
21
+ entryFileNames: `[name].js`,
22
+ chunkFileNames: `[name].js`,
23
+ assetFileNames: `[name].[ext]`,
24
+ },
25
+ },
26
+ },
27
+ resolve: {
28
+ // excludes - map buildConfig.excludes packages to an empty module
29
+ alias: excludes(args.buildConfig?.excludes),
30
+ },
31
+ plugins: [
32
+ // externals - map buildConfig.externals packages to a global variable on window
33
+ viteExternalsPlugin(args.buildConfig?.externals, { useWindow: false }),
34
+ ],
35
+ };
36
+ }
37
+
38
+ export async function viteConfigProductionServer(
39
+ args: BuildArgs
40
+ ): Promise<InlineConfig> {
41
+ return {
42
+ ...(await viteConfigShared(args)),
43
+ build: {
44
+ emptyOutDir: false,
45
+ modulePreload: false,
46
+ // This is an important setting for producing a server build
47
+ ssr: true,
48
+ rollupOptions: {
49
+ input: '/node_modules/@nerest/nerest/server/production.ts',
50
+ output: {
51
+ dir: 'build',
52
+ entryFileNames: `server.mjs`,
53
+ chunkFileNames: `[name].mjs`,
54
+ assetFileNames: `[name].[ext]`,
55
+ },
56
+ },
57
+ },
58
+ };
59
+ }