@shuvi/platform-web 1.0.0-rc.2 → 1.0.0-rc.20

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 (152) hide show
  1. package/esm/shared/appTypes.d.ts +12 -6
  2. package/esm/shared/configTypes.d.ts +1 -3
  3. package/esm/shared/constants.d.ts +8 -0
  4. package/esm/shared/constants.js +8 -0
  5. package/esm/shared/htmlRenderer.d.ts +33 -0
  6. package/esm/shared/{serverTypes.js → htmlRenderer.js} +0 -0
  7. package/esm/shared/index.d.ts +2 -1
  8. package/esm/shared/index.js +2 -1
  9. package/esm/shared/renderTypes.d.ts +8 -7
  10. package/esm/shared/routeTypes.d.ts +4 -9
  11. package/esm/shuvi-app/app/client.d.ts +2 -1
  12. package/esm/shuvi-app/app/client.js +13 -17
  13. package/esm/shuvi-app/app/server.js +13 -9
  14. package/esm/shuvi-app/dev/eventsource.d.ts +1 -0
  15. package/esm/shuvi-app/dev/eventsource.js +60 -0
  16. package/esm/shuvi-app/dev/hotDevClient.d.ts +32 -0
  17. package/esm/shuvi-app/dev/hotDevClient.js +327 -0
  18. package/esm/shuvi-app/dev/index.d.ts +3 -0
  19. package/esm/shuvi-app/dev/index.js +27 -0
  20. package/esm/shuvi-app/dev/websocket.d.ts +16 -0
  21. package/esm/shuvi-app/dev/websocket.js +61 -0
  22. package/esm/shuvi-app/entry/client/app.d.ts +2 -1
  23. package/esm/shuvi-app/entry/client/app.js +13 -6
  24. package/esm/shuvi-app/entry/client/index.js +1 -1
  25. package/esm/shuvi-app/entry/client/run.dev.js +15 -16
  26. package/esm/shuvi-app/entry/server/index.d.ts +5 -4
  27. package/esm/shuvi-app/entry/server/index.js +5 -4
  28. package/esm/shuvi-app/helper/serializeServerError.d.ts +2 -0
  29. package/esm/shuvi-app/helper/serializeServerError.js +21 -0
  30. package/esm/shuvi-app/react/AppContainer.d.ts +4 -5
  31. package/esm/shuvi-app/react/AppContainer.jsx +4 -5
  32. package/esm/shuvi-app/react/ApplicationContext.d.ts +7 -0
  33. package/esm/shuvi-app/react/{applicationContext.jsx → ApplicationContext.jsx} +0 -0
  34. package/esm/shuvi-app/react/Error.jsx +4 -1
  35. package/esm/shuvi-app/react/Link.d.ts +2 -1
  36. package/esm/shuvi-app/react/Link.jsx +1 -1
  37. package/esm/shuvi-app/react/getRoutes.d.ts +2 -2
  38. package/esm/shuvi-app/react/getRoutes.js +9 -8
  39. package/esm/shuvi-app/react/{redox-react → model}/RedoxWrapper.d.ts +3 -3
  40. package/esm/shuvi-app/react/{redox-react → model}/RedoxWrapper.jsx +3 -3
  41. package/esm/shuvi-app/react/model/runtime.d.ts +8 -0
  42. package/esm/shuvi-app/react/{redox-react → model}/runtime.js +8 -3
  43. package/esm/shuvi-app/react/store.d.ts +5 -0
  44. package/esm/shuvi-app/react/store.js +3 -0
  45. package/esm/shuvi-app/react/types.d.ts +0 -7
  46. package/esm/shuvi-app/react/useLoaderData.js +9 -20
  47. package/esm/shuvi-app/react/view/ReactView.client.jsx +34 -23
  48. package/esm/shuvi-app/react/view/ReactView.server.jsx +29 -14
  49. package/esm/shuvi-app/react/view/render.d.ts +8 -0
  50. package/esm/shuvi-app/react/view/{render-action.js → render.js} +6 -6
  51. package/lib/node/features/custom-server/index.d.ts +1 -1
  52. package/lib/node/features/custom-server/server.d.ts +1 -1
  53. package/lib/node/features/custom-server/server.js +20 -11
  54. package/lib/node/features/filesystem-routes/api/apiRouteHandler.d.ts +7 -7
  55. package/lib/node/features/filesystem-routes/api/apiRouteHandler.js +5 -5
  56. package/lib/node/features/filesystem-routes/api/middleware.d.ts +2 -2
  57. package/lib/node/features/filesystem-routes/api/middleware.js +5 -2
  58. package/lib/node/features/filesystem-routes/hooks.d.ts +2 -1
  59. package/lib/node/features/filesystem-routes/hooks.js +2 -1
  60. package/lib/node/features/filesystem-routes/index.d.ts +1 -13
  61. package/lib/node/features/filesystem-routes/index.js +55 -84
  62. package/lib/node/features/filesystem-routes/middleware/middleware.d.ts +2 -2
  63. package/lib/node/features/filesystem-routes/middleware/middleware.js +5 -2
  64. package/lib/node/features/filesystem-routes/page/routes.d.ts +3 -3
  65. package/lib/node/features/filesystem-routes/page/routes.js +25 -12
  66. package/lib/node/features/html-render/index.d.ts +4 -18
  67. package/lib/node/features/html-render/index.js +129 -16
  68. package/lib/node/features/{main → html-render/lib}/buildHtml.d.ts +0 -0
  69. package/lib/node/features/{main → html-render/lib}/buildHtml.js +2 -1
  70. package/lib/node/features/html-render/lib/generateFilesByRoutId.d.ts +3 -3
  71. package/lib/node/features/html-render/lib/generateFilesByRoutId.js +3 -3
  72. package/lib/node/features/{main → html-render/lib}/generateResource.d.ts +0 -0
  73. package/lib/node/features/{main → html-render/lib}/generateResource.js +12 -8
  74. package/lib/node/features/html-render/lib/getPageMiddleware.d.ts +2 -2
  75. package/lib/node/features/html-render/lib/getPageMiddleware.js +18 -13
  76. package/lib/node/features/html-render/lib/index.d.ts +0 -2
  77. package/lib/node/features/html-render/lib/index.js +1 -4
  78. package/lib/node/features/html-render/lib/renderToHTML.d.ts +2 -2
  79. package/lib/node/features/html-render/lib/renderToHTML.js +9 -49
  80. package/lib/node/features/html-render/lib/renderer/base.d.ts +7 -8
  81. package/lib/node/features/html-render/lib/renderer/base.js +19 -11
  82. package/lib/node/features/html-render/lib/renderer/index.d.ts +5 -4
  83. package/lib/node/features/html-render/lib/renderer/index.js +77 -8
  84. package/lib/node/features/html-render/lib/renderer/spa.d.ts +2 -2
  85. package/lib/node/features/html-render/lib/renderer/spa.js +4 -6
  86. package/lib/node/features/html-render/lib/renderer/ssr.d.ts +2 -2
  87. package/lib/node/features/html-render/lib/renderer/ssr.js +9 -11
  88. package/lib/node/features/html-render/lib/renderer/types.d.ts +10 -8
  89. package/lib/node/features/html-render/lib/webpack/build-manifest-plugin.d.ts +27 -0
  90. package/lib/node/features/html-render/lib/webpack/build-manifest-plugin.js +223 -0
  91. package/lib/node/features/html-render/server.d.ts +1 -1
  92. package/lib/node/features/html-render/serverHooks.d.ts +6 -1
  93. package/lib/node/features/html-render/serverHooks.js +1 -2
  94. package/lib/node/features/index.d.ts +3 -31
  95. package/lib/node/features/index.js +6 -7
  96. package/lib/node/features/middlewares.d.ts +1 -1
  97. package/lib/node/features/middlewares.js +12 -3
  98. package/lib/node/features/model/index.d.ts +1 -13
  99. package/lib/node/features/model/runtime.d.ts +3 -8
  100. package/lib/node/features/model/runtime.js +13 -18
  101. package/lib/node/features/model/server.js +2 -3
  102. package/lib/node/features/model/shuvi-app.d.ts +2 -2
  103. package/lib/node/features/on-demand-compile-page/index.d.ts +3 -13
  104. package/lib/node/features/on-demand-compile-page/index.js +4 -1
  105. package/lib/node/features/on-demand-compile-page/onDemandRouteManager.d.ts +3 -3
  106. package/lib/node/features/on-demand-compile-page/onDemandRouteManager.js +4 -6
  107. package/lib/node/index.d.ts +1 -0
  108. package/lib/node/index.js +17 -5
  109. package/lib/node/paths.js +0 -2
  110. package/lib/node/shuvi-runtime-server.d.ts +26 -0
  111. package/lib/{shared/serverTypes.js → node/shuvi-runtime-server.js} +0 -0
  112. package/lib/node/shuvi-type-extensions-node.d.ts +20 -23
  113. package/lib/node/targets/react/bundler/index.d.ts +1 -13
  114. package/lib/node/targets/react/bundler/index.js +19 -13
  115. package/lib/node/targets/react/index.d.ts +2 -27
  116. package/lib/node/targets/react/index.js +3 -7
  117. package/lib/node/targets/react/model/index.d.ts +6 -0
  118. package/lib/node/targets/react/{redox-react → model}/index.js +7 -6
  119. package/lib/node/version.d.ts +1 -0
  120. package/lib/node/version.js +13 -0
  121. package/lib/shared/appTypes.d.ts +12 -6
  122. package/lib/shared/configTypes.d.ts +1 -3
  123. package/lib/shared/constants.d.ts +8 -0
  124. package/lib/shared/constants.js +15 -0
  125. package/lib/shared/htmlRenderer.d.ts +33 -0
  126. package/lib/shared/htmlRenderer.js +2 -0
  127. package/lib/shared/index.d.ts +2 -1
  128. package/lib/shared/index.js +2 -1
  129. package/lib/shared/renderTypes.d.ts +8 -7
  130. package/lib/shared/routeTypes.d.ts +4 -9
  131. package/package.json +40 -26
  132. package/polyfills/polyfills.js +1 -0
  133. package/shuvi-env.d.ts +10 -0
  134. package/shuvi-image.d.ts +54 -0
  135. package/shuvi-type-extensions-node.js +1 -0
  136. package/shuvi-type-extensions-runtime.d.ts +2 -2
  137. package/esm/shared/serverTypes.d.ts +0 -6
  138. package/esm/shuvi-app/dev/webpackHotDevClient.d.ts +0 -5
  139. package/esm/shuvi-app/dev/webpackHotDevClient.js +0 -34
  140. package/esm/shuvi-app/react/applicationContext.d.ts +0 -7
  141. package/esm/shuvi-app/react/redox-react/runtime.d.ts +0 -2
  142. package/esm/shuvi-app/react/view/render-action.d.ts +0 -10
  143. package/esm/shuvi-app/shuvi-runtime-index.d.ts +0 -4
  144. package/esm/shuvi-app/shuvi-runtime-index.js +0 -2
  145. package/esm/shuvi-app/shuvi-runtime-server.d.ts +0 -6
  146. package/esm/shuvi-app/shuvi-runtime-server.js +0 -1
  147. package/lib/node/features/html-render/lib/pageLoader.d.ts +0 -1
  148. package/lib/node/features/html-render/lib/pageLoader.js +0 -42
  149. package/lib/node/features/main/index.d.ts +0 -3
  150. package/lib/node/features/main/index.js +0 -82
  151. package/lib/node/targets/react/redox-react/index.d.ts +0 -18
  152. package/lib/shared/serverTypes.d.ts +0 -6
@@ -0,0 +1,327 @@
1
+ /* eslint-disable camelcase */
2
+ /**
3
+ MIT License
4
+
5
+ Copyright (c) 2013-present, Facebook, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+ */
25
+ // This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/webpackHotDevClient.js
26
+ // It's been edited to rely on webpack-hot-middleware.
27
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
28
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
+ return new (P || (P = Promise))(function (resolve, reject) {
30
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
34
+ });
35
+ };
36
+ // @ts-nocheck
37
+ import stripAnsi from 'strip-ansi';
38
+ import formatWebpackMessages from '@shuvi/toolpack/lib/utils/formatWebpackMessages';
39
+ import { startReportingRuntimeErrors, stopReportingRuntimeErrors, onBuildError, onBuildOk, onRefresh } from '@shuvi/error-overlay';
40
+ import { DEV_SOCKET_TIMEOUT_MS } from '@shuvi/shared/esm/constants';
41
+ import { connectHMR, addMessageListener, sendMessage } from './websocket';
42
+ // This alternative WebpackDevServer combines the functionality of:
43
+ // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
44
+ // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
45
+ // It only supports their simplest configuration (hot updates on same server).
46
+ // It makes some opinionated choices on top, like adding a syntax error overlay
47
+ // that looks similar to our console output. The error overlay is inspired by:
48
+ // https://github.com/glenjamin/webpack-hot-middleware
49
+ // This is a modified version of create-react-app's webpackHotDevClient.js
50
+ // It implements webpack-hot-middleware's EventSource events instead of webpack-dev-server's websocket.
51
+ // https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-dev-utils/webpackHotDevClient.js
52
+ let hadRuntimeError = false;
53
+ let customHmrEventHandler;
54
+ export default function connect(options) {
55
+ startReportingRuntimeErrors({
56
+ onError: function () {
57
+ hadRuntimeError = true;
58
+ }
59
+ });
60
+ if (module.hot && typeof module.hot.dispose === 'function') {
61
+ module.hot.dispose(function () {
62
+ stopReportingRuntimeErrors();
63
+ });
64
+ }
65
+ connectHMR(Object.assign(Object.assign({}, options), { log: true }));
66
+ addMessageListener(event => {
67
+ // This is the heartbeat event
68
+ const obj = JSON.parse(event.data);
69
+ if (obj.action === 'pong') {
70
+ return;
71
+ }
72
+ try {
73
+ processMessage(event);
74
+ }
75
+ catch (ex) {
76
+ console.warn('Invalid HMR message: ' + event.data + '\n' + ex);
77
+ }
78
+ });
79
+ setInterval(() => {
80
+ sendMessage(JSON.stringify({ event: 'ping' }));
81
+ }, DEV_SOCKET_TIMEOUT_MS / 2);
82
+ return {
83
+ sendMessage(data) {
84
+ sendMessage(data);
85
+ },
86
+ subscribeToHmrEvent(handler) {
87
+ customHmrEventHandler = handler;
88
+ }
89
+ };
90
+ }
91
+ // Remember some state related to hot module replacement.
92
+ var isFirstCompilation = true;
93
+ var mostRecentCompilationHash = null;
94
+ var hasCompileErrors = false;
95
+ function clearOutdatedErrors() {
96
+ // Clean up outdated compile errors, if any.
97
+ if (typeof console !== 'undefined' && typeof console.clear === 'function') {
98
+ if (hasCompileErrors) {
99
+ console.clear();
100
+ }
101
+ }
102
+ }
103
+ let startLatency = undefined;
104
+ function onFastRefresh(hasUpdates) {
105
+ onBuildOk();
106
+ if (hasUpdates) {
107
+ onRefresh();
108
+ }
109
+ if (startLatency) {
110
+ const endLatency = Date.now();
111
+ const latency = endLatency - startLatency;
112
+ console.log(`[Fast Refresh] done in ${latency}ms`);
113
+ }
114
+ }
115
+ // Successful compilation.
116
+ function handleSuccess() {
117
+ clearOutdatedErrors();
118
+ const isHotUpdate = !isFirstCompilation;
119
+ isFirstCompilation = false;
120
+ hasCompileErrors = false;
121
+ // Attempt to apply hot updates or reload.
122
+ if (isHotUpdate) {
123
+ tryApplyUpdates(function onHotUpdateSuccess(hasUpdates) {
124
+ // Only dismiss it when we're sure it's a hot update.
125
+ // Otherwise it would flicker right before the reload.
126
+ onFastRefresh(hasUpdates);
127
+ });
128
+ }
129
+ }
130
+ // Compilation with warnings (e.g. ESLint).
131
+ function handleWarnings(warnings) {
132
+ clearOutdatedErrors();
133
+ var isHotUpdate = !isFirstCompilation;
134
+ isFirstCompilation = false;
135
+ hasCompileErrors = false;
136
+ // Print warnings to the console.
137
+ const formatted = formatWebpackMessages({
138
+ warnings: warnings,
139
+ errors: []
140
+ });
141
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
142
+ for (let i = 0; i < formatted.warnings.length; i++) {
143
+ if (i === 5) {
144
+ console.warn('There were more warnings in other files.\n' +
145
+ 'You can find a complete log in the terminal.');
146
+ break;
147
+ }
148
+ console.warn(stripAnsi(formatted.warnings[i]));
149
+ }
150
+ }
151
+ // Attempt to apply hot updates or reload.
152
+ if (isHotUpdate) {
153
+ tryApplyUpdates(function onSuccessfulHotUpdate(hasUpdates) {
154
+ // Only dismiss it when we're sure it's a hot update.
155
+ // Otherwise it would flicker right before the reload.
156
+ onFastRefresh(hasUpdates);
157
+ });
158
+ }
159
+ }
160
+ // Compilation with errors (e.g. syntax error or missing modules).
161
+ function handleErrors(errors) {
162
+ if (!Boolean(errors && errors.length)) {
163
+ return;
164
+ }
165
+ clearOutdatedErrors();
166
+ isFirstCompilation = false;
167
+ hasCompileErrors = true;
168
+ // "Massage" webpack messages.
169
+ var formatted = formatWebpackMessages({
170
+ errors: errors,
171
+ warnings: []
172
+ });
173
+ // Only show the first error.
174
+ onBuildError(formatted.errors[0]);
175
+ // Also log them to the console.
176
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
177
+ for (var i = 0; i < formatted.errors.length; i++) {
178
+ console.error(stripAnsi(formatted.errors[i]));
179
+ }
180
+ }
181
+ }
182
+ // There is a newer version of the code available.
183
+ function handleAvailableHash(hash) {
184
+ // Update last known compilation hash.
185
+ mostRecentCompilationHash = hash;
186
+ }
187
+ // Handle messages from the server.
188
+ function processMessage(e) {
189
+ const obj = JSON.parse(e.data);
190
+ switch (obj.action) {
191
+ case 'building': {
192
+ startLatency = Date.now();
193
+ console.log('[Fast Refresh] bundle ' +
194
+ (obj.name ? "'" + obj.name + "' " : '') +
195
+ 'rebuilding');
196
+ break;
197
+ }
198
+ case 'built':
199
+ case 'sync': {
200
+ if (obj.hash) {
201
+ handleAvailableHash(obj.hash);
202
+ }
203
+ const { errors, warnings } = obj;
204
+ const hasErrors = Boolean(errors && errors.length);
205
+ if (hasErrors) {
206
+ return handleErrors(errors);
207
+ }
208
+ const hasWarnings = Boolean(warnings && warnings.length);
209
+ if (hasWarnings) {
210
+ return handleWarnings(warnings);
211
+ }
212
+ return handleSuccess();
213
+ }
214
+ case 'warnings':
215
+ handleWarnings(obj.data);
216
+ break;
217
+ case 'errors':
218
+ handleErrors(obj.data);
219
+ break;
220
+ default: {
221
+ if (customHmrEventHandler) {
222
+ customHmrEventHandler(obj);
223
+ break;
224
+ }
225
+ break;
226
+ }
227
+ }
228
+ }
229
+ // Is there a newer version of this code available?
230
+ function isUpdateAvailable() {
231
+ /* globals __webpack_hash__ */
232
+ // __webpack_hash__ is the hash of the current compilation.
233
+ // It's a global variable injected by Webpack.
234
+ return mostRecentCompilationHash !== __webpack_hash__;
235
+ }
236
+ // Webpack disallows updates in other states.
237
+ function canApplyUpdates() {
238
+ return module.hot.status() === 'idle';
239
+ }
240
+ function waitForReady() {
241
+ return new Promise((resolve, reject) => {
242
+ if (module.hot.status() !== 'prepare') {
243
+ reject();
244
+ }
245
+ const handler = status => {
246
+ module.hot.removeStatusHandler(handler);
247
+ if (status === 'ready') {
248
+ resolve();
249
+ }
250
+ if (status === 'abort' || status === 'fail') {
251
+ reject();
252
+ }
253
+ };
254
+ module.hot.addStatusHandler(handler);
255
+ });
256
+ }
257
+ // Attempt to update code on the fly, fall back to a hard reload.
258
+ function tryApplyUpdates(onHotUpdateSuccess) {
259
+ return __awaiter(this, void 0, void 0, function* () {
260
+ if (!module.hot) {
261
+ // HotModuleReplacementPlugin is not in Webpack configuration.
262
+ console.error('HotModuleReplacementPlugin is not in Webpack configuration.');
263
+ window.location.reload();
264
+ return;
265
+ }
266
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
267
+ onBuildOk();
268
+ // HMR failed, need to refresh
269
+ const hmrStatus = module.hot.status();
270
+ if (hmrStatus === 'abort' || hmrStatus === 'fail') {
271
+ window.location.reload();
272
+ }
273
+ return;
274
+ }
275
+ function handleApplyUpdates(err, updatedModules) {
276
+ const hasUpdates = Boolean(updatedModules === null || updatedModules === void 0 ? void 0 : updatedModules.length);
277
+ if (hadRuntimeError) {
278
+ hadRuntimeError = false;
279
+ window.location.reload();
280
+ return;
281
+ }
282
+ if (err) {
283
+ hadRuntimeError = true;
284
+ }
285
+ if (typeof onHotUpdateSuccess === 'function') {
286
+ // Maybe we want to do something.
287
+ onHotUpdateSuccess(hasUpdates);
288
+ }
289
+ if (isUpdateAvailable()) {
290
+ // While we were updating, there was a new update! Do it again.
291
+ tryApplyUpdates(hasUpdates ? onBuildOk : onHotUpdateSuccess);
292
+ }
293
+ else {
294
+ onBuildOk();
295
+ }
296
+ }
297
+ try {
298
+ // https://webpack.js.org/api/hot-module-replacement/#check
299
+ let updatedModules = yield module.hot.check(/* autoApply */ false);
300
+ if (!updatedModules) {
301
+ return;
302
+ }
303
+ // if there is another updating, delay the update
304
+ // multiple hotupdate occurs during import() will cause hmr error
305
+ // so we delay the adjacent hotupdates
306
+ // import() == loade module script ----> require(module)
307
+ // |
308
+ // |
309
+ // if applyUpdate happens here, require will cause a error
310
+ if (isUpdateAvailable()) {
311
+ yield new Promise(resolve => {
312
+ setTimeout(resolve, 50);
313
+ });
314
+ }
315
+ if (updatedModules) {
316
+ if (module.hot.status() !== 'ready') {
317
+ yield waitForReady();
318
+ }
319
+ updatedModules = yield module.hot.apply();
320
+ }
321
+ handleApplyUpdates(null, updatedModules);
322
+ }
323
+ catch (err) {
324
+ handleApplyUpdates(err, null);
325
+ }
326
+ });
327
+ }
@@ -0,0 +1,3 @@
1
+ import { InternalApplication } from '../../shared';
2
+ import { HotDevClient } from './hotDevClient';
3
+ export declare const initHMRAndDevClient: (app: InternalApplication) => HotDevClient;
@@ -0,0 +1,27 @@
1
+ import { DEV_SOCKET_TIMEOUT_MS, DEV_HOT_MIDDLEWARE_PATH, DEV_HOT_LAUNCH_EDITOR_ENDPOINT } from '@shuvi/shared/esm/constants';
2
+ import connect from './hotDevClient';
3
+ let devClient;
4
+ export const initHMRAndDevClient = (app) => {
5
+ if (devClient) {
6
+ return devClient;
7
+ }
8
+ devClient = connect({
9
+ launchEditorEndpoint: DEV_HOT_LAUNCH_EDITOR_ENDPOINT,
10
+ path: DEV_HOT_MIDDLEWARE_PATH,
11
+ location
12
+ });
13
+ setInterval(() => {
14
+ devClient.sendMessage(JSON.stringify({
15
+ event: 'updatePageStatus',
16
+ currentRoutes: app.router.current.matches.map(({ route: { __componentRawRequest__ } }) => __componentRawRequest__),
17
+ page: location.pathname
18
+ }));
19
+ }, DEV_SOCKET_TIMEOUT_MS / 2);
20
+ devClient.subscribeToHmrEvent((event) => {
21
+ // if (obj.action === "reloadPage") {
22
+ // return window.location.reload();
23
+ // }
24
+ // throw new Error("Unexpected action " + obj.action);
25
+ });
26
+ return devClient;
27
+ };
@@ -0,0 +1,16 @@
1
+ export declare function addMessageListener(cb: (event: any) => void): void;
2
+ export declare function sendMessage(data: any): any;
3
+ export declare type HotDevClient = {
4
+ sendMessage: (data: any) => void;
5
+ subscribeToHmrEvent?: (handler: any) => void;
6
+ };
7
+ export declare function connectHMR(options: {
8
+ path: string;
9
+ timeout: number;
10
+ log?: boolean;
11
+ location: {
12
+ protocol: string;
13
+ hostname: string;
14
+ port?: string;
15
+ };
16
+ }): void;
@@ -0,0 +1,61 @@
1
+ let source;
2
+ const eventCallbacks = [];
3
+ let lastActivity = Date.now();
4
+ let initDataBeforeWsOnline = [];
5
+ function getSocketProtocol(protocol) {
6
+ return protocol === 'http:' ? 'ws' : 'wss';
7
+ }
8
+ export function addMessageListener(cb) {
9
+ eventCallbacks.push(cb);
10
+ }
11
+ export function sendMessage(data) {
12
+ if (!source || source.readyState !== source.OPEN) {
13
+ initDataBeforeWsOnline.push(data);
14
+ return;
15
+ }
16
+ return source.send(data);
17
+ }
18
+ export function connectHMR(options) {
19
+ if (!options.timeout) {
20
+ options.timeout = 5000;
21
+ }
22
+ init();
23
+ let timer = setInterval(function () {
24
+ if (Date.now() - lastActivity > options.timeout) {
25
+ handleDisconnect();
26
+ }
27
+ }, options.timeout / 2);
28
+ function init() {
29
+ if (source)
30
+ source.close();
31
+ let { protocol, hostname, port } = options.location;
32
+ protocol = getSocketProtocol(protocol);
33
+ let url = `${protocol}://${hostname}:${port}`;
34
+ source = new WebSocket(`${url}${options.path}`);
35
+ source.onopen = handleOnline;
36
+ source.onerror = handleDisconnect;
37
+ source.onmessage = handleMessage;
38
+ }
39
+ function handleOnline() {
40
+ if (initDataBeforeWsOnline.length !== 0) {
41
+ initDataBeforeWsOnline.forEach(data => {
42
+ sendMessage(data);
43
+ });
44
+ initDataBeforeWsOnline = [];
45
+ }
46
+ if (options.log)
47
+ console.log('[HMR] connected');
48
+ lastActivity = Date.now();
49
+ }
50
+ function handleMessage(event) {
51
+ lastActivity = Date.now();
52
+ eventCallbacks.forEach(cb => {
53
+ cb(event);
54
+ });
55
+ }
56
+ function handleDisconnect() {
57
+ clearInterval(timer);
58
+ source.close();
59
+ setTimeout(init, options.timeout);
60
+ }
61
+ }
@@ -1,2 +1,3 @@
1
+ declare const app: import("../../app/client").InternalApplication;
1
2
  declare const run: () => Promise<void>;
2
- export { run };
3
+ export { run, app };
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { CLIENT_CONTAINER_ID } from '@shuvi/shared/lib/constants';
11
11
  // renderer must be imported before application
12
- // we need to init init renderer before import AppComponent
12
+ // we need to init renderer before import AppComponent
13
13
  import { view, getRoutes, app as PlatformAppComponent } from '@shuvi/app/core/platform';
14
14
  import routes from '@shuvi/app/files/routes';
15
15
  import { getAppData } from '@shuvi/platform-shared/shared/helper/getAppData';
@@ -20,19 +20,19 @@ const app = createApp({
20
20
  routes,
21
21
  appData
22
22
  });
23
- const render = () => {
23
+ const render = () => __awaiter(void 0, void 0, void 0, function* () {
24
24
  const appContainer = document.getElementById(CLIENT_CONTAINER_ID);
25
- view.renderApp({
25
+ yield view.renderApp({
26
26
  app: app.getPublicAPI(),
27
27
  appData,
28
28
  appContainer
29
29
  });
30
- };
30
+ });
31
31
  const run = () => __awaiter(void 0, void 0, void 0, function* () {
32
32
  yield app.init();
33
- render();
33
+ yield render();
34
34
  });
35
- export { run };
35
+ export { run, app };
36
36
  if (module.hot) {
37
37
  const handleHotUpdate = () => __awaiter(void 0, void 0, void 0, function* () {
38
38
  const rerender = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -55,3 +55,10 @@ if (module.hot) {
55
55
  });
56
56
  module.hot.accept(['@shuvi/app/files/routes'], handleHotUpdate);
57
57
  }
58
+ // For e2e test
59
+ if (window.__SHUVI) {
60
+ window.__SHUVI.router = app.router;
61
+ }
62
+ else {
63
+ window.__SHUVI = { router: app.router };
64
+ }
@@ -1,5 +1,5 @@
1
1
  // shuvi built-in entry
2
- // IMPORTANT: there files must be runned before any other codes
2
+ // IMPORTANT: there files must be run before any other codes
3
3
  import './setup-env';
4
4
  // user entry
5
5
  import '@shuvi/app/core/entry';
@@ -8,23 +8,22 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  /// <reference lib="dom" />
11
- import { DEV_STYLE_HIDE_FOUC, DEV_STYLE_PREPARE } from '@shuvi/shared/lib/constants';
12
- import initWebpackHMR from '../../dev/webpackHotDevClient';
13
- import { run } from './app';
11
+ import { DEV_STYLE_HIDE_FOUC } from '@shuvi/shared/lib/constants';
12
+ import { initHMRAndDevClient } from '../../dev';
13
+ import { run, app } from './app';
14
+ function applyStyle() {
15
+ document
16
+ .querySelectorAll(`[${DEV_STYLE_HIDE_FOUC}]`)
17
+ .forEach(el => { var _a; return (_a = el.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(el); });
18
+ }
14
19
  function init() {
15
20
  return __awaiter(this, void 0, void 0, function* () {
16
- initWebpackHMR();
17
- // reduce FOUC caused by style-loader
18
- const styleReady = new Promise(resolve => {
19
- (window.requestAnimationFrame || setTimeout)(() => __awaiter(this, void 0, void 0, function* () {
20
- yield window[DEV_STYLE_PREPARE];
21
- document
22
- .querySelectorAll(`[${DEV_STYLE_HIDE_FOUC}]`)
23
- .forEach(el => { var _a; return (_a = el.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(el); });
24
- resolve();
25
- }));
26
- });
27
- yield styleReady;
21
+ initHMRAndDevClient(app);
28
22
  });
29
23
  }
30
- init().then(run);
24
+ init()
25
+ .then(() => run())
26
+ .finally(() => {
27
+ // reduce FOUC caused by style-loader
28
+ applyStyle();
29
+ });
@@ -1,6 +1,7 @@
1
- import * as application from '../../app/server';
2
- import * as server from '@shuvi/app/user/server';
1
+ import { default as pageRoutes } from '@shuvi/app/files/routes';
3
2
  import { default as apiRoutes } from '@shuvi/app/files/apiRoutes';
4
3
  import { default as middlewareRoutes } from '@shuvi/app/files/middlewareRoutes';
5
- export { server, application, apiRoutes, middlewareRoutes };
6
- export { view } from '@shuvi/app/core/platform';
4
+ import { view } from '@shuvi/app/core/platform';
5
+ import * as server from '@shuvi/app/user/server';
6
+ import * as application from '../../app/server';
7
+ export { pageRoutes, apiRoutes, middlewareRoutes, server, view, application };
@@ -1,7 +1,8 @@
1
1
  // This is the shuvi server-side main module exports collection
2
- import * as application from '../../app/server';
3
- import * as server from '@shuvi/app/user/server';
2
+ import { default as pageRoutes } from '@shuvi/app/files/routes';
4
3
  import { default as apiRoutes } from '@shuvi/app/files/apiRoutes';
5
4
  import { default as middlewareRoutes } from '@shuvi/app/files/middlewareRoutes';
6
- export { server, application, apiRoutes, middlewareRoutes };
7
- export { view } from '@shuvi/app/core/platform';
5
+ import { view } from '@shuvi/app/core/platform';
6
+ import * as server from '@shuvi/app/user/server';
7
+ import * as application from '../../app/server';
8
+ export { pageRoutes, apiRoutes, middlewareRoutes, server, view, application };
@@ -0,0 +1,2 @@
1
+ import { IError } from '@shuvi/platform-shared/shared';
2
+ export declare function serializeServerError(err: Error): IError;
@@ -0,0 +1,21 @@
1
+ // @ts-ignore
2
+ import stripAnsi from 'strip-ansi';
3
+ function errorToJSON(err) {
4
+ return {
5
+ code: 500,
6
+ message: stripAnsi(err.message),
7
+ name: err.name,
8
+ source: 'server',
9
+ stack: err.stack
10
+ };
11
+ }
12
+ export function serializeServerError(err) {
13
+ if (process.env.NODE_ENV === 'development') {
14
+ return errorToJSON(err);
15
+ }
16
+ return {
17
+ code: 500,
18
+ message: 'Internal Server Error',
19
+ name: 'Internal Server Error'
20
+ };
21
+ }
@@ -1,6 +1,5 @@
1
1
  import * as React from 'react';
2
- import { IApplication } from '@shuvi/platform-shared/shared';
3
- export default function AppContainer({ children, app }: {
4
- app: IApplication;
5
- children: React.ReactElement;
6
- }): JSX.Element;
2
+ import { Application } from '../../shared';
3
+ export default function AppContainer({ app, children }: React.PropsWithChildren<{
4
+ app: Application;
5
+ }>): JSX.Element;
@@ -1,10 +1,9 @@
1
1
  import * as React from 'react';
2
2
  import { errorModel } from '@shuvi/platform-shared/shared';
3
- import { createContainer } from '@shuvi/redox-react';
4
- import { AppProvider } from './applicationContext';
3
+ import { AppProvider } from './ApplicationContext';
5
4
  import ErrorPage from './ErrorPage';
6
5
  import { ErrorBoundary } from './ErrorBoundary';
7
- const { Provider, useSharedModel } = createContainer();
6
+ import { Provider, useSharedModel } from './store';
8
7
  function ErrorGuard({ children = null }) {
9
8
  const [errorState] = useSharedModel(errorModel);
10
9
  if (errorState.error !== undefined) {
@@ -12,10 +11,10 @@ function ErrorGuard({ children = null }) {
12
11
  }
13
12
  return <>{children}</>;
14
13
  }
15
- export default function AppContainer({ children, app }) {
14
+ export default function AppContainer({ app, children }) {
16
15
  return (<ErrorBoundary>
17
16
  <AppProvider app={app}>
18
- <Provider storeManager={app.storeManager}>
17
+ <Provider store={app.store}>
19
18
  <ErrorGuard>{children}</ErrorGuard>
20
19
  </Provider>
21
20
  </AppProvider>
@@ -0,0 +1,7 @@
1
+ import * as React from 'react';
2
+ import { Application } from '../../shared';
3
+ export declare const ApplicationContext: React.Context<Application>;
4
+ export declare function AppProvider({ app, children }: React.PropsWithChildren<{
5
+ app: Application;
6
+ }>): JSX.Element;
7
+ export declare function useApp(): Application;
@@ -1,5 +1,6 @@
1
1
  import * as React from 'react';
2
2
  import { Head } from './head';
3
+ import { useApp } from './ApplicationContext';
3
4
  const style = {
4
5
  container: {
5
6
  color: '#000',
@@ -25,13 +26,15 @@ const style = {
25
26
  }
26
27
  };
27
28
  export default function Error({ errorCode, errorDesc }) {
29
+ const app = useApp();
28
30
  return (<div style={style.container}>
29
31
  <Head>
30
32
  <title>Page Error</title>
31
33
  </Head>
32
34
 
33
35
  <div style={style.error}>
34
- <div style={style.errorCode}>{errorCode}</div>
36
+ {/* 500 will cause confusion for SPA application, so only show error code on SSR */}
37
+ {app.config.ssr && <div style={style.errorCode}>{errorCode}</div>}
35
38
  <div style={style.errorDesc}>{errorDesc || 'Error'}</div>
36
39
  </div>
37
40
  </div>);