@modern-js/runtime 1.4.3 → 1.15.0

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 (83) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/js/modern/cli/index.js +1 -3
  3. package/dist/js/modern/core/app-config.js +10 -0
  4. package/dist/js/modern/core/compatible.js +218 -0
  5. package/dist/js/modern/core/index.js +7 -0
  6. package/dist/js/modern/core/loader/index.js +1 -0
  7. package/dist/js/modern/core/loader/loaderManager.js +189 -0
  8. package/dist/js/modern/core/loader/useLoader.js +105 -0
  9. package/dist/js/modern/core/plugin.js +63 -0
  10. package/dist/js/modern/core/runtime-context.js +2 -0
  11. package/dist/js/modern/exports/styled.js +2 -2
  12. package/dist/js/modern/index.js +1 -1
  13. package/dist/js/modern/router/runtime/plugin.js +1 -1
  14. package/dist/js/modern/router/runtime/utils.js +3 -1
  15. package/dist/js/modern/ssr/index.js +4 -0
  16. package/dist/js/modern/ssr/index.node.js +1 -1
  17. package/dist/js/modern/ssr/prefetch.js +2 -2
  18. package/dist/js/modern/ssr/serverRender/index.js +1 -1
  19. package/dist/js/modern/ssr/serverRender/styledComponent.js +1 -1
  20. package/dist/js/modern/ssr/utils.js +9 -3
  21. package/dist/js/modern/state/cli/index.js +1 -1
  22. package/dist/js/modern/state/runtime/plugin.js +1 -1
  23. package/dist/js/node/cli/index.js +1 -3
  24. package/dist/js/node/core/app-config.js +22 -0
  25. package/dist/js/node/core/compatible.js +247 -0
  26. package/dist/js/node/core/index.js +111 -0
  27. package/dist/js/node/core/loader/index.js +15 -0
  28. package/dist/js/node/core/loader/loaderManager.js +201 -0
  29. package/dist/js/node/core/loader/useLoader.js +118 -0
  30. package/dist/js/node/core/plugin.js +79 -0
  31. package/dist/js/node/core/runtime-context.js +11 -0
  32. package/dist/js/node/exports/styled.js +5 -5
  33. package/dist/js/node/index.js +10 -10
  34. package/dist/js/node/router/runtime/plugin.js +3 -3
  35. package/dist/js/node/router/runtime/utils.js +3 -1
  36. package/dist/js/node/ssr/index.js +4 -0
  37. package/dist/js/node/ssr/index.node.js +2 -2
  38. package/dist/js/node/ssr/serverRender/index.js +2 -2
  39. package/dist/js/node/ssr/serverRender/styledComponent.js +2 -2
  40. package/dist/js/node/ssr/utils.js +9 -3
  41. package/dist/js/node/state/cli/index.js +1 -1
  42. package/dist/js/node/state/runtime/plugin.js +3 -3
  43. package/dist/js/treeshaking/cli/index.js +1 -3
  44. package/dist/js/treeshaking/core/app-config.js +13 -0
  45. package/dist/js/treeshaking/core/compatible.js +255 -0
  46. package/dist/js/treeshaking/core/index.js +7 -0
  47. package/dist/js/treeshaking/core/loader/index.js +1 -0
  48. package/dist/js/treeshaking/core/loader/loaderManager.js +267 -0
  49. package/dist/js/treeshaking/core/loader/useLoader.js +107 -0
  50. package/dist/js/treeshaking/core/plugin.js +105 -0
  51. package/dist/js/treeshaking/core/runtime-context.js +2 -0
  52. package/dist/js/treeshaking/exports/styled.js +2 -2
  53. package/dist/js/treeshaking/index.js +1 -1
  54. package/dist/js/treeshaking/router/runtime/plugin.js +1 -1
  55. package/dist/js/treeshaking/router/runtime/utils.js +3 -1
  56. package/dist/js/treeshaking/ssr/index.js +4 -0
  57. package/dist/js/treeshaking/ssr/index.node.js +1 -1
  58. package/dist/js/treeshaking/ssr/prefetch.js +2 -2
  59. package/dist/js/treeshaking/ssr/serverRender/index.js +1 -1
  60. package/dist/js/treeshaking/ssr/serverRender/styledComponent.js +1 -1
  61. package/dist/js/treeshaking/ssr/utils.js +8 -3
  62. package/dist/js/treeshaking/state/cli/index.js +1 -1
  63. package/dist/js/treeshaking/state/runtime/plugin.js +1 -1
  64. package/dist/types/core/app-config.d.ts +6 -0
  65. package/dist/types/core/compatible.d.ts +13 -0
  66. package/dist/types/core/index.d.ts +9 -0
  67. package/dist/types/core/loader/index.d.ts +2 -0
  68. package/dist/types/core/loader/loaderManager.d.ts +57 -0
  69. package/dist/types/core/loader/useLoader.d.ts +54 -0
  70. package/dist/types/core/plugin.d.ts +208 -0
  71. package/dist/types/core/runtime-context.d.ts +13 -0
  72. package/dist/types/exports/styled.d.ts +2 -2
  73. package/dist/types/index.d.ts +4 -9
  74. package/dist/types/router/runtime/plugin.d.ts +1 -1
  75. package/dist/types/ssr/index.d.ts +2 -2
  76. package/dist/types/ssr/index.node.d.ts +1 -1
  77. package/dist/types/ssr/prefetch.d.ts +2 -2
  78. package/dist/types/ssr/serverRender/entry.d.ts +1 -1
  79. package/dist/types/ssr/serverRender/index.d.ts +1 -1
  80. package/dist/types/ssr/serverRender/type.d.ts +1 -1
  81. package/dist/types/state/runtime/plugin.d.ts +2 -2
  82. package/lib/types.d.ts +10 -0
  83. package/package.json +36 -26
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # @modern-js/runtime
2
2
 
3
+ ## 1.15.0
4
+
5
+ ### Patch Changes
6
+
7
+ - 335c97c: fix: fix runtime context format bug
8
+ fix: 修复 runtimeContext 数据格式化时的问题
9
+ - a04a11b: fix: 修复 SSR 物理降级时,获取不到请求上下文的问题
10
+ fix: should get ssrContext anyway if entry is ssr enable
11
+ - Updated dependencies [8658a78]
12
+ - Updated dependencies [0df4970]
13
+ - Updated dependencies [05d4a4f]
14
+ - Updated dependencies [ad05af9]
15
+ - Updated dependencies [5d53d1c]
16
+ - Updated dependencies [37cd159]
17
+ - @modern-js/utils@1.15.0
18
+ - @modern-js/webpack@1.15.0
19
+ - @modern-js/plugin@1.15.0
20
+
21
+ ## 1.5.0
22
+
23
+ ### Minor Changes
24
+
25
+ - 59c941a: chore(runtime): merge `@modern-js/runtime-core` to `@modern-js/runtime`
26
+
27
+ chore(runtime): 合并 `@modern-js/runtime-core` 到 `@modern-js/runtime`
28
+
29
+ ### Patch Changes
30
+
31
+ - e0cd14a: feat: support runtime router and state type
32
+
33
+ feat: 支持在 `modern.config.ts` 中提示 `runtime.router` and `runtime.state` 类型
34
+
35
+ - 287ac8b: fix(runtime): router plugin replace error
36
+
37
+ fix(runtime): router 插件 replace 报错
38
+
39
+ - Updated dependencies [79e83ef]
40
+ - Updated dependencies [5f1a231]
41
+ - Updated dependencies [22f4dca]
42
+ - Updated dependencies [7b9067f]
43
+ - @modern-js/utils@1.9.0
44
+ - @modern-js/webpack@1.12.4
45
+
3
46
  ## 1.4.3
4
47
 
5
48
  ### Patch Changes
@@ -25,9 +25,7 @@ export default (() => ({
25
25
  * But it will not be installed under the user project.
26
26
  * So need to add alias
27
27
  */
28
- 'styled-components': require.resolve('styled-components', {
29
- paths: [require.resolve('@modern-js/runtime-core')]
30
- })
28
+ 'styled-components': require.resolve('styled-components')
31
29
  }
32
30
  }
33
31
  };
@@ -0,0 +1,10 @@
1
+ const APP_CONFIG_SYMBOL = 'config';
2
+ export const getConfig = Component => // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3
+ // @ts-expect-error
4
+ Component[APP_CONFIG_SYMBOL];
5
+ export const defineConfig = (Component, config) => {
6
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7
+ // @ts-expect-error
8
+ Component[APP_CONFIG_SYMBOL] = config;
9
+ return Component;
10
+ };
@@ -0,0 +1,218 @@
1
+ const _excluded = ["context"];
2
+
3
+ function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
4
+
5
+ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
6
+
7
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
8
+
9
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
10
+
11
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
+
13
+ import React, { useContext, useMemo } from 'react';
14
+ import ReactDOM from 'react-dom';
15
+ import hoistNonReactStatics from 'hoist-non-react-statics';
16
+ import { runtime } from "./plugin";
17
+ import { RuntimeReactContext } from "./runtime-context";
18
+ import { createLoaderManager } from "./loader/loaderManager";
19
+ import { jsx as _jsx } from "react/jsx-runtime";
20
+
21
+ function isClientArgs(id) {
22
+ return typeof id === 'string' || typeof HTMLElement !== 'undefined' && id instanceof HTMLElement;
23
+ }
24
+
25
+ const runnerMap = new WeakMap();
26
+
27
+ const getInitialContext = runner => ({
28
+ loaderManager: createLoaderManager({}),
29
+ runner,
30
+ isBrowser: true
31
+ });
32
+
33
+ export const createApp = ({
34
+ plugins
35
+ }) => {
36
+ const appRuntime = runtime.clone();
37
+ appRuntime.usePlugin(...plugins);
38
+ return App => {
39
+ const runner = appRuntime.init();
40
+
41
+ const WrapperComponent = props => {
42
+ const element = /*#__PURE__*/React.createElement(App || React.Fragment, _objectSpread({}, props), props.children);
43
+ const context = useContext(RuntimeReactContext);
44
+ return runner.provide({
45
+ element,
46
+ props: _objectSpread({}, props),
47
+ context
48
+ }, {
49
+ onLast: ({
50
+ element
51
+ }) => element
52
+ });
53
+ };
54
+
55
+ if (App) {
56
+ hoistNonReactStatics(WrapperComponent, App);
57
+ }
58
+
59
+ const HOCApp = runner.hoc({
60
+ App: WrapperComponent
61
+ }, {
62
+ onLast: ({
63
+ App
64
+ }) => {
65
+ const WrapComponent = _ref => {
66
+ var _contextValue;
67
+
68
+ let {
69
+ context
70
+ } = _ref,
71
+ props = _objectWithoutProperties(_ref, _excluded);
72
+
73
+ let contextValue = context; // We should construct the context, when root component is not passed into `bootstrap`.
74
+
75
+ if (!((_contextValue = contextValue) !== null && _contextValue !== void 0 && _contextValue.runner)) {
76
+ contextValue = getInitialContext(runner);
77
+ runner.init({
78
+ context: contextValue
79
+ }, {
80
+ onLast: ({
81
+ context: context1
82
+ }) => {
83
+ var _App$init;
84
+
85
+ return App === null || App === void 0 ? void 0 : (_App$init = App.init) === null || _App$init === void 0 ? void 0 : _App$init.call(App, context1);
86
+ }
87
+ });
88
+ }
89
+
90
+ return /*#__PURE__*/_jsx(RuntimeReactContext.Provider, {
91
+ value: contextValue,
92
+ children: /*#__PURE__*/_jsx(App, _objectSpread({}, props))
93
+ });
94
+ };
95
+
96
+ return hoistNonReactStatics(WrapComponent, App);
97
+ }
98
+ });
99
+ runnerMap.set(HOCApp, runner);
100
+ return HOCApp;
101
+ };
102
+ };
103
+ export const bootstrap = async (BootApp,
104
+ /**
105
+ * When csr, id is root id.
106
+ * When ssr, id is serverContext
107
+ */
108
+ id) => {
109
+ let App = BootApp;
110
+ let runner = runnerMap.get(App); // ensure Component used is created by `createApp`
111
+
112
+ if (!runner) {
113
+ App = createApp({
114
+ plugins: []
115
+ })(App);
116
+ runner = runnerMap.get(App);
117
+ }
118
+
119
+ const context = getInitialContext(runner);
120
+
121
+ const runInit = _context => runner.init({
122
+ context: _context
123
+ }, {
124
+ onLast: ({
125
+ context: context1
126
+ }) => {
127
+ var _App, _App$init2;
128
+
129
+ return (_App = App) === null || _App === void 0 ? void 0 : (_App$init2 = _App.init) === null || _App$init2 === void 0 ? void 0 : _App$init2.call(_App, context1);
130
+ }
131
+ }); // don't mount the App, let user in charge of it.
132
+
133
+
134
+ if (!id) {
135
+ return /*#__PURE__*/React.createElement(App, {
136
+ context
137
+ });
138
+ }
139
+
140
+ const isBrowser = typeof window !== 'undefined' && window.name !== 'nodejs';
141
+
142
+ if (isBrowser) {
143
+ if (isClientArgs(id)) {
144
+ var _ssrData$data, _ssrData$data2;
145
+
146
+ const ssrData = window._SSR_DATA;
147
+ const loadersData = (ssrData === null || ssrData === void 0 ? void 0 : (_ssrData$data = ssrData.data) === null || _ssrData$data === void 0 ? void 0 : _ssrData$data.loadersData) || {};
148
+ const initialLoadersState = Object.keys(loadersData).reduce((res, key) => {
149
+ const loaderData = loadersData[key];
150
+
151
+ if (loaderData.loading !== false) {
152
+ return res;
153
+ }
154
+
155
+ res[key] = loaderData;
156
+ return res;
157
+ }, {});
158
+ Object.assign(context, _objectSpread({
159
+ loaderManager: createLoaderManager(initialLoadersState, {
160
+ skipStatic: true
161
+ })
162
+ }, ssrData ? {
163
+ ssrContext: ssrData === null || ssrData === void 0 ? void 0 : ssrData.context
164
+ } : {}));
165
+ context.initialData = ssrData === null || ssrData === void 0 ? void 0 : (_ssrData$data2 = ssrData.data) === null || _ssrData$data2 === void 0 ? void 0 : _ssrData$data2.initialData;
166
+ const initialData = await runInit(context);
167
+
168
+ if (initialData) {
169
+ context.initialData = initialData;
170
+ }
171
+
172
+ return runner.client({
173
+ App,
174
+ context,
175
+ rootElement: typeof id !== 'string' ? id : document.getElementById(id || 'root')
176
+ }, {
177
+ onLast: ({
178
+ App,
179
+ rootElement
180
+ }) => {
181
+ ReactDOM.render( /*#__PURE__*/React.createElement(App, {
182
+ context
183
+ }), rootElement);
184
+ }
185
+ });
186
+ } else {
187
+ throw Error('`bootstrap` needs id in browser environment, it needs to be string or element');
188
+ }
189
+ } else {
190
+ Object.assign(context, {
191
+ ssrContext: id,
192
+ isBrowser: false,
193
+ loaderManager: createLoaderManager({}, {
194
+ skipNonStatic: id.staticGenerate,
195
+ // if not static generate, only non-static loader can exec on prod env
196
+ skipStatic: process.env.NODE_ENV === 'production' && !id.staticGenerate
197
+ })
198
+ });
199
+ const initialData = await runInit(context);
200
+ context.initialData = initialData;
201
+ return runner.server({
202
+ App,
203
+ context
204
+ });
205
+ }
206
+ };
207
+ export const useRuntimeContext = () => {
208
+ const context = useContext(RuntimeReactContext);
209
+ const memoizedContext = useMemo(() => context.runner.pickContext({
210
+ context,
211
+ pickedContext: {}
212
+ }, {
213
+ onLast: ({
214
+ pickedContext
215
+ }) => pickedContext
216
+ }), [context]);
217
+ return memoizedContext;
218
+ };
@@ -0,0 +1,7 @@
1
+ export { createPlugin, createRuntime, runtime, registerInit, registerPrefetch } from "./plugin";
2
+ export { defineConfig, getConfig } from "./app-config";
3
+ // compatible
4
+ export * from "./compatible";
5
+ export { RuntimeReactContext } from "./runtime-context";
6
+ export * from "./loader";
7
+ export * from '@modern-js/plugin';
@@ -0,0 +1 @@
1
+ export { default as useLoader } from "./useLoader";
@@ -0,0 +1,189 @@
1
+ import invariant from 'invariant';
2
+
3
+ /**
4
+ * Calc id from string or object
5
+ */
6
+ const createGetId = () => {
7
+ const idCache = new Map();
8
+ return objectId => {
9
+ const cachedId = idCache.get(objectId);
10
+
11
+ if (cachedId) {
12
+ return cachedId;
13
+ } // WARNING: id should be unique after serialize.
14
+
15
+
16
+ const id = JSON.stringify(objectId);
17
+ invariant(id, 'params should be not null value');
18
+ idCache.set(objectId, id);
19
+ return id;
20
+ };
21
+ };
22
+
23
+ export let LoaderStatus;
24
+
25
+ (function (LoaderStatus) {
26
+ LoaderStatus[LoaderStatus["idle"] = 0] = "idle";
27
+ LoaderStatus[LoaderStatus["loading"] = 1] = "loading";
28
+ LoaderStatus[LoaderStatus["fulfilled"] = 2] = "fulfilled";
29
+ LoaderStatus[LoaderStatus["rejected"] = 3] = "rejected";
30
+ })(LoaderStatus || (LoaderStatus = {}));
31
+
32
+ const createLoader = (id, initialData = {
33
+ loading: false,
34
+ reloading: false,
35
+ data: undefined,
36
+ error: undefined
37
+ }, loaderFn, skip = false) => {
38
+ let promise;
39
+ let status = LoaderStatus.idle;
40
+ let {
41
+ data,
42
+ error
43
+ } = initialData;
44
+ let hasLoaded = false;
45
+ const handlers = new Set();
46
+
47
+ const load = async () => {
48
+ if (skip) {
49
+ return promise;
50
+ }
51
+
52
+ if (status === LoaderStatus.loading) {
53
+ return promise;
54
+ }
55
+
56
+ status = LoaderStatus.loading;
57
+ notify();
58
+ promise = loaderFn().then(value => {
59
+ data = value;
60
+ error = null;
61
+ status = LoaderStatus.fulfilled;
62
+ }).catch(e => {
63
+ error = e;
64
+ data = null;
65
+ status = LoaderStatus.rejected;
66
+ }).finally(() => {
67
+ promise = null;
68
+ hasLoaded = true;
69
+ notify();
70
+ });
71
+ return promise;
72
+ };
73
+
74
+ const getResult = () => ({
75
+ loading: !hasLoaded && status === LoaderStatus.loading,
76
+ reloading: hasLoaded && status === LoaderStatus.loading,
77
+ data,
78
+ error: error instanceof Error ? `${error.message}` : error,
79
+ // redundant fields for ssr log
80
+ _error: error
81
+ });
82
+
83
+ const notify = () => {
84
+ // don't iterate handlers directly, since it could be modified during iteration
85
+ [...handlers].forEach(handler => {
86
+ handler(status, getResult());
87
+ });
88
+ };
89
+
90
+ const onChange = handler => {
91
+ handlers.add(handler);
92
+ return () => {
93
+ handlers.delete(handler);
94
+ };
95
+ };
96
+
97
+ return {
98
+ get result() {
99
+ return getResult();
100
+ },
101
+
102
+ get promise() {
103
+ return promise;
104
+ },
105
+
106
+ onChange,
107
+ load
108
+ };
109
+ };
110
+
111
+ /**
112
+ * Create loaders manager. It's returned instance will add to context
113
+ * @param initialDataMap used to initialing loader data
114
+ */
115
+ export const createLoaderManager = (initialDataMap, managerOptions = {}) => {
116
+ const {
117
+ skipStatic = false,
118
+ skipNonStatic = false
119
+ } = managerOptions;
120
+ const loadersMap = new Map();
121
+ const getId = createGetId();
122
+
123
+ const add = (loaderFn, loaderOptions) => {
124
+ const id = getId(loaderOptions.params);
125
+ let loader = loadersMap.get(id); // private property for opting out loader cache, maybe change in future
126
+
127
+ const cache = loaderOptions._cache;
128
+
129
+ if (!loader || cache === false) {
130
+ // ignore non-static loader on static phase
131
+ const ignoreNonStatic = skipNonStatic && !loaderOptions.static; // ignore static loader on non-static phase
132
+
133
+ const ignoreStatic = skipStatic && loaderOptions.static;
134
+ const skipExec = ignoreNonStatic || ignoreStatic;
135
+ loader = createLoader(id, typeof initialDataMap[id] !== 'undefined' ? initialDataMap[id] : {
136
+ data: loaderOptions.initialData
137
+ }, loaderFn, // Todo whether static loader is exec when CSR
138
+ skipExec);
139
+ loadersMap.set(id, loader);
140
+ }
141
+
142
+ return id;
143
+ };
144
+
145
+ const get = id => loadersMap.get(id); // check if there has pending loaders
146
+
147
+
148
+ const hasPendingLoaders = () => {
149
+ for (const loader of loadersMap.values()) {
150
+ const {
151
+ promise
152
+ } = loader;
153
+
154
+ if (promise instanceof Promise) {
155
+ return true;
156
+ }
157
+ }
158
+
159
+ return false;
160
+ }; // waiting for all pending loaders to be settled
161
+
162
+
163
+ const awaitPendingLoaders = async () => {
164
+ const pendingLoaders = [];
165
+
166
+ for (const [id, loader] of loadersMap) {
167
+ const {
168
+ promise
169
+ } = loader;
170
+
171
+ if (promise instanceof Promise) {
172
+ pendingLoaders.push([id, loader]);
173
+ }
174
+ }
175
+
176
+ await Promise.all(pendingLoaders.map(item => item[1].promise));
177
+ return pendingLoaders.reduce((res, [id, loader]) => {
178
+ res[id] = loader.result;
179
+ return res;
180
+ }, {});
181
+ };
182
+
183
+ return {
184
+ hasPendingLoaders,
185
+ awaitPendingLoaders,
186
+ add,
187
+ get
188
+ };
189
+ };
@@ -0,0 +1,105 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
+
5
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+
7
+ import { useContext, useRef, useMemo, useState, useCallback, useEffect } from 'react';
8
+ import invariant from 'invariant';
9
+ import { RuntimeReactContext } from "../runtime-context";
10
+ import { LoaderStatus } from "./loaderManager";
11
+
12
+ const useLoader = (loaderFn, options = {
13
+ params: undefined
14
+ }) => {
15
+ const context = useContext(RuntimeReactContext);
16
+ const isSSRRender = Boolean(context.ssr);
17
+ const {
18
+ loaderManager
19
+ } = context;
20
+ const loaderRef = useRef();
21
+ const unlistenLoaderChangeRef = useRef(null); // SSR render should ignore `_cache` prop
22
+
23
+ if (isSSRRender && Object.prototype.hasOwnProperty.call(options, '_cache')) {
24
+ delete options._cache;
25
+ }
26
+
27
+ const load = useCallback(params => {
28
+ var _unlistenLoaderChange, _window, _window$_SSR_DATA, _window$_SSR_DATA$dat, _window$_SSR_DATA$dat2, _loaderRef$current2;
29
+
30
+ if (typeof params === 'undefined') {
31
+ var _loaderRef$current;
32
+
33
+ return (_loaderRef$current = loaderRef.current) === null || _loaderRef$current === void 0 ? void 0 : _loaderRef$current.load();
34
+ }
35
+
36
+ const id = loaderManager.add(() => {
37
+ try {
38
+ const res = loaderFn(context, params);
39
+
40
+ if (res instanceof Promise) {
41
+ return res;
42
+ }
43
+
44
+ return Promise.resolve(res);
45
+ } catch (e) {
46
+ return Promise.reject(e);
47
+ }
48
+ }, _objectSpread(_objectSpread({}, options), {}, {
49
+ params
50
+ }));
51
+ loaderRef.current = loaderManager.get(id); // unsubscribe old loader onChange event
52
+
53
+ (_unlistenLoaderChange = unlistenLoaderChangeRef.current) === null || _unlistenLoaderChange === void 0 ? void 0 : _unlistenLoaderChange.call(unlistenLoaderChangeRef);
54
+
55
+ if (isSSRRender) {
56
+ return undefined;
57
+ } // skip this loader, then try to unlisten loader change
58
+
59
+
60
+ if (options.skip) {
61
+ return undefined;
62
+ } // do not load data again in CSR hydrate stage if SSR data exists
63
+
64
+
65
+ if (context._hydration && ((_window = window) === null || _window === void 0 ? void 0 : (_window$_SSR_DATA = _window._SSR_DATA) === null || _window$_SSR_DATA === void 0 ? void 0 : (_window$_SSR_DATA$dat = _window$_SSR_DATA.data) === null || _window$_SSR_DATA$dat === void 0 ? void 0 : (_window$_SSR_DATA$dat2 = _window$_SSR_DATA$dat.loadersData[id]) === null || _window$_SSR_DATA$dat2 === void 0 ? void 0 : _window$_SSR_DATA$dat2.error) === null) {
66
+ return undefined;
67
+ }
68
+
69
+ const res = loaderRef.current.load();
70
+ unlistenLoaderChangeRef.current = (_loaderRef$current2 = loaderRef.current) === null || _loaderRef$current2 === void 0 ? void 0 : _loaderRef$current2.onChange((_status, _result) => {
71
+ setResult(_result);
72
+
73
+ if (_status === LoaderStatus.fulfilled) {
74
+ var _options$onSuccess;
75
+
76
+ options === null || options === void 0 ? void 0 : (_options$onSuccess = options.onSuccess) === null || _options$onSuccess === void 0 ? void 0 : _options$onSuccess.call(options, _result.data);
77
+ }
78
+
79
+ if (_status === LoaderStatus.rejected) {
80
+ var _options$onError;
81
+
82
+ options === null || options === void 0 ? void 0 : (_options$onError = options.onError) === null || _options$onError === void 0 ? void 0 : _options$onError.call(options, _result.error);
83
+ }
84
+ });
85
+ return res;
86
+ }, [options.skip]);
87
+ useEffect(() => () => {
88
+ var _unlistenLoaderChange2;
89
+
90
+ (_unlistenLoaderChange2 = unlistenLoaderChangeRef.current) === null || _unlistenLoaderChange2 === void 0 ? void 0 : _unlistenLoaderChange2.call(unlistenLoaderChangeRef);
91
+ }, []);
92
+ useMemo(() => {
93
+ var _options$params;
94
+
95
+ const p = (_options$params = options.params) !== null && _options$params !== void 0 ? _options$params : loaderFn.id;
96
+ invariant(typeof p !== 'undefined' && p !== null, 'Params is required in useLoader');
97
+ load(p);
98
+ }, [options.params]);
99
+ const [result, setResult] = useState(loaderRef.current.result);
100
+ return _objectSpread(_objectSpread({}, result), {}, {
101
+ reload: load
102
+ });
103
+ };
104
+
105
+ export default useLoader;
@@ -0,0 +1,63 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
+
5
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+
7
+ import { createManager, createPipeline, createAsyncPipeline } from '@modern-js/plugin';
8
+ import { createLoaderManager } from "./loader/loaderManager";
9
+ const hoc = createPipeline(); // eslint-disable-next-line @typescript-eslint/no-empty-interface
10
+
11
+ const provide = createPipeline();
12
+ const client = createAsyncPipeline();
13
+ const server = createAsyncPipeline();
14
+ const init = createAsyncPipeline();
15
+ const pickContext = createPipeline();
16
+ const runtimeHooks = {
17
+ hoc,
18
+ provide,
19
+ client,
20
+ server,
21
+ init,
22
+ pickContext
23
+ };
24
+ /** All hooks of runtime plugin. */
25
+
26
+ export const createRuntime = () => createManager(runtimeHooks);
27
+ /**
28
+ * register init hook. It would be revoked both ssr and csr.
29
+ */
30
+
31
+ const registerInit = (App, _init) => {
32
+ const originalInit = App.init;
33
+
34
+ App.init = async context => {
35
+ if (!context.loaderManager) {
36
+ context.loaderManager = createLoaderManager({});
37
+ }
38
+
39
+ await Promise.all([originalInit === null || originalInit === void 0 ? void 0 : originalInit(context), _init === null || _init === void 0 ? void 0 : _init(context)]);
40
+ };
41
+ };
42
+ /**
43
+ * register prefetch hook. It would be revoked both ssr and csr.
44
+ * But if ssr success, It wont exec in csr again.
45
+ * If ssr prefetch failed, It will fallback to exec in csr.
46
+ */
47
+
48
+
49
+ const registerPrefetch = (App, prefetch) => {
50
+ const originalPrefetch = App.prefetch;
51
+
52
+ App.prefetch = async context => {
53
+ const originResult = await (originalPrefetch === null || originalPrefetch === void 0 ? void 0 : originalPrefetch(context));
54
+ const result = await (prefetch === null || prefetch === void 0 ? void 0 : prefetch(context));
55
+ return _objectSpread(_objectSpread({}, originResult), result);
56
+ };
57
+ };
58
+
59
+ export const runtime = createRuntime();
60
+ export const {
61
+ createPlugin
62
+ } = runtime;
63
+ export { registerInit, registerPrefetch };
@@ -0,0 +1,2 @@
1
+ import { createContext } from 'react';
2
+ export const RuntimeReactContext = /*#__PURE__*/createContext({});
@@ -1,3 +1,3 @@
1
- import styled from '@modern-js/runtime-core/styled';
1
+ import styled from 'styled-components';
2
2
  export default styled;
3
- export * from '@modern-js/runtime-core/styled';
3
+ export * from 'styled-components';
@@ -1 +1 @@
1
- export { createApp, createPlugin, useLoader, bootstrap, RuntimeReactContext, registerPrefetch, defineConfig, registerInit, useRuntimeContext } from '@modern-js/runtime-core';
1
+ export { createApp, createPlugin, useLoader, bootstrap, RuntimeReactContext, registerPrefetch, defineConfig, registerInit, useRuntimeContext } from "./core";
@@ -7,8 +7,8 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope
7
7
  import React, { useContext } from 'react';
8
8
  import { createBrowserHistory, createHashHistory } from 'history';
9
9
  import { Router, StaticRouter } from 'react-router-dom';
10
- import { RuntimeReactContext } from '@modern-js/runtime-core';
11
10
  import hoistNonReactStatics from 'hoist-non-react-statics';
11
+ import { RuntimeReactContext } from "../../core";
12
12
  import { isBrowser } from "../../common";
13
13
  import { renderRoutes, getLocation, urlJoin } from "./utils";
14
14
  import { jsx as _jsx } from "react/jsx-runtime";