@modern-js/runtime-utils 0.0.0-nightly-20250225160325 → 0.0.0-nightly-20250226085424

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.
@@ -27,12 +27,11 @@ var import_constants = require("@modern-js/utils/universal/constants");
27
27
  var import_react = require("react");
28
28
  var import_react_router_dom = require("react-router-dom");
29
29
  var import_time = require("../time");
30
- const transformNestedRoutes = (routes, reporter) => {
30
+ var import_async_storage = require("../universal/async_storage");
31
+ const transformNestedRoutes = (routes) => {
31
32
  const routeElements = [];
32
33
  for (const route of routes) {
33
- const routeElement = renderNestedRoute(route, {
34
- reporter
35
- });
34
+ const routeElement = renderNestedRoute(route);
36
35
  routeElements.push(routeElement);
37
36
  }
38
37
  return (0, import_react_router_dom.createRoutesFromElements)(routeElements);
@@ -40,12 +39,12 @@ const transformNestedRoutes = (routes, reporter) => {
40
39
  const renderNestedRoute = (nestedRoute, options = {}) => {
41
40
  const { children, index, id, component, isRoot, lazyImport, config, handle } = nestedRoute;
42
41
  const Component = component;
43
- const { parent, props = {}, reporter } = options;
42
+ const { parent, props = {} } = options;
44
43
  const routeProps = {
45
44
  caseSensitive: nestedRoute.caseSensitive,
46
45
  path: nestedRoute.path,
47
46
  id: nestedRoute.id,
48
- loader: createLoader(nestedRoute, reporter),
47
+ loader: createLoader(nestedRoute),
49
48
  action: nestedRoute.action,
50
49
  hasErrorBoundary: nestedRoute.hasErrorBoundary,
51
50
  shouldRevalidate: nestedRoute.shouldRevalidate,
@@ -98,8 +97,7 @@ const renderNestedRoute = (nestedRoute, options = {}) => {
98
97
  }
99
98
  const childElements = children === null || children === void 0 ? void 0 : children.map((childRoute) => {
100
99
  return renderNestedRoute(childRoute, {
101
- parent: nestedRoute,
102
- reporter
100
+ parent: nestedRoute
103
101
  });
104
102
  });
105
103
  const routeElement = index ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Route, {
@@ -112,7 +110,7 @@ const renderNestedRoute = (nestedRoute, options = {}) => {
112
110
  }, id);
113
111
  return routeElement;
114
112
  };
115
- function createLoader(route, reporter) {
113
+ function createLoader(route) {
116
114
  const { loader } = route;
117
115
  if (loader) {
118
116
  return async (args) => {
@@ -122,8 +120,10 @@ function createLoader(route, reporter) {
122
120
  const end = (0, import_time.time)();
123
121
  const res = await loader(args);
124
122
  const cost = end();
125
- if (typeof document === "undefined" && reporter) {
126
- reporter === null || reporter === void 0 ? void 0 : reporter.reportTiming(`${import_constants.LOADER_REPORTER_NAME}-${route.id}`, cost);
123
+ if (typeof document === "undefined") {
124
+ var _storage_useContext_monitors;
125
+ const storage = (0, import_async_storage.getAsyncLocalStorage)();
126
+ storage === null || storage === void 0 ? void 0 : (_storage_useContext_monitors = storage.useContext().monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.timing(`${import_constants.LOADER_REPORTER_NAME}-${route.id}`, cost);
127
127
  }
128
128
  return res;
129
129
  };
@@ -20,10 +20,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var node_exports = {};
21
21
  __export(node_exports, {
22
22
  serializeJson: () => import_serialize.serializeJson,
23
- storage: () => import_storage.storage
23
+ storage: () => import_async_storage.storage
24
24
  });
25
25
  module.exports = __toCommonJS(node_exports);
26
- var import_storage = require("./storage");
26
+ var import_async_storage = require("../universal/async_storage.server");
27
27
  var import_serialize = require("./serialize");
28
28
  __reExport(node_exports, require("./loaderContext"), module.exports);
29
29
  __reExport(node_exports, require("./stream"), module.exports);
@@ -21,8 +21,9 @@ __export(async_storage_exports, {
21
21
  getAsyncLocalStorage: () => getAsyncLocalStorage
22
22
  });
23
23
  module.exports = __toCommonJS(async_storage_exports);
24
- const getAsyncLocalStorage = async () => {
25
- return Promise.resolve(null);
24
+ const getAsyncLocalStorage = () => {
25
+ console.error("You should not get async storage in browser");
26
+ return null;
26
27
  };
27
28
  // Annotate the CommonJS export names for ESM import in node:
28
29
  0 && (module.exports = {
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,17 +17,64 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var async_storage_server_exports = {};
20
30
  __export(async_storage_server_exports, {
21
- getAsyncLocalStorage: () => getAsyncLocalStorage
31
+ getAsyncLocalStorage: () => getAsyncLocalStorage,
32
+ storage: () => storage
22
33
  });
23
34
  module.exports = __toCommonJS(async_storage_server_exports);
24
- var import_storage = require("../node/storage");
25
- const getAsyncLocalStorage = async () => {
26
- return import_storage.storage;
35
+ var ah = __toESM(require("async_hooks"));
36
+ const createStorage = () => {
37
+ let storage2;
38
+ if (typeof ah.AsyncLocalStorage !== "undefined") {
39
+ storage2 = new ah.AsyncLocalStorage();
40
+ }
41
+ const run = (context, cb) => {
42
+ if (!storage2) {
43
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
44
+ `);
45
+ }
46
+ return new Promise((resolve, reject) => {
47
+ storage2.run(context, () => {
48
+ try {
49
+ return resolve(cb());
50
+ } catch (error) {
51
+ return reject(error);
52
+ }
53
+ });
54
+ });
55
+ };
56
+ const useContext = () => {
57
+ if (!storage2) {
58
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
59
+ `);
60
+ }
61
+ const context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
62
+ if (!context) {
63
+ throw new Error(`Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules`);
64
+ }
65
+ return context;
66
+ };
67
+ return {
68
+ run,
69
+ useContext
70
+ };
71
+ };
72
+ const storage = createStorage();
73
+ const getAsyncLocalStorage = () => {
74
+ return storage;
27
75
  };
28
76
  // Annotate the CommonJS export names for ESM import in node:
29
77
  0 && (module.exports = {
30
- getAsyncLocalStorage
78
+ getAsyncLocalStorage,
79
+ storage
31
80
  });
@@ -133,9 +133,9 @@ function cache(fn, options) {
133
133
  tags.forEach((t) => addTagFnRelation(t, fn));
134
134
  return async (...args) => {
135
135
  if (isServer && typeof options === "undefined") {
136
- var _asyncLocalStorage_useContext;
137
- const asyncLocalStorage = await (0, import_async_storage.getAsyncLocalStorage)();
138
- const request = asyncLocalStorage === null || asyncLocalStorage === void 0 ? void 0 : (_asyncLocalStorage_useContext = asyncLocalStorage.useContext()) === null || _asyncLocalStorage_useContext === void 0 ? void 0 : _asyncLocalStorage_useContext.request;
136
+ var _storage_useContext;
137
+ const storage = (0, import_async_storage.getAsyncLocalStorage)();
138
+ const request = storage === null || storage === void 0 ? void 0 : (_storage_useContext = storage.useContext()) === null || _storage_useContext === void 0 ? void 0 : _storage_useContext.request;
139
139
  if (request) {
140
140
  let requestCache = requestCacheMap.get(request);
141
141
  if (!requestCache) {
@@ -169,7 +169,7 @@ function cache(fn, options) {
169
169
  if (age < maxAge) {
170
170
  return cached.data;
171
171
  }
172
- if (revalidate > 0 && age < maxAge + revalidate * 1e3) {
172
+ if (revalidate > 0 && age < maxAge + revalidate) {
173
173
  if (!cached.isRevalidating) {
174
174
  cached.isRevalidating = true;
175
175
  Promise.resolve().then(async () => {
@@ -184,9 +184,9 @@ function cache(fn, options) {
184
184
  } catch (error) {
185
185
  cached.isRevalidating = false;
186
186
  if (isServer) {
187
- var _asyncLocalStorage_useContext_monitors, _asyncLocalStorage_useContext2;
188
- const asyncLocalStorage = await (0, import_async_storage.getAsyncLocalStorage)();
189
- asyncLocalStorage === null || asyncLocalStorage === void 0 ? void 0 : (_asyncLocalStorage_useContext2 = asyncLocalStorage.useContext()) === null || _asyncLocalStorage_useContext2 === void 0 ? void 0 : (_asyncLocalStorage_useContext_monitors = _asyncLocalStorage_useContext2.monitors) === null || _asyncLocalStorage_useContext_monitors === void 0 ? void 0 : _asyncLocalStorage_useContext_monitors.error(error.message);
187
+ var _storage_useContext_monitors, _storage_useContext2;
188
+ const storage = (0, import_async_storage.getAsyncLocalStorage)();
189
+ storage === null || storage === void 0 ? void 0 : (_storage_useContext2 = storage.useContext()) === null || _storage_useContext2 === void 0 ? void 0 : (_storage_useContext_monitors = _storage_useContext2.monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.error(error.message);
190
190
  } else {
191
191
  console.error("Background revalidation failed:", error);
192
192
  }
@@ -205,7 +205,7 @@ function cache(fn, options) {
205
205
  store.set(fn, tagCache);
206
206
  return data;
207
207
  } else {
208
- console.warn("The cache function will not work because it runs on the client and there are no options are provided.");
208
+ console.warn("The cache function will not work because it runs on the browser and there are no options are provided.");
209
209
  return fn(...args);
210
210
  }
211
211
  };
@@ -215,8 +215,8 @@ function withRequestCache(handler) {
215
215
  return handler;
216
216
  }
217
217
  return async (req, ...args) => {
218
- const asyncLocalStorage = await (0, import_async_storage.getAsyncLocalStorage)();
219
- return asyncLocalStorage.run({
218
+ const storage = (0, import_async_storage.getAsyncLocalStorage)();
219
+ return storage.run({
220
220
  request: req
221
221
  }, () => handler(req, ...args));
222
222
  };
@@ -8,15 +8,14 @@ import { LOADER_REPORTER_NAME } from "@modern-js/utils/universal/constants";
8
8
  import { Suspense } from "react";
9
9
  import { Outlet, Route, createRoutesFromElements } from "react-router-dom";
10
10
  import { time } from "../time";
11
- var transformNestedRoutes = function(routes, reporter) {
11
+ import { getAsyncLocalStorage } from "../universal/async_storage";
12
+ var transformNestedRoutes = function(routes) {
12
13
  var routeElements = [];
13
14
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
14
15
  try {
15
16
  for (var _iterator = routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
16
17
  var route = _step.value;
17
- var routeElement = renderNestedRoute(route, {
18
- reporter
19
- });
18
+ var routeElement = renderNestedRoute(route);
20
19
  routeElements.push(routeElement);
21
20
  }
22
21
  } catch (err) {
@@ -39,12 +38,12 @@ var renderNestedRoute = function(nestedRoute) {
39
38
  var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
40
39
  var children = nestedRoute.children, index = nestedRoute.index, id = nestedRoute.id, component = nestedRoute.component, isRoot = nestedRoute.isRoot, lazyImport = nestedRoute.lazyImport, config = nestedRoute.config, handle = nestedRoute.handle;
41
40
  var Component = component;
42
- var parent = options.parent, _options_props = options.props, props = _options_props === void 0 ? {} : _options_props, reporter = options.reporter;
41
+ var parent = options.parent, _options_props = options.props, props = _options_props === void 0 ? {} : _options_props;
43
42
  var routeProps = {
44
43
  caseSensitive: nestedRoute.caseSensitive,
45
44
  path: nestedRoute.path,
46
45
  id: nestedRoute.id,
47
- loader: createLoader(nestedRoute, reporter),
46
+ loader: createLoader(nestedRoute),
48
47
  action: nestedRoute.action,
49
48
  hasErrorBoundary: nestedRoute.hasErrorBoundary,
50
49
  shouldRevalidate: nestedRoute.shouldRevalidate,
@@ -92,8 +91,7 @@ var renderNestedRoute = function(nestedRoute) {
92
91
  }
93
92
  var childElements = children === null || children === void 0 ? void 0 : children.map(function(childRoute) {
94
93
  return renderNestedRoute(childRoute, {
95
- parent: nestedRoute,
96
- reporter
94
+ parent: nestedRoute
97
95
  });
98
96
  });
99
97
  var routeElement = index ? /* @__PURE__ */ _jsx(Route, _object_spread_props(_object_spread({}, routeProps), {
@@ -104,12 +102,12 @@ var renderNestedRoute = function(nestedRoute) {
104
102
  }), id);
105
103
  return routeElement;
106
104
  };
107
- function createLoader(route, reporter) {
105
+ function createLoader(route) {
108
106
  var loader = route.loader;
109
107
  if (loader) {
110
108
  return function() {
111
109
  var _ref = _async_to_generator(function(args) {
112
- var end, res, cost;
110
+ var end, res, cost, _storage_useContext_monitors, storage;
113
111
  return _ts_generator(this, function(_state) {
114
112
  switch (_state.label) {
115
113
  case 0:
@@ -124,8 +122,10 @@ function createLoader(route, reporter) {
124
122
  case 1:
125
123
  res = _state.sent();
126
124
  cost = end();
127
- if (typeof document === "undefined" && reporter) {
128
- reporter === null || reporter === void 0 ? void 0 : reporter.reportTiming("".concat(LOADER_REPORTER_NAME, "-").concat(route.id), cost);
125
+ if (typeof document === "undefined") {
126
+ ;
127
+ storage = getAsyncLocalStorage();
128
+ storage === null || storage === void 0 ? void 0 : (_storage_useContext_monitors = storage.useContext().monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.timing("".concat(LOADER_REPORTER_NAME, "-").concat(route.id), cost);
129
129
  }
130
130
  return [
131
131
  2,
@@ -1,4 +1,4 @@
1
- import { storage } from "./storage";
1
+ import { storage } from "../universal/async_storage.server";
2
2
  import { serializeJson } from "./serialize";
3
3
  export * from "./loaderContext";
4
4
  export * from "./stream";
@@ -1,18 +1,7 @@
1
- import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
- import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
3
1
  var getAsyncLocalStorage = function() {
4
- var _ref = _async_to_generator(function() {
5
- return _ts_generator(this, function(_state) {
6
- return [
7
- 2,
8
- Promise.resolve(null)
9
- ];
10
- });
11
- });
12
- return function getAsyncLocalStorage2() {
13
- return _ref.apply(this, arguments);
14
- };
15
- }();
2
+ console.error("You should not get async storage in browser");
3
+ return null;
4
+ };
16
5
  export {
17
6
  getAsyncLocalStorage
18
7
  };
@@ -1,19 +1,43 @@
1
- import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
- import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
3
- import { storage } from "../node/storage";
4
- var getAsyncLocalStorage = function() {
5
- var _ref = _async_to_generator(function() {
6
- return _ts_generator(this, function(_state) {
7
- return [
8
- 2,
9
- storage
10
- ];
1
+ import * as ah from "async_hooks";
2
+ var createStorage = function() {
3
+ var storage2;
4
+ if (typeof ah.AsyncLocalStorage !== "undefined") {
5
+ storage2 = new ah.AsyncLocalStorage();
6
+ }
7
+ var run = function(context, cb) {
8
+ if (!storage2) {
9
+ throw new Error("Unable to use async_hook, please confirm the node version >= 12.17\n ");
10
+ }
11
+ return new Promise(function(resolve, reject) {
12
+ storage2.run(context, function() {
13
+ try {
14
+ return resolve(cb());
15
+ } catch (error) {
16
+ return reject(error);
17
+ }
18
+ });
11
19
  });
12
- });
13
- return function getAsyncLocalStorage2() {
14
- return _ref.apply(this, arguments);
15
20
  };
16
- }();
21
+ var useContext = function() {
22
+ if (!storage2) {
23
+ throw new Error("Unable to use async_hook, please confirm the node version >= 12.17\n ");
24
+ }
25
+ var context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
26
+ if (!context) {
27
+ throw new Error("Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules");
28
+ }
29
+ return context;
30
+ };
31
+ return {
32
+ run,
33
+ useContext
34
+ };
35
+ };
36
+ var storage = createStorage();
37
+ var getAsyncLocalStorage = function() {
38
+ return storage;
39
+ };
17
40
  export {
18
- getAsyncLocalStorage
41
+ getAsyncLocalStorage,
42
+ storage
19
43
  };
@@ -130,7 +130,7 @@ function cache(fn, options) {
130
130
  return addTagFnRelation(t, fn);
131
131
  });
132
132
  return /* @__PURE__ */ _async_to_generator(function() {
133
- var _len, args, _key, _asyncLocalStorage_useContext, asyncLocalStorage, request, requestCache, key, promise, data, error, tagCache, key1, cached, now, age, data1;
133
+ var _len, args, _key, _storage_useContext, storage, request, requestCache, key, promise, data, error, tagCache, key1, cached, now, age, data1;
134
134
  var _arguments = arguments;
135
135
  return _ts_generator(this, function(_state) {
136
136
  switch (_state.label) {
@@ -141,19 +141,14 @@ function cache(fn, options) {
141
141
  if (!(isServer && typeof options === "undefined"))
142
142
  return [
143
143
  3,
144
- 6
144
+ 5
145
145
  ];
146
- return [
147
- 4,
148
- getAsyncLocalStorage()
149
- ];
150
- case 1:
151
- asyncLocalStorage = _state.sent();
152
- request = asyncLocalStorage === null || asyncLocalStorage === void 0 ? void 0 : (_asyncLocalStorage_useContext = asyncLocalStorage.useContext()) === null || _asyncLocalStorage_useContext === void 0 ? void 0 : _asyncLocalStorage_useContext.request;
146
+ storage = getAsyncLocalStorage();
147
+ request = storage === null || storage === void 0 ? void 0 : (_storage_useContext = storage.useContext()) === null || _storage_useContext === void 0 ? void 0 : _storage_useContext.request;
153
148
  if (!request)
154
149
  return [
155
150
  3,
156
- 5
151
+ 4
157
152
  ];
158
153
  requestCache = requestCacheMap.get(request);
159
154
  if (!requestCache) {
@@ -169,38 +164,38 @@ function cache(fn, options) {
169
164
  }
170
165
  promise = fn.apply(void 0, _to_consumable_array(args));
171
166
  requestCache.set(key, promise);
172
- _state.label = 2;
173
- case 2:
167
+ _state.label = 1;
168
+ case 1:
174
169
  _state.trys.push([
175
- 2,
176
- 4,
170
+ 1,
171
+ 3,
177
172
  ,
178
- 5
173
+ 4
179
174
  ]);
180
175
  return [
181
176
  4,
182
177
  promise
183
178
  ];
184
- case 3:
179
+ case 2:
185
180
  data = _state.sent();
186
181
  return [
187
182
  2,
188
183
  data
189
184
  ];
190
- case 4:
185
+ case 3:
191
186
  error = _state.sent();
192
187
  requestCache.delete(key);
193
188
  throw error;
194
- case 5:
189
+ case 4:
195
190
  return [
196
191
  3,
197
- 9
192
+ 8
198
193
  ];
199
- case 6:
194
+ case 5:
200
195
  if (!(typeof options !== "undefined"))
201
196
  return [
202
197
  3,
203
- 8
198
+ 7
204
199
  ];
205
200
  tagCache = store.get(fn);
206
201
  if (!tagCache) {
@@ -217,11 +212,11 @@ function cache(fn, options) {
217
212
  cached.data
218
213
  ];
219
214
  }
220
- if (revalidate > 0 && age < maxAge + revalidate * 1e3) {
215
+ if (revalidate > 0 && age < maxAge + revalidate) {
221
216
  if (!cached.isRevalidating) {
222
217
  cached.isRevalidating = true;
223
218
  Promise.resolve().then(/* @__PURE__ */ _async_to_generator(function() {
224
- var newData, error2, _asyncLocalStorage_useContext_monitors, _asyncLocalStorage_useContext2, asyncLocalStorage2;
219
+ var newData, error2, _storage_useContext_monitors, _storage_useContext2, storage2;
225
220
  return _ts_generator(this, function(_state2) {
226
221
  switch (_state2.label) {
227
222
  case 0:
@@ -229,7 +224,7 @@ function cache(fn, options) {
229
224
  0,
230
225
  2,
231
226
  ,
232
- 6
227
+ 3
233
228
  ]);
234
229
  return [
235
230
  4,
@@ -245,36 +240,23 @@ function cache(fn, options) {
245
240
  store.set(fn, tagCache);
246
241
  return [
247
242
  3,
248
- 6
243
+ 3
249
244
  ];
250
245
  case 2:
251
246
  error2 = _state2.sent();
252
247
  cached.isRevalidating = false;
253
- if (!isServer)
254
- return [
255
- 3,
256
- 4
257
- ];
258
- return [
259
- 4,
260
- getAsyncLocalStorage()
261
- ];
262
- case 3:
263
- asyncLocalStorage2 = _state2.sent();
264
- asyncLocalStorage2 === null || asyncLocalStorage2 === void 0 ? void 0 : (_asyncLocalStorage_useContext2 = asyncLocalStorage2.useContext()) === null || _asyncLocalStorage_useContext2 === void 0 ? void 0 : (_asyncLocalStorage_useContext_monitors = _asyncLocalStorage_useContext2.monitors) === null || _asyncLocalStorage_useContext_monitors === void 0 ? void 0 : _asyncLocalStorage_useContext_monitors.error(error2.message);
265
- return [
266
- 3,
267
- 5
268
- ];
269
- case 4:
270
- console.error("Background revalidation failed:", error2);
271
- _state2.label = 5;
272
- case 5:
248
+ if (isServer) {
249
+ ;
250
+ storage2 = getAsyncLocalStorage();
251
+ storage2 === null || storage2 === void 0 ? void 0 : (_storage_useContext2 = storage2.useContext()) === null || _storage_useContext2 === void 0 ? void 0 : (_storage_useContext_monitors = _storage_useContext2.monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.error(error2.message);
252
+ } else {
253
+ console.error("Background revalidation failed:", error2);
254
+ }
273
255
  return [
274
256
  3,
275
- 6
257
+ 3
276
258
  ];
277
- case 6:
259
+ case 3:
278
260
  return [
279
261
  2
280
262
  ];
@@ -292,7 +274,7 @@ function cache(fn, options) {
292
274
  4,
293
275
  fn.apply(void 0, _to_consumable_array(args))
294
276
  ];
295
- case 7:
277
+ case 6:
296
278
  data1 = _state.sent();
297
279
  tagCache.set(key1, {
298
280
  data: data1,
@@ -304,13 +286,13 @@ function cache(fn, options) {
304
286
  2,
305
287
  data1
306
288
  ];
307
- case 8:
308
- console.warn("The cache function will not work because it runs on the client and there are no options are provided.");
289
+ case 7:
290
+ console.warn("The cache function will not work because it runs on the browser and there are no options are provided.");
309
291
  return [
310
292
  2,
311
293
  fn.apply(void 0, _to_consumable_array(args))
312
294
  ];
313
- case 9:
295
+ case 8:
314
296
  return [
315
297
  2
316
298
  ];
@@ -324,31 +306,23 @@ function withRequestCache(handler) {
324
306
  }
325
307
  return function() {
326
308
  var _ref = _async_to_generator(function(req) {
327
- var _len, args, _key, asyncLocalStorage;
309
+ var _len, args, _key, storage;
328
310
  var _arguments = arguments;
329
311
  return _ts_generator(this, function(_state) {
330
- switch (_state.label) {
331
- case 0:
332
- for (_len = _arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
333
- args[_key - 1] = _arguments[_key];
334
- }
335
- return [
336
- 4,
337
- getAsyncLocalStorage()
338
- ];
339
- case 1:
340
- asyncLocalStorage = _state.sent();
341
- return [
342
- 2,
343
- asyncLocalStorage.run({
344
- request: req
345
- }, function() {
346
- return handler.apply(void 0, [
347
- req
348
- ].concat(_to_consumable_array(args)));
349
- })
350
- ];
312
+ for (_len = _arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
313
+ args[_key - 1] = _arguments[_key];
351
314
  }
315
+ storage = getAsyncLocalStorage();
316
+ return [
317
+ 2,
318
+ storage.run({
319
+ request: req
320
+ }, function() {
321
+ return handler.apply(void 0, [
322
+ req
323
+ ].concat(_to_consumable_array(args)));
324
+ })
325
+ ];
352
326
  });
353
327
  });
354
328
  return function(req) {
@@ -3,12 +3,11 @@ import { LOADER_REPORTER_NAME } from "@modern-js/utils/universal/constants";
3
3
  import { Suspense } from "react";
4
4
  import { Outlet, Route, createRoutesFromElements } from "react-router-dom";
5
5
  import { time } from "../time";
6
- const transformNestedRoutes = (routes, reporter) => {
6
+ import { getAsyncLocalStorage } from "../universal/async_storage";
7
+ const transformNestedRoutes = (routes) => {
7
8
  const routeElements = [];
8
9
  for (const route of routes) {
9
- const routeElement = renderNestedRoute(route, {
10
- reporter
11
- });
10
+ const routeElement = renderNestedRoute(route);
12
11
  routeElements.push(routeElement);
13
12
  }
14
13
  return createRoutesFromElements(routeElements);
@@ -16,12 +15,12 @@ const transformNestedRoutes = (routes, reporter) => {
16
15
  const renderNestedRoute = (nestedRoute, options = {}) => {
17
16
  const { children, index, id, component, isRoot, lazyImport, config, handle } = nestedRoute;
18
17
  const Component = component;
19
- const { parent, props = {}, reporter } = options;
18
+ const { parent, props = {} } = options;
20
19
  const routeProps = {
21
20
  caseSensitive: nestedRoute.caseSensitive,
22
21
  path: nestedRoute.path,
23
22
  id: nestedRoute.id,
24
- loader: createLoader(nestedRoute, reporter),
23
+ loader: createLoader(nestedRoute),
25
24
  action: nestedRoute.action,
26
25
  hasErrorBoundary: nestedRoute.hasErrorBoundary,
27
26
  shouldRevalidate: nestedRoute.shouldRevalidate,
@@ -74,8 +73,7 @@ const renderNestedRoute = (nestedRoute, options = {}) => {
74
73
  }
75
74
  const childElements = children === null || children === void 0 ? void 0 : children.map((childRoute) => {
76
75
  return renderNestedRoute(childRoute, {
77
- parent: nestedRoute,
78
- reporter
76
+ parent: nestedRoute
79
77
  });
80
78
  });
81
79
  const routeElement = index ? /* @__PURE__ */ _jsx(Route, {
@@ -88,7 +86,7 @@ const renderNestedRoute = (nestedRoute, options = {}) => {
88
86
  }, id);
89
87
  return routeElement;
90
88
  };
91
- function createLoader(route, reporter) {
89
+ function createLoader(route) {
92
90
  const { loader } = route;
93
91
  if (loader) {
94
92
  return async (args) => {
@@ -98,8 +96,10 @@ function createLoader(route, reporter) {
98
96
  const end = time();
99
97
  const res = await loader(args);
100
98
  const cost = end();
101
- if (typeof document === "undefined" && reporter) {
102
- reporter === null || reporter === void 0 ? void 0 : reporter.reportTiming(`${LOADER_REPORTER_NAME}-${route.id}`, cost);
99
+ if (typeof document === "undefined") {
100
+ var _storage_useContext_monitors;
101
+ const storage = getAsyncLocalStorage();
102
+ storage === null || storage === void 0 ? void 0 : (_storage_useContext_monitors = storage.useContext().monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.timing(`${LOADER_REPORTER_NAME}-${route.id}`, cost);
103
103
  }
104
104
  return res;
105
105
  };
@@ -1,4 +1,4 @@
1
- import { storage } from "./storage";
1
+ import { storage } from "../universal/async_storage.server";
2
2
  import { serializeJson } from "./serialize";
3
3
  export * from "./loaderContext";
4
4
  export * from "./stream";
@@ -1,5 +1,6 @@
1
- const getAsyncLocalStorage = async () => {
2
- return Promise.resolve(null);
1
+ const getAsyncLocalStorage = () => {
2
+ console.error("You should not get async storage in browser");
3
+ return null;
3
4
  };
4
5
  export {
5
6
  getAsyncLocalStorage
@@ -1,7 +1,45 @@
1
- import { storage } from "../node/storage";
2
- const getAsyncLocalStorage = async () => {
1
+ import * as ah from "async_hooks";
2
+ const createStorage = () => {
3
+ let storage2;
4
+ if (typeof ah.AsyncLocalStorage !== "undefined") {
5
+ storage2 = new ah.AsyncLocalStorage();
6
+ }
7
+ const run = (context, cb) => {
8
+ if (!storage2) {
9
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
10
+ `);
11
+ }
12
+ return new Promise((resolve, reject) => {
13
+ storage2.run(context, () => {
14
+ try {
15
+ return resolve(cb());
16
+ } catch (error) {
17
+ return reject(error);
18
+ }
19
+ });
20
+ });
21
+ };
22
+ const useContext = () => {
23
+ if (!storage2) {
24
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
25
+ `);
26
+ }
27
+ const context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
28
+ if (!context) {
29
+ throw new Error(`Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules`);
30
+ }
31
+ return context;
32
+ };
33
+ return {
34
+ run,
35
+ useContext
36
+ };
37
+ };
38
+ const storage = createStorage();
39
+ const getAsyncLocalStorage = () => {
3
40
  return storage;
4
41
  };
5
42
  export {
6
- getAsyncLocalStorage
43
+ getAsyncLocalStorage,
44
+ storage
7
45
  };
@@ -103,9 +103,9 @@ function cache(fn, options) {
103
103
  tags.forEach((t) => addTagFnRelation(t, fn));
104
104
  return async (...args) => {
105
105
  if (isServer && typeof options === "undefined") {
106
- var _asyncLocalStorage_useContext;
107
- const asyncLocalStorage = await getAsyncLocalStorage();
108
- const request = asyncLocalStorage === null || asyncLocalStorage === void 0 ? void 0 : (_asyncLocalStorage_useContext = asyncLocalStorage.useContext()) === null || _asyncLocalStorage_useContext === void 0 ? void 0 : _asyncLocalStorage_useContext.request;
106
+ var _storage_useContext;
107
+ const storage = getAsyncLocalStorage();
108
+ const request = storage === null || storage === void 0 ? void 0 : (_storage_useContext = storage.useContext()) === null || _storage_useContext === void 0 ? void 0 : _storage_useContext.request;
109
109
  if (request) {
110
110
  let requestCache = requestCacheMap.get(request);
111
111
  if (!requestCache) {
@@ -139,7 +139,7 @@ function cache(fn, options) {
139
139
  if (age < maxAge) {
140
140
  return cached.data;
141
141
  }
142
- if (revalidate > 0 && age < maxAge + revalidate * 1e3) {
142
+ if (revalidate > 0 && age < maxAge + revalidate) {
143
143
  if (!cached.isRevalidating) {
144
144
  cached.isRevalidating = true;
145
145
  Promise.resolve().then(async () => {
@@ -154,9 +154,9 @@ function cache(fn, options) {
154
154
  } catch (error) {
155
155
  cached.isRevalidating = false;
156
156
  if (isServer) {
157
- var _asyncLocalStorage_useContext_monitors, _asyncLocalStorage_useContext2;
158
- const asyncLocalStorage = await getAsyncLocalStorage();
159
- asyncLocalStorage === null || asyncLocalStorage === void 0 ? void 0 : (_asyncLocalStorage_useContext2 = asyncLocalStorage.useContext()) === null || _asyncLocalStorage_useContext2 === void 0 ? void 0 : (_asyncLocalStorage_useContext_monitors = _asyncLocalStorage_useContext2.monitors) === null || _asyncLocalStorage_useContext_monitors === void 0 ? void 0 : _asyncLocalStorage_useContext_monitors.error(error.message);
157
+ var _storage_useContext_monitors, _storage_useContext2;
158
+ const storage = getAsyncLocalStorage();
159
+ storage === null || storage === void 0 ? void 0 : (_storage_useContext2 = storage.useContext()) === null || _storage_useContext2 === void 0 ? void 0 : (_storage_useContext_monitors = _storage_useContext2.monitors) === null || _storage_useContext_monitors === void 0 ? void 0 : _storage_useContext_monitors.error(error.message);
160
160
  } else {
161
161
  console.error("Background revalidation failed:", error);
162
162
  }
@@ -175,7 +175,7 @@ function cache(fn, options) {
175
175
  store.set(fn, tagCache);
176
176
  return data;
177
177
  } else {
178
- console.warn("The cache function will not work because it runs on the client and there are no options are provided.");
178
+ console.warn("The cache function will not work because it runs on the browser and there are no options are provided.");
179
179
  return fn(...args);
180
180
  }
181
181
  };
@@ -185,8 +185,8 @@ function withRequestCache(handler) {
185
185
  return handler;
186
186
  }
187
187
  return async (req, ...args) => {
188
- const asyncLocalStorage = await getAsyncLocalStorage();
189
- return asyncLocalStorage.run({
188
+ const storage = getAsyncLocalStorage();
189
+ return storage.run({
190
190
  request: req
191
191
  }, () => handler(req, ...args));
192
192
  };
@@ -1,6 +1,6 @@
1
1
  /// <reference types="react" />
2
- import type { NestedRoute, Reporter } from '@modern-js/types';
3
- export declare const transformNestedRoutes: (routes: NestedRoute[], reporter?: Reporter) => import("react-router-dom").RouteObject[];
2
+ import type { NestedRoute } from '@modern-js/types';
3
+ export declare const transformNestedRoutes: (routes: NestedRoute[]) => import("react-router-dom").RouteObject[];
4
4
  type DeferredDataComponentType = (props?: {
5
5
  nonce?: string;
6
6
  }) => JSX.Element | null;
@@ -8,6 +8,5 @@ export declare const renderNestedRoute: (nestedRoute: NestedRoute, options?: {
8
8
  parent?: NestedRoute;
9
9
  DeferredDataComponent?: DeferredDataComponentType;
10
10
  props?: Record<string, any>;
11
- reporter?: Reporter;
12
11
  }) => import("react/jsx-runtime").JSX.Element;
13
12
  export {};
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * ssr helpers
3
3
  */
4
- export { storage } from './storage';
4
+ export { storage } from '../universal/async_storage.server';
5
5
  export { serializeJson } from './serialize';
6
6
  export * from './loaderContext';
7
7
  export * from './stream';
@@ -1,3 +1,2 @@
1
- import type { ModernServerContext, ServerRoute } from '@modern-js/types';
2
- export type ServerContext = Pick<ModernServerContext, 'logger' | 'req' | 'reporter' | 'res' | 'params' | 'headers' | 'method' | 'url' | 'host' | 'protocol' | 'origin' | 'href' | 'path' | 'query'>;
1
+ import type { ServerRoute } from '@modern-js/types';
3
2
  export declare const matchEntry: (pathname: string, entries: ServerRoute[]) => ServerRoute | undefined;
@@ -1,2 +1,2 @@
1
- import type { storage } from '../node/storage';
2
- export declare const getAsyncLocalStorage: () => Promise<typeof storage | null>;
1
+ import type { Storage } from './async_storage.server';
2
+ export declare const getAsyncLocalStorage: () => Storage | null;
@@ -1,2 +1,18 @@
1
- import { storage } from '../node/storage';
2
- export declare const getAsyncLocalStorage: () => Promise<typeof storage | null>;
1
+ /// <reference types="node" />
2
+ import type { IncomingHttpHeaders } from 'http';
3
+ import type { Monitors } from '@modern-js/types';
4
+ declare const storage: {
5
+ run: <O>(context: {
6
+ monitors?: Monitors | undefined;
7
+ headers?: IncomingHttpHeaders | undefined;
8
+ request?: Request | undefined;
9
+ }, cb: () => O | Promise<O>) => Promise<O>;
10
+ useContext: () => {
11
+ monitors?: Monitors | undefined;
12
+ headers?: IncomingHttpHeaders | undefined;
13
+ request?: Request | undefined;
14
+ };
15
+ };
16
+ type Storage = typeof storage;
17
+ export { storage, type Storage };
18
+ export declare const getAsyncLocalStorage: () => Storage;
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "modern",
16
16
  "modern.js"
17
17
  ],
18
- "version": "0.0.0-nightly-20250225160325",
18
+ "version": "0.0.0-nightly-20250226085424",
19
19
  "_comment": "Provide ESM and CJS exports, ESM is used by runtime package, for treeshaking",
20
20
  "exports": {
21
21
  "./router": {
@@ -146,8 +146,8 @@
146
146
  "lru-cache": "^11.0.2",
147
147
  "react-router-dom": "6.27.0",
148
148
  "serialize-javascript": "^6.0.0",
149
- "@modern-js/types": "0.0.0-nightly-20250225160325",
150
- "@modern-js/utils": "0.0.0-nightly-20250225160325"
149
+ "@modern-js/types": "0.0.0-nightly-20250226085424",
150
+ "@modern-js/utils": "0.0.0-nightly-20250226085424"
151
151
  },
152
152
  "peerDependencies": {
153
153
  "react": ">=17.0.0",
@@ -169,8 +169,8 @@
169
169
  "react": "^18.3.1",
170
170
  "react-dom": "^18.3.1",
171
171
  "typescript": "^5",
172
- "@scripts/build": "0.0.0-nightly-20250225160325",
173
- "@scripts/jest-config": "0.0.0-nightly-20250225160325"
172
+ "@scripts/build": "0.0.0-nightly-20250226085424",
173
+ "@scripts/jest-config": "0.0.0-nightly-20250226085424"
174
174
  },
175
175
  "sideEffects": false,
176
176
  "scripts": {
@@ -1,75 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var storage_exports = {};
30
- __export(storage_exports, {
31
- storage: () => storage
32
- });
33
- module.exports = __toCommonJS(storage_exports);
34
- var ah = __toESM(require("async_hooks"));
35
- const createStorage = () => {
36
- let storage2;
37
- if (typeof ah.AsyncLocalStorage !== "undefined") {
38
- storage2 = new ah.AsyncLocalStorage();
39
- }
40
- const run = (context, cb) => {
41
- if (!storage2) {
42
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
43
- `);
44
- }
45
- return new Promise((resolve, reject) => {
46
- storage2.run(context, () => {
47
- try {
48
- return resolve(cb());
49
- } catch (error) {
50
- return reject(error);
51
- }
52
- });
53
- });
54
- };
55
- const useContext = () => {
56
- if (!storage2) {
57
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
58
- `);
59
- }
60
- const context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
61
- if (!context) {
62
- throw new Error(`Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules`);
63
- }
64
- return context;
65
- };
66
- return {
67
- run,
68
- useContext
69
- };
70
- };
71
- const storage = createStorage();
72
- // Annotate the CommonJS export names for ESM import in node:
73
- 0 && (module.exports = {
74
- storage
75
- });
@@ -1,39 +0,0 @@
1
- import * as ah from "async_hooks";
2
- var createStorage = function() {
3
- var storage2;
4
- if (typeof ah.AsyncLocalStorage !== "undefined") {
5
- storage2 = new ah.AsyncLocalStorage();
6
- }
7
- var run = function(context, cb) {
8
- if (!storage2) {
9
- throw new Error("Unable to use async_hook, please confirm the node version >= 12.17\n ");
10
- }
11
- return new Promise(function(resolve, reject) {
12
- storage2.run(context, function() {
13
- try {
14
- return resolve(cb());
15
- } catch (error) {
16
- return reject(error);
17
- }
18
- });
19
- });
20
- };
21
- var useContext = function() {
22
- if (!storage2) {
23
- throw new Error("Unable to use async_hook, please confirm the node version >= 12.17\n ");
24
- }
25
- var context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
26
- if (!context) {
27
- throw new Error("Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules");
28
- }
29
- return context;
30
- };
31
- return {
32
- run,
33
- useContext
34
- };
35
- };
36
- var storage = createStorage();
37
- export {
38
- storage
39
- };
@@ -1,41 +0,0 @@
1
- import * as ah from "async_hooks";
2
- const createStorage = () => {
3
- let storage2;
4
- if (typeof ah.AsyncLocalStorage !== "undefined") {
5
- storage2 = new ah.AsyncLocalStorage();
6
- }
7
- const run = (context, cb) => {
8
- if (!storage2) {
9
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
10
- `);
11
- }
12
- return new Promise((resolve, reject) => {
13
- storage2.run(context, () => {
14
- try {
15
- return resolve(cb());
16
- } catch (error) {
17
- return reject(error);
18
- }
19
- });
20
- });
21
- };
22
- const useContext = () => {
23
- if (!storage2) {
24
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
25
- `);
26
- }
27
- const context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore();
28
- if (!context) {
29
- throw new Error(`Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules`);
30
- }
31
- return context;
32
- };
33
- return {
34
- run,
35
- useContext
36
- };
37
- };
38
- const storage = createStorage();
39
- export {
40
- storage
41
- };
@@ -1,16 +0,0 @@
1
- /// <reference types="node" />
2
- import type { IncomingHttpHeaders } from 'http';
3
- import type { Monitors } from '@modern-js/types';
4
- declare const storage: {
5
- run: <O>(context: {
6
- headers?: IncomingHttpHeaders | undefined;
7
- monitors?: Monitors | undefined;
8
- request?: Request | undefined;
9
- }, cb: () => O | Promise<O>) => Promise<O>;
10
- useContext: () => {
11
- headers?: IncomingHttpHeaders | undefined;
12
- monitors?: Monitors | undefined;
13
- request?: Request | undefined;
14
- };
15
- };
16
- export { storage };