remote-components 0.0.33 → 0.0.35

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 (77) hide show
  1. package/dist/{component-loader-28ad0083.d.ts → component-loader-8951c052.d.ts} +6 -4
  2. package/dist/html/host.cjs +353 -129
  3. package/dist/html/host.cjs.map +1 -1
  4. package/dist/html/host.js +353 -129
  5. package/dist/html/host.js.map +1 -1
  6. package/dist/html/remote.cjs +199 -0
  7. package/dist/html/remote.cjs.map +1 -0
  8. package/dist/html/remote.d.ts +2 -0
  9. package/dist/html/remote.js +198 -0
  10. package/dist/html/remote.js.map +1 -0
  11. package/dist/internal/next/host/app-router-client.cjs +60 -19
  12. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  13. package/dist/internal/next/host/app-router-client.d.ts +3 -3
  14. package/dist/internal/next/host/app-router-client.js +65 -23
  15. package/dist/internal/next/host/app-router-client.js.map +1 -1
  16. package/dist/internal/next/host/app-router-compat.cjs.map +1 -1
  17. package/dist/internal/next/host/app-router-compat.d.ts +1 -1
  18. package/dist/internal/next/host/app-router-compat.js.map +1 -1
  19. package/dist/internal/next/remote/render-server.cjs +1 -1
  20. package/dist/internal/next/remote/render-server.cjs.map +1 -1
  21. package/dist/internal/next/remote/render-server.js +1 -1
  22. package/dist/internal/next/remote/render-server.js.map +1 -1
  23. package/dist/internal/shared/client/polyfill.cjs.map +1 -1
  24. package/dist/internal/shared/client/polyfill.js.map +1 -1
  25. package/dist/internal/shared/client/remote-component.cjs +237 -133
  26. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  27. package/dist/internal/shared/client/remote-component.d.ts +29 -22
  28. package/dist/internal/shared/client/remote-component.js +235 -133
  29. package/dist/internal/shared/client/remote-component.js.map +1 -1
  30. package/dist/internal/shared/error.cjs +1 -1
  31. package/dist/internal/shared/error.cjs.map +1 -1
  32. package/dist/internal/shared/error.d.ts +1 -1
  33. package/dist/internal/shared/error.js +1 -1
  34. package/dist/internal/shared/error.js.map +1 -1
  35. package/dist/internal/shared/ssr/dom-flight.cjs +24 -8
  36. package/dist/internal/shared/ssr/dom-flight.cjs.map +1 -1
  37. package/dist/internal/shared/ssr/dom-flight.d.ts +1 -1
  38. package/dist/internal/shared/ssr/dom-flight.js +24 -8
  39. package/dist/internal/shared/ssr/dom-flight.js.map +1 -1
  40. package/dist/internal/shared/ssr/fetch-remote-component.cjs +8 -4
  41. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  42. package/dist/internal/shared/ssr/fetch-remote-component.d.ts +2 -1
  43. package/dist/internal/shared/ssr/fetch-remote-component.js +9 -5
  44. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  45. package/dist/next/config.cjs +100 -86
  46. package/dist/next/config.cjs.map +1 -1
  47. package/dist/next/config.js +100 -86
  48. package/dist/next/config.js.map +1 -1
  49. package/dist/next/host/app-router-server.cjs +1 -0
  50. package/dist/next/host/app-router-server.cjs.map +1 -1
  51. package/dist/next/host/app-router-server.js +2 -1
  52. package/dist/next/host/app-router-server.js.map +1 -1
  53. package/dist/next/host/client/index.cjs +1381 -1187
  54. package/dist/next/host/client/index.cjs.map +1 -1
  55. package/dist/next/host/client/index.d.ts +1 -1
  56. package/dist/next/host/client/index.js +682 -490
  57. package/dist/next/host/client/index.js.map +1 -1
  58. package/dist/next/host/pages-router-server.cjs +4 -4
  59. package/dist/next/host/pages-router-server.cjs.map +1 -1
  60. package/dist/next/host/pages-router-server.js +4 -4
  61. package/dist/next/host/pages-router-server.js.map +1 -1
  62. package/dist/next/{middleware.cjs → proxy.cjs} +24 -14
  63. package/dist/next/proxy.cjs.map +1 -0
  64. package/dist/next/proxy.d.ts +29 -0
  65. package/dist/next/{middleware.js → proxy.js} +21 -11
  66. package/dist/next/proxy.js.map +1 -0
  67. package/dist/react/index.cjs +201 -107
  68. package/dist/react/index.cjs.map +1 -1
  69. package/dist/react/index.d.ts +2 -2
  70. package/dist/react/index.js +206 -112
  71. package/dist/react/index.js.map +1 -1
  72. package/dist/{types-7c207455.d.ts → types-4e7dea94.d.ts} +2 -1
  73. package/dist/{types-e4a3fa37.d.ts → types-cbf6c34f.d.ts} +2 -2
  74. package/package.json +22 -9
  75. package/dist/next/middleware.cjs.map +0 -1
  76. package/dist/next/middleware.d.ts +0 -29
  77. package/dist/next/middleware.js.map +0 -1
@@ -40,1187 +40,1287 @@ var Image = __toESM(require("next/image"), 1);
40
40
  var import_react = require("react");
41
41
  var import_react_dom = require("react-dom");
42
42
 
43
- // src/shared/client/component-loader.ts
44
- var React = __toESM(require("react"), 1);
45
- var ReactDOM = __toESM(require("react-dom"), 1);
46
- var ReactDOMClient = __toESM(require("react-dom/client"), 1);
47
- var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
48
- var JSXRuntime = __toESM(require("react/jsx-runtime"), 1);
49
-
50
- // src/shared/webpack/shared-modules.ts
51
- function applySharedModules(bundle, resolve) {
52
- const self = globalThis;
53
- if (self.__remote_webpack_require__?.[bundle]) {
54
- const modulePaths = Object.keys(
55
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
43
+ // src/shared/client/apply-origin.ts
44
+ var tagNames = [
45
+ "img",
46
+ "source",
47
+ "video",
48
+ "audio",
49
+ "track",
50
+ "iframe",
51
+ "embed",
52
+ "script",
53
+ "link"
54
+ ];
55
+ function applyOriginToNodes(doc, url) {
56
+ if (url.origin !== location.origin) {
57
+ const nodes = doc.querySelectorAll(
58
+ tagNames.map(
59
+ (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
60
+ ).join(",")
56
61
  );
57
- for (const [key, value] of Object.entries(resolve)) {
58
- let ids = modulePaths.filter((p) => p === key);
59
- if (ids.length === 0) {
60
- ids = modulePaths.filter((p) => p.includes(key));
62
+ nodes.forEach((node) => {
63
+ if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
64
+ node.src = new URL(node.getAttribute("src") ?? "/", url).href;
61
65
  }
62
- for (let id of ids) {
63
- const webpackBundle = self.__remote_webpack_require__[bundle];
64
- if (webpackBundle.m) {
65
- if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {
66
- id = `${self.__remote_webpack_module_map__[bundle][id]}`;
67
- }
68
- webpackBundle.m[id] = (module2) => {
69
- module2.exports = value;
70
- };
66
+ if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
67
+ node.setAttribute(
68
+ "href",
69
+ new URL(node.getAttribute("href") ?? "/", url).href
70
+ );
71
+ }
72
+ if (node.hasAttribute("srcset")) {
73
+ const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
74
+ const [urlPart, descriptor] = entry.trim().split(/\s+/);
75
+ if (!urlPart)
76
+ return entry;
77
+ const absoluteUrl = new URL(urlPart, url).href;
78
+ return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
79
+ }).join(", ");
80
+ if (srcSet) {
81
+ node.setAttribute("srcset", srcSet);
71
82
  }
72
83
  }
73
- }
74
- }
75
- }
76
-
77
- // src/shared/error.ts
78
- var RemoteComponentsError = class extends Error {
79
- constructor(message, options) {
80
- super(message, options);
81
- this.code = "REMOTE_COMPONENTS_ERROR";
82
- this.name = "RemoteComponentsError";
83
- }
84
- };
85
- function multipleRemoteComponentsError(url) {
86
- return new Error(
87
- `Multiple Remote Components found at "${url}". When a page exposes multiple Remote Components you must specify the "name" prop to select which one to load.`
88
- );
89
- }
90
- function failedToFetchRemoteComponentError(url, error) {
91
- return new RemoteComponentsError(
92
- `Failed to fetch Remote Component from "${url}". Is the URL correct and accessible?`,
93
- { cause: error instanceof Error ? error : new Error(String(error)) }
94
- );
95
- }
96
-
97
- // src/shared/webpack/next-client-pages-loader.ts
98
- function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
99
- const self = globalThis;
100
- const nextCssOriginal = document.querySelector(
101
- `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
102
- );
103
- if (nextCssOriginal) {
104
- nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
105
- }
106
- const nextCss = document.createElement("noscript");
107
- nextCss.id = "__next_css__DO_NOT_USE__";
108
- nextCss.setAttribute("data-bundle", bundle);
109
- nextCss.setAttribute("data-route", route);
110
- const nextCssEnd = document.createElement("noscript");
111
- nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
112
- nextCssEnd.setAttribute("data-bundle", bundle);
113
- nextCssEnd.setAttribute("data-route", route);
114
- document.head.appendChild(nextCssEnd);
115
- document.head.appendChild(nextCss);
116
- const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
117
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
118
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
119
- (key) => key.includes("/next/dist/client/page-loader.js")
120
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
121
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
122
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
123
- (key) => key.includes("/next/dist/client/page-loader.js")
124
- ) ?? ""] ?? -1;
125
- const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
126
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
127
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
128
- (key) => key.includes("/next/dist/client/page-loader.js")
129
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
130
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
131
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
132
- (key) => key.includes("/next/dist/client/page-loader.js")
133
- ) ?? ""] ?? -1;
134
- if (!(componentLoaderChunk && appLoaderChunk)) {
135
- throw new RemoteComponentsError(
136
- `Next.js client pages loader not found in bundle "${bundle}".`
137
- );
138
- }
139
- const __NEXT_P_ORIGINAL = self.__NEXT_P;
140
- const selfOriginal = self;
141
- delete selfOriginal.__NEXT_P;
142
- self.__remote_webpack_require__?.[bundle]?.(
143
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
144
- );
145
- if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
146
- self.__remote_webpack_require__?.[bundle]?.(
147
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
148
- );
149
- }
150
- if (self.__NEXT_P) {
151
- const [, componentLoader] = self.__NEXT_P[0] ?? [
152
- void 0,
153
- () => ({ default: null })
154
- ];
155
- const [, appLoader] = self.__NEXT_P[2] ?? [
156
- void 0,
157
- () => ({
158
- default: null
159
- })
160
- ];
161
- const { default: Component } = componentLoader();
162
- const { default: App } = appLoader();
163
- if (!self.__remote_next_css__) {
164
- self.__remote_next_css__ = {};
165
- }
166
- if (!self.__remote_next_css__[bundle]) {
167
- const cssRE = /\.s?css$/;
168
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
169
- self.__remote_webpack_require__?.[bundle]?.(id);
170
- });
171
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
172
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
173
- if (id) {
174
- self.__remote_webpack_require__?.[bundle]?.(id);
84
+ if (node.hasAttribute("imagesrcset")) {
85
+ const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
86
+ const [urlPart, descriptor] = entry.trim().split(/\s+/);
87
+ if (!urlPart)
88
+ return entry;
89
+ const absoluteUrl = new URL(urlPart, url).href;
90
+ return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
91
+ }).join(", ");
92
+ if (srcSet) {
93
+ node.setAttribute("imagesrcset", srcSet);
175
94
  }
176
- });
177
- const elements = [];
178
- let node = nextCss.previousSibling;
179
- while (node && node !== nextCssEnd) {
180
- elements.push(node);
181
- node.remove();
182
- node = nextCss.previousSibling;
183
95
  }
184
- self.__remote_next_css__[bundle] = elements;
185
- }
186
- if (styleContainer) {
187
- const elements = self.__remote_next_css__[bundle];
188
- elements.forEach((el) => {
189
- styleContainer.appendChild(el.cloneNode(true));
190
- });
191
- } else {
192
- const elements = self.__remote_next_css__[bundle];
193
- elements.forEach((el) => {
194
- document.head.appendChild(el);
195
- });
196
- }
197
- delete self.__NEXT_P;
198
- self.__NEXT_P = __NEXT_P_ORIGINAL;
199
- if (nextCssOriginal) {
200
- nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
201
- }
202
- nextCss.remove();
203
- nextCssEnd.remove();
204
- return { Component, App };
96
+ });
205
97
  }
206
- return { Component: null, App: null };
207
- }
208
-
209
- // src/shared/utils/index.ts
210
- function escapeString(str) {
211
- return str.replace(/[^a-z0-9]/g, "_");
212
- }
213
- var attrToProp = {
214
- fetchpriority: "fetchPriority",
215
- crossorigin: "crossOrigin",
216
- imagesrcset: "imageSrcSet",
217
- imagesizes: "imageSizes",
218
- srcset: "srcSet"
219
- };
220
-
221
- // src/shared/client/const.ts
222
- var DEFAULT_ROUTE = "/";
223
- var RUNTIME_WEBPACK = "webpack";
224
- var RUNTIME_TURBOPACK = "turbopack";
225
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
226
- function getBundleKey(bundle) {
227
- return escapeString(bundle);
228
98
  }
229
99
 
230
- // src/shared/client/webpack-adapter.ts
231
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}) {
100
+ // src/shared/client/polyfill.tsx
101
+ var import_jsx_runtime = (
102
+ // eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text
103
+ require("react/jsx-runtime")
104
+ );
105
+ function applyBundleUrlToSrc(bundle, src) {
232
106
  const self = globalThis;
233
- if (!self.__remote_bundle_url__) {
234
- self.__remote_bundle_url__ = {};
107
+ if (self.__remote_bundle_url__?.[bundle]?.origin === location.origin) {
108
+ return src;
235
109
  }
236
- self.__remote_bundle_url__[bundle ?? "default"] = url;
237
- self.__webpack_get_script_filename__ = () => null;
238
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
239
- if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
240
- self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
241
- self.__original_webpack_require__ = self.__webpack_require__;
242
- }
243
- self.__webpack_chunk_load__ = createChunkLoader(runtime);
244
- self.__webpack_require__ = createModuleRequire(runtime);
245
- self.__webpack_require_type__ = runtime;
246
- if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
247
- const remoteBundle = bundle ?? "default";
248
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
249
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
250
- }
110
+ const { assetPrefix, path } = /^(?<assetPrefix>.*?)\/_next\/(?<path>.*)/.exec(src)?.groups ?? {};
111
+ if (!path) {
112
+ return new URL(src, self.__remote_bundle_url__?.[bundle]?.origin).href;
251
113
  }
252
- if (runtime === RUNTIME_TURBOPACK) {
253
- await Promise.all(
254
- scripts.map((script) => {
255
- if (script.src) {
256
- return self.__webpack_chunk_load__?.(script.src, bundle);
257
- }
258
- return Promise.resolve(void 0);
259
- })
260
- );
114
+ return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ""}${assetPrefix}/_next/${path}`;
115
+ }
116
+ function applyBundleUrlToImagePropsSrc(bundle, src) {
117
+ if (typeof src === "string") {
118
+ return applyBundleUrlToSrc(bundle, src);
261
119
  }
262
- await initializeSharedModules(
263
- bundle ?? "default",
264
- // include all core modules as shared
265
- {
266
- react: async () => (await import("react")).default,
267
- "react-dom": async () => (await import("react-dom")).default,
268
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
269
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
270
- "react-dom/client": async () => (await import("react-dom/client")).default,
271
- ...shared
272
- },
273
- remoteShared
274
- );
120
+ const propSrc = src;
121
+ return applyBundleUrlToSrc(bundle, propSrc.src);
275
122
  }
276
- function createChunkLoader(runtime) {
277
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
278
- const self = globalThis;
279
- const {
280
- bundle,
281
- id: path,
282
- prefix
283
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
284
- bundle: scriptBundle ?? "",
285
- id: chunkId
286
- };
287
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
288
- if (remoteRuntime === RUNTIME_WEBPACK) {
289
- return Promise.resolve(void 0);
290
- }
291
- const url = new URL(
292
- path ? `${prefix ?? ""}${path}`.replace(
293
- /(?<char>[^:])(?<double>\/\/)/g,
294
- "$1/"
295
- ) : "/",
296
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
297
- ).href;
298
- if (url.endsWith(".css")) {
299
- return;
300
- }
301
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
302
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
303
- }
304
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
305
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
123
+ var imageImpl = (bundle) => function RemoteImage({
124
+ fill: _fill,
125
+ loader: _loader,
126
+ quality: _quality,
127
+ priority: _priority,
128
+ loading: _loading,
129
+ placeholder: _placeholder,
130
+ blurDataURL: _blurDataURL,
131
+ unoptimized: _unoptimized,
132
+ overrideSrc: _overrideSrc,
133
+ src,
134
+ ...props
135
+ }) {
136
+ const newSrc = applyBundleUrlToImagePropsSrc(
137
+ bundle,
138
+ typeof src === "string" ? src : src.src
139
+ );
140
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
141
+ "img",
142
+ {
143
+ decoding: "async",
144
+ style: { color: "transparent" },
145
+ ...props,
146
+ src: newSrc,
147
+ suppressHydrationWarning: true
306
148
  }
307
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
308
- fetch(url).then((res) => res.text()).then((code) => {
309
- if (code.includes("globalThis.TURBOPACK")) {
310
- return handleTurbopackChunk(code, bundle ?? "", url);
149
+ );
150
+ };
151
+ function sharedPolyfills(shared) {
152
+ const self = globalThis;
153
+ const polyfill = {
154
+ "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
155
+ useRouter() {
156
+ return {
157
+ push: (routerUrl) => {
158
+ history.pushState({}, "", routerUrl);
159
+ },
160
+ replace: (routerUrl) => {
161
+ history.replaceState({}, "", routerUrl);
162
+ },
163
+ back: () => {
164
+ history.back();
165
+ }
166
+ };
167
+ },
168
+ usePathname() {
169
+ return location.pathname;
170
+ },
171
+ useParams() {
172
+ return {};
173
+ },
174
+ useSearchParams() {
175
+ return new URLSearchParams(location.search);
176
+ },
177
+ useSelectedLayoutSegment() {
178
+ return null;
179
+ },
180
+ useSelectedLayoutSegments() {
181
+ return [];
182
+ },
183
+ __esModule: true
184
+ })),
185
+ "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
186
+ default: ({
187
+ scroll: _,
188
+ replace,
189
+ prefetch,
190
+ onNavigate,
191
+ children,
192
+ ...props
193
+ }) => {
194
+ if (prefetch) {
195
+ console.warn(
196
+ "Next.js Link prefetch is not supported in remote components"
197
+ );
311
198
  }
312
- }).then(resolve).catch(reject);
313
- });
314
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
199
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
200
+ "a",
201
+ {
202
+ ...props,
203
+ href: props.href,
204
+ onClick: (e) => {
205
+ e.preventDefault();
206
+ let preventDefaulted = false;
207
+ e.preventDefault = () => {
208
+ preventDefaulted = true;
209
+ e.defaultPrevented = true;
210
+ };
211
+ if (typeof props.onClick === "function") {
212
+ props.onClick(e);
213
+ }
214
+ onNavigate?.(e);
215
+ if (preventDefaulted) {
216
+ return;
217
+ }
218
+ if (replace) {
219
+ history.replaceState({}, "", props.href);
220
+ } else {
221
+ history.pushState({}, "", props.href);
222
+ }
223
+ },
224
+ suppressHydrationWarning: true,
225
+ children: children ?? null
226
+ }
227
+ );
228
+ },
229
+ useLinkStatus() {
230
+ return { pending: false };
231
+ },
232
+ __esModule: true
233
+ })),
234
+ "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
235
+ default: () => {
236
+ throw new Error("Next.js <Form> component not implemented");
237
+ },
238
+ __esModule: true
239
+ })),
240
+ "next/dist/client/image-component": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
241
+ Image: imageImpl(bundle),
242
+ __esModule: true
243
+ })),
244
+ "next/image": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
245
+ default: imageImpl(bundle),
246
+ getImageProps: (_imgProps) => {
247
+ throw new Error(
248
+ "Next.js getImageProps() is not implemented in remote components"
249
+ );
250
+ },
251
+ __esModule: true
252
+ })),
253
+ "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
254
+ // TODO: implement <Script> component for non-Next.js host applications
255
+ // do not throw an error for now
256
+ default: () => null,
257
+ __esModule: true
258
+ })),
259
+ "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
260
+ // TODO: incomplete implementation
261
+ Promise.resolve({
262
+ useRouter() {
263
+ return {
264
+ push: (routerUrl) => {
265
+ history.pushState({}, "", routerUrl);
266
+ },
267
+ replace: (routerUrl) => {
268
+ history.replaceState({}, "", routerUrl);
269
+ },
270
+ back: () => {
271
+ history.back();
272
+ }
273
+ };
274
+ },
275
+ __esModule: true
276
+ })
277
+ )),
278
+ "next/dist/build/polyfills/process": () => Promise.resolve({
279
+ default: {
280
+ env: {
281
+ NODE_ENV: "production"
282
+ }
283
+ },
284
+ __esModule: true
285
+ })
315
286
  };
287
+ polyfill["next/navigation"] = polyfill["next/dist/client/components/navigation"];
288
+ polyfill["next/link"] = polyfill["next/dist/client/app-dir/link"];
289
+ polyfill["next/form"] = polyfill["next/dist/client/app-dir/form"];
290
+ polyfill["next/dist/api/image"] = polyfill["next/dist/client/image-component"];
291
+ polyfill["next/script"] = polyfill["next/dist/client/script"];
292
+ return polyfill;
316
293
  }
317
- async function handleTurbopackChunk(code, bundle, url) {
318
- if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
319
- const preloadLinks = document.querySelectorAll(
320
- `link[rel="preload"][href="${new URL(url).pathname}"]`
321
- );
322
- preloadLinks.forEach((preloadLink) => preloadLink.remove());
323
- return;
294
+
295
+ // src/shared/error.ts
296
+ var RemoteComponentsError = class extends Error {
297
+ code = "REMOTE_COMPONENTS_ERROR";
298
+ constructor(message, options) {
299
+ super(message, options);
300
+ this.name = "RemoteComponentsError";
324
301
  }
325
- const self = globalThis;
326
- const bundleKey = getBundleKey(bundle);
327
- const transformedCode = code.replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(
328
- /TURBOPACK_WORKER_LOCATION/g,
329
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
330
- ).replace(
331
- /TURBOPACK_NEXT_CHUNK_URLS/g,
332
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
333
- ).replace(
334
- /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
335
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
336
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
337
- /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
338
- `//# sourceMappingURL=${new URL(
339
- ".",
340
- new URL(
341
- url,
342
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
343
- )
344
- ).href}$1$2.js.map`
302
+ };
303
+ function multipleRemoteComponentsError(url) {
304
+ return new Error(
305
+ `Multiple Remote Components found at "${url}". When a page exposes multiple Remote Components you must specify the "name" prop to select which one to load.`
345
306
  );
346
- await new Promise((scriptResolve, scriptReject) => {
347
- const blob = new Blob([transformedCode], {
348
- type: "application/javascript; charset=UTF-8"
349
- });
350
- const scriptUrl = URL.createObjectURL(blob);
351
- const script = document.createElement("script");
352
- script.setAttribute("data-turbopack-src", url);
353
- script.src = scriptUrl;
354
- script.async = true;
355
- script.onload = () => {
356
- URL.revokeObjectURL(scriptUrl);
357
- scriptResolve(void 0);
358
- script.remove();
359
- };
360
- script.onerror = () => {
361
- URL.revokeObjectURL(scriptUrl);
362
- scriptReject(
363
- new RemoteComponentsError(
364
- `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
365
- )
366
- );
367
- script.remove();
368
- };
369
- document.head.appendChild(script);
370
- });
371
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
372
- const loadChunkLists = [];
373
- while (chunkLists?.length) {
374
- const { chunks } = chunkLists.shift() ?? { chunks: [] };
375
- if (chunks.length > 0) {
376
- chunks.forEach((id) => {
377
- const chunkLoadResult = self.__webpack_chunk_load__?.(
378
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
379
- );
380
- if (chunkLoadResult) {
381
- loadChunkLists.push(chunkLoadResult);
307
+ }
308
+ function failedToFetchRemoteComponentError(url, error) {
309
+ return new RemoteComponentsError(
310
+ `Failed to fetch Remote Component from "${url}". Is the URL correct and accessible?`,
311
+ { cause: error instanceof Error ? error : new Error(String(error)) }
312
+ );
313
+ }
314
+
315
+ // src/shared/client/component-loader.ts
316
+ var React = __toESM(require("react"), 1);
317
+ var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
318
+ var JSXRuntime = __toESM(require("react/jsx-runtime"), 1);
319
+ var ReactDOM = __toESM(require("react-dom"), 1);
320
+ var ReactDOMClient = __toESM(require("react-dom/client"), 1);
321
+
322
+ // src/shared/webpack/next-client-pages-loader.ts
323
+ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
324
+ const self = globalThis;
325
+ const nextCssOriginal = document.querySelector(
326
+ `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
327
+ );
328
+ if (nextCssOriginal) {
329
+ nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
330
+ }
331
+ const nextCss = document.createElement("noscript");
332
+ nextCss.id = "__next_css__DO_NOT_USE__";
333
+ nextCss.setAttribute("data-bundle", bundle);
334
+ nextCss.setAttribute("data-route", route);
335
+ const nextCssEnd = document.createElement("noscript");
336
+ nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
337
+ nextCssEnd.setAttribute("data-bundle", bundle);
338
+ nextCssEnd.setAttribute("data-route", route);
339
+ document.head.appendChild(nextCssEnd);
340
+ document.head.appendChild(nextCss);
341
+ const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
342
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
343
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
344
+ (key) => key.includes("/next/dist/client/page-loader.js")
345
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
346
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
347
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
348
+ (key) => key.includes("/next/dist/client/page-loader.js")
349
+ ) ?? ""] ?? -1;
350
+ const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
351
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
352
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
353
+ (key) => key.includes("/next/dist/client/page-loader.js")
354
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
355
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
356
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
357
+ (key) => key.includes("/next/dist/client/page-loader.js")
358
+ ) ?? ""] ?? -1;
359
+ if (!(componentLoaderChunk && appLoaderChunk)) {
360
+ throw new RemoteComponentsError(
361
+ `Next.js client pages loader not found in bundle "${bundle}".`
362
+ );
363
+ }
364
+ const __NEXT_P_ORIGINAL = self.__NEXT_P;
365
+ const selfOriginal = self;
366
+ delete selfOriginal.__NEXT_P;
367
+ self.__remote_webpack_require__?.[bundle]?.(
368
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
369
+ );
370
+ if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
371
+ self.__remote_webpack_require__?.[bundle]?.(
372
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
373
+ );
374
+ }
375
+ if (self.__NEXT_P) {
376
+ const [, componentLoader] = self.__NEXT_P[0] ?? [
377
+ void 0,
378
+ () => ({ default: null })
379
+ ];
380
+ const [, appLoader] = self.__NEXT_P[2] ?? [
381
+ void 0,
382
+ () => ({
383
+ default: null
384
+ })
385
+ ];
386
+ const { default: Component } = componentLoader();
387
+ const { default: App } = appLoader();
388
+ if (!self.__remote_next_css__) {
389
+ self.__remote_next_css__ = {};
390
+ }
391
+ if (!self.__remote_next_css__[bundle]) {
392
+ const cssRE = /\.s?css$/;
393
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
394
+ self.__remote_webpack_require__?.[bundle]?.(id);
395
+ });
396
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
397
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
398
+ if (id) {
399
+ self.__remote_webpack_require__?.[bundle]?.(id);
382
400
  }
383
401
  });
402
+ const elements = [];
403
+ let node = nextCss.previousSibling;
404
+ while (node && node !== nextCssEnd) {
405
+ elements.push(node);
406
+ node.remove();
407
+ node = nextCss.previousSibling;
408
+ }
409
+ self.__remote_next_css__[bundle] = elements;
384
410
  }
411
+ if (styleContainer) {
412
+ const elements = self.__remote_next_css__[bundle];
413
+ elements.forEach((el) => {
414
+ styleContainer.appendChild(el.cloneNode(true));
415
+ });
416
+ } else {
417
+ const elements = self.__remote_next_css__[bundle];
418
+ elements.forEach((el) => {
419
+ document.head.appendChild(el);
420
+ });
421
+ }
422
+ delete self.__NEXT_P;
423
+ self.__NEXT_P = __NEXT_P_ORIGINAL;
424
+ if (nextCssOriginal) {
425
+ nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
426
+ }
427
+ nextCss.remove();
428
+ nextCssEnd.remove();
429
+ return { Component, App };
385
430
  }
386
- if (loadChunkLists.length > 0) {
387
- await Promise.all(loadChunkLists);
388
- }
431
+ return { Component: null, App: null };
389
432
  }
390
- function createModuleRequire(runtime) {
391
- return (id) => {
392
- const self = globalThis;
393
- const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? { bundle: "default", id };
394
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
395
- try {
396
- if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
397
- return self.__remote_webpack_require__?.[bundle]?.(moduleId);
398
- }
399
- const sharedModule = getSharedModule(bundle ?? "default", moduleId ?? id);
400
- if (sharedModule) {
401
- return sharedModule;
402
- }
403
- if (bundle && moduleId) {
404
- return handleTurbopackModule(bundle, moduleId, id);
433
+
434
+ // src/shared/webpack/shared-modules.ts
435
+ function applySharedModules(bundle, resolve) {
436
+ const self = globalThis;
437
+ if (self.__remote_webpack_require__?.[bundle]) {
438
+ const modulePaths = Object.keys(
439
+ self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
440
+ );
441
+ for (const [key, value] of Object.entries(resolve)) {
442
+ let ids = modulePaths.filter((p) => p === key);
443
+ if (ids.length === 0) {
444
+ ids = modulePaths.filter((p) => p.includes(key));
405
445
  }
406
- throw new Error(`Module "${id}" not found.`);
407
- } catch (requireError) {
408
- if (typeof self.__original_webpack_require__ !== "function") {
409
- throw new RemoteComponentsError(
410
- `Module "${id}" not found in remote component bundle "${bundle}".`,
411
- {
412
- cause: requireError instanceof Error ? requireError : void 0
446
+ for (let id of ids) {
447
+ const webpackBundle = self.__remote_webpack_require__[bundle];
448
+ if (webpackBundle.m) {
449
+ if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {
450
+ id = `${self.__remote_webpack_module_map__[bundle][id]}`;
413
451
  }
414
- );
415
- }
416
- try {
417
- return self.__original_webpack_require__(id);
418
- } catch (originalError) {
419
- throw new RemoteComponentsError(
420
- `Module "${id}" not found in remote component bundle "${bundle}".`,
421
- { cause: originalError instanceof Error ? originalError : void 0 }
422
- );
452
+ webpackBundle.m[id] = (module2) => {
453
+ module2.exports = value;
454
+ };
455
+ }
423
456
  }
424
457
  }
425
- };
426
- }
427
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
428
- const self = globalThis;
429
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
430
- if (!self.__remote_shared_modules__[bundle]) {
431
- self.__remote_shared_modules__[bundle] = {};
432
458
  }
433
- const bundleKey = getBundleKey(bundle);
434
- const modules = self[`TURBOPACK_${bundleKey}`];
435
- let sharedModuleInitializer = null;
436
- if (modules && Array.isArray(modules)) {
437
- const allModules = modules.flat();
438
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
439
- if (typeof idOrFunc !== "function") {
440
- return false;
459
+ }
460
+
461
+ // src/shared/client/rsc.ts
462
+ var import_web_streams_polyfill = require("web-streams-polyfill");
463
+ function fixPayload(payload) {
464
+ if (Array.isArray(payload)) {
465
+ if (payload[0] === "$") {
466
+ fixPayload(payload[3]);
467
+ if (payload.length === 4) {
468
+ payload.push(null, null, 1);
441
469
  }
442
- const funcCode = idOrFunc.toString();
443
- return /[a-z]\.TURBOPACK_REMOTE_SHARED/.test(funcCode);
444
- });
445
- if (sharedModuleInitializerIndex > 0) {
446
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
447
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
448
- const { sharedModuleId } = /\.TURBOPACK_REMOTE_SHARED=await e\.A\((?<sharedModuleId>[0-9]+)\)/.exec(
449
- sharedModuleInitializerCode
450
- )?.groups ?? {};
451
- if (sharedModuleId) {
452
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
453
- bundle,
454
- sharedModuleId,
455
- `[${bundle}] ${sharedModuleInitializerId}`
456
- );
457
- sharedModuleInitializer = sharedModuleInitializerInstance;
470
+ } else {
471
+ for (const item of payload) {
472
+ fixPayload(item);
458
473
  }
459
474
  }
460
- if (sharedModuleInitializer) {
461
- const { shared } = await sharedModuleInitializer;
462
- const sharedModuleIds = Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
463
- const { asyncSharedModuleId } = /e\.A\((?<asyncSharedModuleId>[0-9]+)\)/.exec(value.toString())?.groups ?? {};
464
- if (asyncSharedModuleId) {
465
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
466
- let asyncSharedModule;
467
- const newAllModules = self[`TURBOPACK_${bundleKey}`]?.flat() ?? [];
468
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
469
- asyncSharedModuleIdNumber
470
- );
471
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
472
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
473
- }
474
- if (asyncSharedModule) {
475
- const asyncSharedModuleCode = asyncSharedModule.toString();
476
- const { sharedModuleId } = /e=>{e\.v\(e=>Promise\.resolve\(\)\.then\(\(\)=>e\((?<sharedModuleId>[0-9]+)\)\)\)}/.exec(
477
- asyncSharedModuleCode
478
- )?.groups ?? /e=>{e\.v\(t=>Promise\.all\(\["[^"]+"\].map\(t=>e\.l\(t\)\)\)\.then\(\(\)=>t\((?<sharedModuleId>[0-9]+)\)\)\)}/.exec(
479
- asyncSharedModuleCode
480
- )?.groups ?? {};
481
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
482
- "__remote_shared_module_",
483
- ""
484
- );
485
- }
486
- }
487
- return acc;
488
- }, {});
489
- return Promise.all(
490
- Object.entries(sharedModuleIds).map(async ([id, module2]) => {
491
- if (self.__remote_shared_modules__?.[bundle]) {
492
- if (hostShared[module2]) {
493
- self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
494
- }
495
- }
496
- })
497
- );
475
+ } else if (typeof payload === "object" && payload !== null) {
476
+ for (const key in payload) {
477
+ fixPayload(payload[key]);
498
478
  }
499
479
  }
500
- return Promise.all(
501
- Object.entries(remoteShared).map(async ([id, module2]) => {
502
- if (self.__remote_shared_modules__?.[bundle]) {
503
- if (hostShared[module2]) {
504
- self.__remote_shared_modules__[bundle][id.replace("[app-ssr]", "[app-client]")] = await hostShared[module2](bundle);
480
+ }
481
+ function createRSCStream(rscName, data) {
482
+ return new import_web_streams_polyfill.ReadableStream({
483
+ type: "bytes",
484
+ start(controller) {
485
+ const encoder = new TextEncoder();
486
+ const self = globalThis;
487
+ if (data.length > 0) {
488
+ data.forEach((chunk) => {
489
+ const lines = chunk.split("\n");
490
+ for (const line of lines) {
491
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
492
+ if (match?.groups?.rsc) {
493
+ self[rscName] = self[rscName] ?? [];
494
+ self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
495
+ }
496
+ }
497
+ });
498
+ }
499
+ const allChunks = (self[rscName] ?? [`0:[null]
500
+ `]).join("");
501
+ self[rscName] = null;
502
+ allChunks.split("\n").forEach((chunk) => {
503
+ if (chunk.length > 0) {
504
+ const { before, id, prefix, payload } = /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
505
+ chunk
506
+ )?.groups ?? {};
507
+ if (payload) {
508
+ const jsonPayload = JSON.parse(payload);
509
+ fixPayload(jsonPayload);
510
+ const reconstruct = `${before ?? ""}${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
511
+ controller.enqueue(encoder.encode(`${reconstruct}
512
+ `));
513
+ } else {
514
+ controller.enqueue(encoder.encode(`${chunk}
515
+ `));
516
+ }
505
517
  } else {
506
- console.error(`Shared module "${module2}" not found for "${bundle}".`);
518
+ controller.enqueue(encoder.encode(`${chunk}
519
+ `));
507
520
  }
508
- }
521
+ });
522
+ controller.close();
523
+ }
524
+ });
525
+ }
526
+
527
+ // src/shared/client/script-loader.ts
528
+ async function loadScripts(scripts) {
529
+ await Promise.all(
530
+ scripts.map((script) => {
531
+ return new Promise((resolve, reject) => {
532
+ const newSrc = new URL(
533
+ // remove the remote component bundle name identifier from the script src
534
+ script.src.replace(/\/_next\/\[.+\](?<whitespace>%20| )/, "/_next/"),
535
+ location.origin
536
+ ).href;
537
+ const newScript = document.createElement("script");
538
+ newScript.onload = () => {
539
+ resolve();
540
+ };
541
+ newScript.onerror = () => {
542
+ reject(
543
+ new RemoteComponentsError(
544
+ `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
545
+ )
546
+ );
547
+ };
548
+ newScript.src = newSrc;
549
+ newScript.async = true;
550
+ document.head.appendChild(newScript);
551
+ });
509
552
  })
510
553
  );
511
554
  }
512
- function getSharedModule(bundle, id) {
513
- const self = globalThis;
514
- for (const [key, value] of Object.entries(
515
- self.__remote_shared_modules__?.[bundle] ?? {}
516
- )) {
517
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
518
- return value;
519
- }
520
- }
521
- return null;
555
+
556
+ // src/shared/utils/index.ts
557
+ function escapeString(str) {
558
+ return str.replace(/[^a-z0-9]/g, "_");
522
559
  }
523
- function handleTurbopackModule(bundle, moduleId, id) {
560
+ var attrToProp = {
561
+ fetchpriority: "fetchPriority",
562
+ crossorigin: "crossOrigin",
563
+ imagesrcset: "imageSrcSet",
564
+ imagesizes: "imageSizes",
565
+ srcset: "srcSet"
566
+ };
567
+
568
+ // src/shared/client/const.ts
569
+ var DEFAULT_ROUTE = "/";
570
+ var RUNTIME_WEBPACK = "webpack";
571
+ var RUNTIME_TURBOPACK = "turbopack";
572
+ var RUNTIME_SCRIPT = "script";
573
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
574
+ function getBundleKey(bundle) {
575
+ return escapeString(bundle);
576
+ }
577
+
578
+ // src/shared/client/webpack-adapter.ts
579
+ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}) {
524
580
  const self = globalThis;
525
- const bundleKey = getBundleKey(bundle);
526
- const modules = self[`TURBOPACK_${bundleKey}`];
527
- let moduleInit;
528
- const allModules = modules?.flat() ?? [];
529
- if (typeof allModules[1] === "string" || typeof allModules[1] === "number") {
530
- const normalizedId = /^[0-9]+$/.test(moduleId) ? Number(moduleId) : moduleId;
531
- let moduleIdIndex = allModules.indexOf(normalizedId);
532
- if (moduleIdIndex === -1) {
533
- moduleIdIndex = allModules.findIndex(
534
- (bundleEntry) => typeof bundleEntry === "string" && bundleEntry.startsWith(moduleId) || bundleEntry === normalizedId
535
- );
581
+ if (!self.__remote_bundle_url__) {
582
+ self.__remote_bundle_url__ = {};
583
+ }
584
+ self.__remote_bundle_url__[bundle ?? "default"] = url;
585
+ self.__webpack_get_script_filename__ = () => null;
586
+ if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
587
+ if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
588
+ self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
589
+ self.__original_webpack_require__ = self.__webpack_require__;
536
590
  }
537
- if (moduleIdIndex !== -1) {
538
- while (typeof allModules[moduleIdIndex] !== "function" && moduleIdIndex < allModules.length) {
539
- moduleIdIndex++;
540
- }
541
- moduleInit = allModules[moduleIdIndex];
591
+ self.__webpack_chunk_load__ = createChunkLoader(runtime);
592
+ self.__webpack_require__ = createModuleRequire(runtime);
593
+ self.__webpack_require_type__ = runtime;
594
+ if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
595
+ const remoteBundle = bundle ?? "default";
596
+ self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
597
+ self.__remote_webpack_require__[remoteBundle].type = "turbopack";
542
598
  }
543
- } else {
544
- moduleInit = allModules.find(
545
- (bundleEntry) => typeof bundleEntry === "object" && bundleEntry !== null && moduleId in bundleEntry
546
- )?.[moduleId];
547
- }
548
- const exports = {};
549
- const moduleExports = { exports };
550
- if (!self.__remote_components_turbopack_modules__) {
551
- self.__remote_components_turbopack_modules__ = {};
552
599
  }
553
- if (!self.__remote_components_turbopack_modules__[bundle]) {
554
- self.__remote_components_turbopack_modules__[bundle] = {};
555
- }
556
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
557
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
558
- }
559
- if (typeof moduleInit !== "function") {
560
- throw new Error(
561
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
600
+ if (runtime === RUNTIME_TURBOPACK) {
601
+ await Promise.all(
602
+ scripts.map((script) => {
603
+ if (script.src) {
604
+ return self.__webpack_chunk_load__?.(script.src, bundle);
605
+ }
606
+ return Promise.resolve(void 0);
607
+ })
562
608
  );
563
609
  }
564
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
565
- if (!self.__remote_components_turbopack_global__) {
566
- self.__remote_components_turbopack_global__ = {};
567
- }
568
- if (!self.__remote_components_turbopack_global__[bundle]) {
569
- self.__remote_components_turbopack_global__[bundle] = {};
570
- }
571
- moduleInit(
610
+ await initializeSharedModules(
611
+ bundle ?? "default",
612
+ // include all core modules as shared
572
613
  {
573
- // HMR not implemented for Remote Components
574
- k: {
575
- register() {
576
- },
577
- registerExports() {
578
- },
579
- signature() {
580
- return (fn) => {
581
- return fn;
582
- };
583
- }
584
- },
585
- // esm
586
- s(bindings, esmId) {
587
- let mod = exports;
588
- if (typeof esmId === "string" || typeof esmId === "number") {
589
- if (!self.__remote_components_turbopack_modules__) {
590
- self.__remote_components_turbopack_modules__ = {};
591
- }
592
- if (!self.__remote_components_turbopack_modules__[bundle]) {
593
- self.__remote_components_turbopack_modules__[bundle] = {};
594
- }
595
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
596
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
597
- }
598
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
599
- }
600
- Object.defineProperty(mod, "__esModule", { value: true });
601
- if (Array.isArray(bindings)) {
602
- let i = 0;
603
- while (i < bindings.length) {
604
- const propName = bindings[i++];
605
- const tagOrFunc = bindings[i++];
606
- if (typeof tagOrFunc === "number") {
607
- Object.defineProperty(mod, propName, {
608
- value: bindings[i++],
609
- enumerable: true,
610
- writable: false
611
- });
612
- } else {
613
- const getterFn = tagOrFunc;
614
- if (typeof bindings[i] === "function") {
615
- const setterFn = bindings[i++];
616
- Object.defineProperty(mod, propName, {
617
- get: getterFn,
618
- set: setterFn,
619
- enumerable: true
620
- });
621
- } else {
622
- Object.defineProperty(mod, propName, {
623
- get: getterFn,
624
- enumerable: true
625
- });
626
- }
627
- }
628
- }
629
- }
630
- },
631
- // import
632
- i(importId) {
633
- let mod;
634
- if (typeof importId === "string") {
635
- const { exportSource, exportName } = /\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(
636
- importId
637
- )?.groups ?? {};
638
- const normalizedId = importId.replace(
639
- /\s+<export(?<specifier>.*)>$/,
640
- ""
641
- );
642
- mod = self.__webpack_require__?.(
643
- `[${bundle}] ${normalizedId}`
644
- );
645
- if (exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
646
- if (exportSource === "*") {
647
- mod[exportName] = mod;
648
- } else {
649
- mod[exportName] = mod[exportSource];
650
- }
651
- }
652
- } else {
653
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
654
- }
655
- if (typeof mod !== "object") {
656
- mod = { default: mod };
657
- } else if (!("default" in mod) && // eslint-disable-next-line @typescript-eslint/no-base-to-string
658
- mod.toString() !== "[object Module]") {
659
- try {
660
- mod.default = mod;
661
- } catch {
662
- }
663
- }
664
- return mod;
665
- },
666
- // require
667
- r(requireId) {
668
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
669
- },
670
- // value exports
671
- v(value) {
672
- if (typeof value === "function") {
673
- exports.default = value((vid) => {
674
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
675
- });
676
- } else {
677
- moduleExports.exports = value;
614
+ react: async () => (await import("react")).default,
615
+ "react-dom": async () => (await import("react-dom")).default,
616
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
617
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
618
+ "react-dom/client": async () => (await import("react-dom/client")).default,
619
+ ...shared
620
+ },
621
+ remoteShared
622
+ );
623
+ }
624
+ function createChunkLoader(runtime) {
625
+ return function __turbopack_chunk_load__(chunkId, scriptBundle) {
626
+ const self = globalThis;
627
+ const {
628
+ bundle,
629
+ id: path,
630
+ prefix
631
+ } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
632
+ bundle: scriptBundle ?? "",
633
+ id: chunkId
634
+ };
635
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
636
+ if (remoteRuntime === RUNTIME_WEBPACK) {
637
+ return Promise.resolve(void 0);
638
+ }
639
+ const url = new URL(
640
+ path ? `${prefix ?? ""}${path}`.replace(
641
+ /(?<char>[^:])(?<double>\/\/)/g,
642
+ "$1/"
643
+ ) : "/",
644
+ self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
645
+ ).href;
646
+ if (url.endsWith(".css")) {
647
+ return;
648
+ }
649
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
650
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
651
+ }
652
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
653
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
654
+ }
655
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
656
+ fetch(url).then((res) => res.text()).then((code) => {
657
+ if (code.includes("globalThis.TURBOPACK")) {
658
+ return handleTurbopackChunk(code, bundle ?? "", url);
678
659
  }
679
- },
680
- // async module initializer
681
- async a(mod) {
682
- let result;
683
- await mod(
684
- () => {
685
- },
686
- (value) => result = value
687
- );
688
- exports.default = result;
689
- },
690
- // async module loader
691
- async A(Aid) {
692
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
693
- return mod.default(
694
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
660
+ }).then(resolve).catch(reject);
661
+ });
662
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
663
+ };
664
+ }
665
+ async function handleTurbopackChunk(code, bundle, url) {
666
+ if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
667
+ const preloadLinks = document.querySelectorAll(
668
+ `link[rel="preload"][href="${new URL(url).pathname}"]`
669
+ );
670
+ preloadLinks.forEach((preloadLink) => preloadLink.remove());
671
+ return;
672
+ }
673
+ const self = globalThis;
674
+ const bundleKey = getBundleKey(bundle);
675
+ const transformedCode = code.replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(
676
+ /TURBOPACK_WORKER_LOCATION/g,
677
+ `TURBOPACK_WORKER_LOCATION_${bundleKey}`
678
+ ).replace(
679
+ /TURBOPACK_NEXT_CHUNK_URLS/g,
680
+ `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
681
+ ).replace(
682
+ /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
683
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
684
+ ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
685
+ /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
686
+ `//# sourceMappingURL=${new URL(
687
+ ".",
688
+ new URL(
689
+ url,
690
+ self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
691
+ )
692
+ ).href}$1$2.js.map`
693
+ );
694
+ await new Promise((scriptResolve, scriptReject) => {
695
+ const blob = new Blob([transformedCode], {
696
+ type: "application/javascript; charset=UTF-8"
697
+ });
698
+ const scriptUrl = URL.createObjectURL(blob);
699
+ const script = document.createElement("script");
700
+ script.setAttribute("data-turbopack-src", url);
701
+ script.src = scriptUrl;
702
+ script.async = true;
703
+ script.onload = () => {
704
+ URL.revokeObjectURL(scriptUrl);
705
+ scriptResolve(void 0);
706
+ script.remove();
707
+ };
708
+ script.onerror = () => {
709
+ URL.revokeObjectURL(scriptUrl);
710
+ scriptReject(
711
+ new RemoteComponentsError(
712
+ `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
713
+ )
714
+ );
715
+ script.remove();
716
+ };
717
+ document.head.appendChild(script);
718
+ });
719
+ const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
720
+ const loadChunkLists = [];
721
+ while (chunkLists?.length) {
722
+ const { chunks } = chunkLists.shift() ?? { chunks: [] };
723
+ if (chunks.length > 0) {
724
+ chunks.forEach((id) => {
725
+ const chunkLoadResult = self.__webpack_chunk_load__?.(
726
+ `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
695
727
  );
696
- },
697
- // chunk loader
698
- l(url) {
699
- const moduleInitIndex = allModules.indexOf(moduleInit);
700
- if (moduleInitIndex !== -1) {
701
- const scriptIndex = allModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
702
- if (scriptIndex !== -1) {
703
- const script = allModules[scriptIndex];
704
- const scriptSrc = script.getAttribute("data-turbopack-src") || "";
705
- const nextIndex = scriptSrc.indexOf("/_next");
706
- const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
707
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
708
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
709
- }
728
+ if (chunkLoadResult) {
729
+ loadChunkLists.push(chunkLoadResult);
710
730
  }
711
- throw new Error(
712
- `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
713
- );
714
- },
715
- // global
716
- g: self.__remote_components_turbopack_global__[bundle],
717
- m: moduleExports,
718
- e: exports
719
- },
720
- moduleExports,
721
- exports
722
- );
723
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
724
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
725
- }
726
- return moduleExports.exports;
727
- }
728
-
729
- // src/shared/client/script-loader.ts
730
- async function loadScripts(scripts) {
731
- await Promise.all(
732
- scripts.map((script) => {
733
- return new Promise((resolve, reject) => {
734
- const newSrc = new URL(
735
- // remove the remote component bundle name identifier from the script src
736
- script.src.replace(/\/_next\/\[.+\](?<whitespace>%20| )/, "/_next/"),
737
- location.origin
738
- ).href;
739
- const newScript = document.createElement("script");
740
- newScript.onload = () => {
741
- resolve();
742
- };
743
- newScript.onerror = () => {
744
- reject(
745
- new RemoteComponentsError(
746
- `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
747
- )
748
- );
749
- };
750
- newScript.src = newSrc;
751
- newScript.async = true;
752
- document.head.appendChild(newScript);
753
731
  });
754
- })
755
- );
756
- }
757
-
758
- // src/shared/client/rsc.ts
759
- var import_web_streams_polyfill = require("web-streams-polyfill");
760
- function fixPayload(payload) {
761
- if (Array.isArray(payload)) {
762
- if (payload[0] === "$") {
763
- fixPayload(payload[3]);
764
- if (payload.length === 4) {
765
- payload.push(null, null, 1);
766
- }
767
- } else {
768
- for (const item of payload) {
769
- fixPayload(item);
770
- }
771
- }
772
- } else if (typeof payload === "object" && payload !== null) {
773
- for (const key in payload) {
774
- fixPayload(payload[key]);
775
732
  }
776
733
  }
734
+ if (loadChunkLists.length > 0) {
735
+ await Promise.all(loadChunkLists);
736
+ }
777
737
  }
778
- function createRSCStream(rscName, data) {
779
- return new import_web_streams_polyfill.ReadableStream({
780
- type: "bytes",
781
- start(controller) {
782
- const encoder = new TextEncoder();
783
- const self = globalThis;
784
- if (data.length > 0) {
785
- data.forEach((chunk) => {
786
- const lines = chunk.split("\n");
787
- for (const line of lines) {
788
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
789
- if (match?.groups?.rsc) {
790
- self[rscName] = self[rscName] ?? [];
791
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
792
- }
793
- }
794
- });
738
+ function createModuleRequire(runtime) {
739
+ return (id) => {
740
+ const self = globalThis;
741
+ const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
742
+ bundle: "default",
743
+ id
744
+ };
745
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
746
+ try {
747
+ if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
748
+ return self.__remote_webpack_require__?.[bundle]?.(moduleId);
795
749
  }
796
- const allChunks = (self[rscName] ?? [`0:[null]
797
- `]).join("");
798
- self[rscName] = null;
799
- allChunks.split("\n").forEach((chunk) => {
800
- if (chunk.length > 0) {
801
- const { before, id, prefix, payload } = /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
802
- chunk
803
- )?.groups ?? {};
804
- if (payload) {
805
- const jsonPayload = JSON.parse(payload);
806
- fixPayload(jsonPayload);
807
- const reconstruct = `${before ?? ""}${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
808
- controller.enqueue(encoder.encode(`${reconstruct}
809
- `));
810
- } else {
811
- controller.enqueue(encoder.encode(`${chunk}
812
- `));
750
+ const sharedModule = getSharedModule(bundle ?? "default", moduleId ?? id);
751
+ if (sharedModule) {
752
+ return sharedModule;
753
+ }
754
+ if (bundle && moduleId) {
755
+ return handleTurbopackModule(bundle, moduleId, id);
756
+ }
757
+ throw new Error(`Module "${id}" not found.`);
758
+ } catch (requireError) {
759
+ if (typeof self.__original_webpack_require__ !== "function") {
760
+ throw new RemoteComponentsError(
761
+ `Module "${id}" not found in remote component bundle "${bundle}".`,
762
+ {
763
+ cause: requireError instanceof Error ? requireError : void 0
813
764
  }
814
- } else {
815
- controller.enqueue(encoder.encode(`${chunk}
816
- `));
817
- }
818
- });
819
- controller.close();
765
+ );
766
+ }
767
+ try {
768
+ return self.__original_webpack_require__(id);
769
+ } catch (originalError) {
770
+ throw new RemoteComponentsError(
771
+ `Module "${id}" not found in remote component bundle "${bundle}".`,
772
+ { cause: originalError instanceof Error ? originalError : void 0 }
773
+ );
774
+ }
820
775
  }
821
- });
776
+ };
822
777
  }
823
-
824
- // src/shared/client/component-loader.ts
825
- async function loadRemoteComponent({
826
- url,
827
- name,
828
- rscName,
829
- bundle,
830
- route = "/",
831
- runtime = "webpack",
832
- data,
833
- nextData,
834
- scripts = [],
835
- shared = Promise.resolve({}),
836
- remoteShared = {},
837
- container
838
- }) {
839
- try {
840
- if (runtime === "webpack") {
841
- const self = globalThis;
842
- if (!self.__DISABLE_WEBPACK_EXEC__) {
843
- self.__DISABLE_WEBPACK_EXEC__ = {};
778
+ async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
779
+ const self = globalThis;
780
+ self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
781
+ if (!self.__remote_shared_modules__[bundle]) {
782
+ self.__remote_shared_modules__[bundle] = {};
783
+ }
784
+ const bundleKey = getBundleKey(bundle);
785
+ const modules = self[`TURBOPACK_${bundleKey}`];
786
+ let sharedModuleInitializer = null;
787
+ if (modules && Array.isArray(modules)) {
788
+ const allModules = modules.flat();
789
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
790
+ if (typeof idOrFunc !== "function") {
791
+ return false;
792
+ }
793
+ const funcCode = idOrFunc.toString();
794
+ return /[a-z]\.TURBOPACK_REMOTE_SHARED/.test(funcCode);
795
+ });
796
+ if (sharedModuleInitializerIndex > 0) {
797
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
798
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
799
+ const { sharedModuleId } = /\.TURBOPACK_REMOTE_SHARED=await e\.A\((?<sharedModuleId>[0-9]+)\)/.exec(
800
+ sharedModuleInitializerCode
801
+ )?.groups ?? {};
802
+ if (sharedModuleId) {
803
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
804
+ bundle,
805
+ sharedModuleId,
806
+ `[${bundle}] ${sharedModuleInitializerId}`
807
+ );
808
+ sharedModuleInitializer = sharedModuleInitializerInstance;
844
809
  }
845
- self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
846
- await loadScripts(scripts);
847
810
  }
848
- const hostShared = await shared;
849
- await setupWebpackRuntime(
850
- runtime,
851
- scripts,
852
- url,
853
- bundle,
854
- hostShared,
855
- remoteShared
856
- );
857
- if (bundle) {
858
- const resolve = {
859
- "/react/index.js": React,
860
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
861
- "/react/jsx-runtime.js": JSXRuntime,
862
- "/react-dom/index.js": ReactDOM,
863
- "/react-dom/client.js": ReactDOMClient,
864
- ...Object.entries(remoteShared).reduce(
865
- (acc, [key, value]) => {
866
- if (typeof hostShared[value] !== "undefined") {
867
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
811
+ if (sharedModuleInitializer) {
812
+ const { shared } = await sharedModuleInitializer;
813
+ const sharedModuleIds = Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
814
+ const { asyncSharedModuleId } = /e\.A\((?<asyncSharedModuleId>[0-9]+)\)/.exec(value.toString())?.groups ?? {};
815
+ if (asyncSharedModuleId) {
816
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
817
+ let asyncSharedModule;
818
+ const newAllModules = self[`TURBOPACK_${bundleKey}`]?.flat() ?? [];
819
+ const asyncSharedModuleIdIndex = newAllModules.indexOf(
820
+ asyncSharedModuleIdNumber
821
+ );
822
+ if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
823
+ asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
824
+ }
825
+ if (asyncSharedModule) {
826
+ const asyncSharedModuleCode = asyncSharedModule.toString();
827
+ const { sharedModuleId } = /e=>{e\.v\(e=>Promise\.resolve\(\)\.then\(\(\)=>e\((?<sharedModuleId>[0-9]+)\)\)\)}/.exec(
828
+ asyncSharedModuleCode
829
+ )?.groups ?? /e=>{e\.v\(t=>Promise\.all\(\["[^"]+"\].map\(t=>e\.l\(t\)\)\)\.then\(\(\)=>t\((?<sharedModuleId>[0-9]+)\)\)\)}/.exec(
830
+ asyncSharedModuleCode
831
+ )?.groups ?? {};
832
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
833
+ "__remote_shared_module_",
834
+ ""
835
+ );
836
+ }
837
+ }
838
+ return acc;
839
+ }, {});
840
+ return Promise.all(
841
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
842
+ if (self.__remote_shared_modules__?.[bundle]) {
843
+ if (hostShared[module2]) {
844
+ self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
868
845
  }
869
- return acc;
870
- },
871
- {}
872
- )
873
- };
874
- await Promise.all(
875
- Object.entries(resolve).map(async ([key, value]) => {
876
- if (typeof value === "function") {
877
- resolve[key] = await value(bundle);
878
846
  }
879
- return Promise.resolve(value);
880
847
  })
881
848
  );
882
- applySharedModules(bundle, resolve);
883
- }
884
- if (data.length > 0) {
885
- return await loadRSCComponent(rscName ?? name, data);
886
- } else if (nextData) {
887
- return loadNextPagesComponent(bundle, route, nextData, name, container);
888
849
  }
889
- return loadRSCComponent(rscName ?? name, [`0:[null]
890
- `]);
891
- } catch (error) {
892
- return {
893
- component: null,
894
- error: new RemoteComponentsError(
895
- `Failed to load remote component "${name}".`,
896
- { cause: error instanceof Error ? error : new Error(String(error)) }
897
- )
898
- };
899
- }
900
- }
901
- async function loadRSCComponent(rscName, data) {
902
- let createFromReadableStream;
903
- try {
904
- const { createFromReadableStream: _createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
905
- createFromReadableStream = _createFromReadableStream;
906
- } catch {
907
- const {
908
- default: { createFromReadableStream: _createFromReadableStream }
909
- } = await import("react-server-dom-webpack/client.browser");
910
- createFromReadableStream = _createFromReadableStream;
911
- }
912
- if (typeof createFromReadableStream !== "function") {
913
- throw new RemoteComponentsError(
914
- 'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
915
- );
916
850
  }
917
- const stream = createRSCStream(rscName, data);
918
- const component = createFromReadableStream(stream);
919
- return { component };
851
+ return Promise.all(
852
+ Object.entries(remoteShared).map(async ([id, module2]) => {
853
+ if (self.__remote_shared_modules__?.[bundle]) {
854
+ if (hostShared[module2]) {
855
+ self.__remote_shared_modules__[bundle][id.replace("[app-ssr]", "[app-client]")] = await hostShared[module2](bundle);
856
+ } else {
857
+ console.error(`Shared module "${module2}" not found for "${bundle}".`);
858
+ }
859
+ }
860
+ })
861
+ );
920
862
  }
921
- function loadNextPagesComponent(bundle, route, nextData, name, container) {
922
- const { Component, App } = nextClientPagesLoader(bundle, route, container);
923
- if (!Component) {
924
- throw new RemoteComponentsError(
925
- `Remote Component "${name}" is trying to load the component for route "${route}" but it is not available.`
926
- );
863
+ function getSharedModule(bundle, id) {
864
+ const self = globalThis;
865
+ for (const [key, value] of Object.entries(
866
+ self.__remote_shared_modules__?.[bundle] ?? {}
867
+ )) {
868
+ if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
869
+ return value;
870
+ }
927
871
  }
928
- const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
929
- return { component };
930
- }
931
-
932
- // src/shared/client/set-attributes-from-props.ts
933
- var DOMAttributeNames = {
934
- acceptCharset: "accept-charset",
935
- className: "class",
936
- htmlFor: "for",
937
- httpEquiv: "http-equiv",
938
- noModule: "noModule"
939
- };
940
- var ignoreProps = [
941
- "onLoad",
942
- "onReady",
943
- "dangerouslySetInnerHTML",
944
- "children",
945
- "onError",
946
- "strategy",
947
- "stylesheets"
948
- ];
949
- function isBooleanScriptAttribute(attr) {
950
- return ["async", "defer", "noModule"].includes(attr);
872
+ return null;
951
873
  }
952
- function setAttributesFromProps(el, props) {
953
- for (const [p, value] of Object.entries(props)) {
954
- if (!Object.prototype.hasOwnProperty.call(props, p))
955
- continue;
956
- if (ignoreProps.includes(p))
957
- continue;
958
- if (value === void 0) {
959
- continue;
960
- }
961
- const attr = DOMAttributeNames[p] || p.toLowerCase();
962
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
963
- el[attr] = Boolean(value);
964
- } else {
965
- el.setAttribute(attr, String(value));
874
+ function handleTurbopackModule(bundle, moduleId, id) {
875
+ const self = globalThis;
876
+ const bundleKey = getBundleKey(bundle);
877
+ const modules = self[`TURBOPACK_${bundleKey}`];
878
+ let moduleInit;
879
+ const allModules = modules?.flat() ?? [];
880
+ if (typeof allModules[1] === "string" || typeof allModules[1] === "number") {
881
+ const normalizedId = /^[0-9]+$/.test(moduleId) ? Number(moduleId) : moduleId;
882
+ let moduleIdIndex = allModules.indexOf(normalizedId);
883
+ if (moduleIdIndex === -1) {
884
+ moduleIdIndex = allModules.findIndex(
885
+ (bundleEntry) => typeof bundleEntry === "string" && bundleEntry.startsWith(moduleId) || bundleEntry === normalizedId
886
+ );
966
887
  }
967
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
968
- el.setAttribute(attr, "");
969
- el.removeAttribute(attr);
888
+ if (moduleIdIndex !== -1) {
889
+ while (typeof allModules[moduleIdIndex] !== "function" && moduleIdIndex < allModules.length) {
890
+ moduleIdIndex++;
891
+ }
892
+ moduleInit = allModules[moduleIdIndex];
970
893
  }
894
+ } else {
895
+ moduleInit = allModules.find(
896
+ (bundleEntry) => typeof bundleEntry === "object" && bundleEntry !== null && moduleId in bundleEntry
897
+ )?.[moduleId];
971
898
  }
972
- }
973
-
974
- // src/shared/client/polyfill.tsx
975
- var import_jsx_runtime = (
976
- // eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text
977
- require("react/jsx-runtime")
978
- );
979
- function applyBundleUrlToSrc(bundle, src) {
980
- const self = globalThis;
981
- if (self.__remote_bundle_url__?.[bundle]?.origin === location.origin) {
982
- return src;
899
+ const exports = {};
900
+ const moduleExports = { exports };
901
+ if (!self.__remote_components_turbopack_modules__) {
902
+ self.__remote_components_turbopack_modules__ = {};
983
903
  }
984
- const { assetPrefix, path } = /^(?<assetPrefix>.*?)\/_next\/(?<path>.*)/.exec(src)?.groups ?? {};
985
- if (!path) {
986
- return new URL(src, self.__remote_bundle_url__?.[bundle]?.origin).href;
904
+ if (!self.__remote_components_turbopack_modules__[bundle]) {
905
+ self.__remote_components_turbopack_modules__[bundle] = {};
987
906
  }
988
- return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ""}${assetPrefix}/_next/${path}`;
989
- }
990
- function applyBundleUrlToImagePropsSrc(bundle, src) {
991
- if (typeof src === "string") {
992
- return applyBundleUrlToSrc(bundle, src);
907
+ if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
908
+ return self.__remote_components_turbopack_modules__[bundle][moduleId];
993
909
  }
994
- const propSrc = src;
995
- return applyBundleUrlToSrc(bundle, propSrc.src);
996
- }
997
- var imageImpl = (bundle) => function RemoteImage({
998
- fill: _fill,
999
- loader: _loader,
1000
- quality: _quality,
1001
- priority: _priority,
1002
- loading: _loading,
1003
- placeholder: _placeholder,
1004
- blurDataURL: _blurDataURL,
1005
- unoptimized: _unoptimized,
1006
- overrideSrc: _overrideSrc,
1007
- src,
1008
- ...props
1009
- }) {
1010
- const newSrc = applyBundleUrlToImagePropsSrc(
1011
- bundle,
1012
- typeof src === "string" ? src : src.src
1013
- );
1014
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1015
- "img",
910
+ if (typeof moduleInit !== "function") {
911
+ throw new Error(
912
+ `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
913
+ );
914
+ }
915
+ self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
916
+ if (!self.__remote_components_turbopack_global__) {
917
+ self.__remote_components_turbopack_global__ = {};
918
+ }
919
+ if (!self.__remote_components_turbopack_global__[bundle]) {
920
+ self.__remote_components_turbopack_global__[bundle] = {};
921
+ }
922
+ moduleInit(
1016
923
  {
1017
- decoding: "async",
1018
- style: { color: "transparent" },
1019
- ...props,
1020
- src: newSrc,
1021
- suppressHydrationWarning: true
1022
- }
1023
- );
1024
- };
1025
- function sharedPolyfills(shared) {
1026
- const self = globalThis;
1027
- const polyfill = {
1028
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
1029
- useRouter() {
1030
- return {
1031
- push: (routerUrl) => {
1032
- history.pushState({}, "", routerUrl);
1033
- },
1034
- replace: (routerUrl) => {
1035
- history.replaceState({}, "", routerUrl);
1036
- },
1037
- back: () => {
1038
- history.back();
1039
- }
1040
- };
1041
- },
1042
- usePathname() {
1043
- return location.pathname;
1044
- },
1045
- useParams() {
1046
- return {};
1047
- },
1048
- useSearchParams() {
1049
- return new URLSearchParams(location.search);
1050
- },
1051
- useSelectedLayoutSegment() {
1052
- return null;
1053
- },
1054
- useSelectedLayoutSegments() {
1055
- return [];
924
+ // HMR not implemented for Remote Components
925
+ k: {
926
+ register() {
927
+ },
928
+ registerExports() {
929
+ },
930
+ signature() {
931
+ return (fn) => {
932
+ return fn;
933
+ };
934
+ }
1056
935
  },
1057
- __esModule: true
1058
- })),
1059
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
1060
- default: ({
1061
- scroll: _,
1062
- replace,
1063
- prefetch,
1064
- onNavigate,
1065
- children,
1066
- ...props
1067
- }) => {
1068
- if (prefetch) {
1069
- console.warn(
1070
- "Next.js Link prefetch is not supported in remote components"
1071
- );
936
+ // esm
937
+ s(bindings, esmId) {
938
+ let mod = exports;
939
+ if (typeof esmId === "string" || typeof esmId === "number") {
940
+ if (!self.__remote_components_turbopack_modules__) {
941
+ self.__remote_components_turbopack_modules__ = {};
942
+ }
943
+ if (!self.__remote_components_turbopack_modules__[bundle]) {
944
+ self.__remote_components_turbopack_modules__[bundle] = {};
945
+ }
946
+ if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
947
+ self.__remote_components_turbopack_modules__[bundle][esmId] = {};
948
+ }
949
+ mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1072
950
  }
1073
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1074
- "a",
1075
- {
1076
- ...props,
1077
- href: props.href,
1078
- onClick: (e) => {
1079
- e.preventDefault();
1080
- let preventDefaulted = false;
1081
- e.preventDefault = () => {
1082
- preventDefaulted = true;
1083
- e.defaultPrevented = true;
1084
- };
1085
- if (typeof props.onClick === "function") {
1086
- props.onClick(e);
1087
- }
1088
- onNavigate?.(e);
1089
- if (preventDefaulted) {
1090
- return;
1091
- }
1092
- if (replace) {
1093
- history.replaceState({}, "", props.href);
951
+ Object.defineProperty(mod, "__esModule", { value: true });
952
+ if (Array.isArray(bindings)) {
953
+ let i = 0;
954
+ while (i < bindings.length) {
955
+ const propName = bindings[i++];
956
+ const tagOrFunc = bindings[i++];
957
+ if (typeof tagOrFunc === "number") {
958
+ Object.defineProperty(mod, propName, {
959
+ value: bindings[i++],
960
+ enumerable: true,
961
+ writable: false
962
+ });
963
+ } else {
964
+ const getterFn = tagOrFunc;
965
+ if (typeof bindings[i] === "function") {
966
+ const setterFn = bindings[i++];
967
+ Object.defineProperty(mod, propName, {
968
+ get: getterFn,
969
+ set: setterFn,
970
+ enumerable: true
971
+ });
1094
972
  } else {
1095
- history.pushState({}, "", props.href);
973
+ Object.defineProperty(mod, propName, {
974
+ get: getterFn,
975
+ enumerable: true
976
+ });
1096
977
  }
1097
- },
1098
- suppressHydrationWarning: true,
1099
- children: children ?? null
978
+ }
1100
979
  }
1101
- );
980
+ }
1102
981
  },
1103
- useLinkStatus() {
1104
- return { pending: false };
982
+ // import
983
+ i(importId) {
984
+ let mod;
985
+ if (typeof importId === "string") {
986
+ const { exportSource, exportName } = /\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(
987
+ importId
988
+ )?.groups ?? {};
989
+ const normalizedId = importId.replace(
990
+ /\s+<export(?<specifier>.*)>$/,
991
+ ""
992
+ );
993
+ mod = self.__webpack_require__?.(
994
+ `[${bundle}] ${normalizedId}`
995
+ );
996
+ if (exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
997
+ if (exportSource === "*") {
998
+ mod[exportName] = mod;
999
+ } else {
1000
+ mod[exportName] = mod[exportSource];
1001
+ }
1002
+ }
1003
+ } else {
1004
+ mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1005
+ }
1006
+ if (typeof mod !== "object") {
1007
+ mod = { default: mod };
1008
+ } else if (!("default" in mod) && // eslint-disable-next-line @typescript-eslint/no-base-to-string
1009
+ mod.toString() !== "[object Module]") {
1010
+ try {
1011
+ mod.default = mod;
1012
+ } catch {
1013
+ }
1014
+ }
1015
+ return mod;
1105
1016
  },
1106
- __esModule: true
1107
- })),
1108
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
1109
- default: () => {
1110
- throw new Error("Next.js <Form> component not implemented");
1017
+ // require
1018
+ r(requireId) {
1019
+ return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1111
1020
  },
1112
- __esModule: true
1113
- })),
1114
- "next/dist/client/image-component": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
1115
- Image: imageImpl(bundle),
1116
- __esModule: true
1117
- })),
1118
- "next/image": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
1119
- default: imageImpl(bundle),
1120
- getImageProps: (_imgProps) => {
1021
+ // value exports
1022
+ v(value) {
1023
+ if (typeof value === "function") {
1024
+ exports.default = value((vid) => {
1025
+ return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1026
+ });
1027
+ } else {
1028
+ moduleExports.exports = value;
1029
+ }
1030
+ },
1031
+ // async module initializer
1032
+ async a(mod) {
1033
+ let result;
1034
+ await mod(
1035
+ () => {
1036
+ },
1037
+ (value) => result = value
1038
+ );
1039
+ exports.default = result;
1040
+ },
1041
+ // async module loader
1042
+ async A(Aid) {
1043
+ const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1044
+ return mod.default(
1045
+ (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1046
+ );
1047
+ },
1048
+ // chunk loader
1049
+ l(url) {
1050
+ const moduleInitIndex = allModules.indexOf(moduleInit);
1051
+ if (moduleInitIndex !== -1) {
1052
+ const scriptIndex = allModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
1053
+ if (scriptIndex !== -1) {
1054
+ const script = allModules[scriptIndex];
1055
+ const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1056
+ const nextIndex = scriptSrc.indexOf("/_next");
1057
+ const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1058
+ const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1059
+ return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1060
+ }
1061
+ }
1121
1062
  throw new Error(
1122
- "Next.js getImageProps() is not implemented in remote components"
1063
+ `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1123
1064
  );
1124
1065
  },
1125
- __esModule: true
1126
- })),
1127
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
1128
- // TODO: implement <Script> component for non-Next.js host applications
1129
- // do not throw an error for now
1130
- default: () => null,
1131
- __esModule: true
1132
- })),
1133
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
1134
- // TODO: incomplete implementation
1135
- Promise.resolve({
1136
- useRouter() {
1137
- return {
1138
- push: (routerUrl) => {
1139
- history.pushState({}, "", routerUrl);
1140
- },
1141
- replace: (routerUrl) => {
1142
- history.replaceState({}, "", routerUrl);
1143
- },
1144
- back: () => {
1145
- history.back();
1066
+ // global
1067
+ g: self.__remote_components_turbopack_global__[bundle],
1068
+ m: moduleExports,
1069
+ e: exports
1070
+ },
1071
+ moduleExports,
1072
+ exports
1073
+ );
1074
+ if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1075
+ self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1076
+ }
1077
+ return moduleExports.exports;
1078
+ }
1079
+
1080
+ // src/shared/client/component-loader.ts
1081
+ async function loadRemoteComponent({
1082
+ url,
1083
+ name,
1084
+ rscName,
1085
+ bundle,
1086
+ route = "/",
1087
+ runtime = "webpack",
1088
+ data,
1089
+ nextData,
1090
+ scripts = [],
1091
+ shared = Promise.resolve({}),
1092
+ remoteShared = {},
1093
+ container
1094
+ }) {
1095
+ try {
1096
+ if (runtime === "webpack") {
1097
+ const self = globalThis;
1098
+ if (!self.__DISABLE_WEBPACK_EXEC__) {
1099
+ self.__DISABLE_WEBPACK_EXEC__ = {};
1100
+ }
1101
+ self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
1102
+ await loadScripts(scripts);
1103
+ }
1104
+ const hostShared = await shared;
1105
+ await setupWebpackRuntime(
1106
+ runtime,
1107
+ scripts,
1108
+ url,
1109
+ bundle,
1110
+ hostShared,
1111
+ remoteShared
1112
+ );
1113
+ if (bundle) {
1114
+ const resolve = {
1115
+ "/react/index.js": React,
1116
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1117
+ "/react/jsx-runtime.js": JSXRuntime,
1118
+ "/react-dom/index.js": ReactDOM,
1119
+ "/react-dom/client.js": ReactDOMClient,
1120
+ ...Object.entries(remoteShared).reduce(
1121
+ (acc, [key, value]) => {
1122
+ if (typeof hostShared[value] !== "undefined") {
1123
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1146
1124
  }
1147
- };
1148
- },
1149
- __esModule: true
1150
- })
1151
- )),
1152
- "next/dist/build/polyfills/process": () => Promise.resolve({
1153
- default: {
1154
- env: {
1155
- NODE_ENV: "production"
1125
+ return acc;
1126
+ },
1127
+ {}
1128
+ )
1129
+ };
1130
+ await Promise.all(
1131
+ Object.entries(resolve).map(async ([key, value]) => {
1132
+ if (typeof value === "function") {
1133
+ resolve[key] = await value(bundle);
1134
+ }
1135
+ return Promise.resolve(value);
1136
+ })
1137
+ );
1138
+ applySharedModules(bundle, resolve);
1139
+ }
1140
+ if (data.length > 0) {
1141
+ return await loadRSCComponent(rscName ?? name, data);
1142
+ } else if (nextData) {
1143
+ return loadNextPagesComponent(bundle, route, nextData, name, container);
1144
+ }
1145
+ return loadRSCComponent(rscName ?? name, [`0:[null]
1146
+ `]);
1147
+ } catch (error) {
1148
+ return {
1149
+ component: null,
1150
+ error: new RemoteComponentsError(
1151
+ `Failed to load remote component "${name}".`,
1152
+ {
1153
+ cause: error instanceof Error ? error : new Error(String(error))
1156
1154
  }
1157
- },
1158
- __esModule: true
1159
- })
1160
- };
1161
- polyfill["next/navigation"] = polyfill["next/dist/client/components/navigation"];
1162
- polyfill["next/link"] = polyfill["next/dist/client/app-dir/link"];
1163
- polyfill["next/form"] = polyfill["next/dist/client/app-dir/form"];
1164
- polyfill["next/dist/api/image"] = polyfill["next/dist/client/image-component"];
1165
- polyfill["next/script"] = polyfill["next/dist/client/script"];
1166
- return polyfill;
1155
+ )
1156
+ };
1157
+ }
1158
+ }
1159
+ async function loadRSCComponent(rscName, data) {
1160
+ let createFromReadableStream;
1161
+ try {
1162
+ const { createFromReadableStream: _createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1163
+ createFromReadableStream = _createFromReadableStream;
1164
+ } catch {
1165
+ const {
1166
+ default: { createFromReadableStream: _createFromReadableStream }
1167
+ } = await import("react-server-dom-webpack/client.browser");
1168
+ createFromReadableStream = _createFromReadableStream;
1169
+ }
1170
+ if (typeof createFromReadableStream !== "function") {
1171
+ throw new RemoteComponentsError(
1172
+ 'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
1173
+ );
1174
+ }
1175
+ const stream = createRSCStream(rscName, data);
1176
+ const component = createFromReadableStream(stream);
1177
+ return { component };
1178
+ }
1179
+ function loadNextPagesComponent(bundle, route, nextData, name, container) {
1180
+ const { Component, App } = nextClientPagesLoader(bundle, route, container);
1181
+ if (!Component) {
1182
+ throw new RemoteComponentsError(
1183
+ `Remote Component "${name}" is trying to load the component for route "${route}" but it is not available.`
1184
+ );
1185
+ }
1186
+ const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
1187
+ return { component };
1167
1188
  }
1168
1189
 
1169
- // src/shared/client/apply-origin.ts
1170
- var tagNames = [
1171
- "img",
1172
- "source",
1173
- "video",
1174
- "audio",
1175
- "track",
1176
- "iframe",
1177
- "embed",
1178
- "script",
1179
- "link"
1190
+ // src/shared/client/set-attributes-from-props.ts
1191
+ var DOMAttributeNames = {
1192
+ acceptCharset: "accept-charset",
1193
+ className: "class",
1194
+ htmlFor: "for",
1195
+ httpEquiv: "http-equiv",
1196
+ noModule: "noModule"
1197
+ };
1198
+ var ignoreProps = [
1199
+ "onLoad",
1200
+ "onReady",
1201
+ "dangerouslySetInnerHTML",
1202
+ "children",
1203
+ "onError",
1204
+ "strategy",
1205
+ "stylesheets"
1180
1206
  ];
1181
- function applyOriginToNodes(doc, url) {
1182
- if (url.origin !== location.origin) {
1183
- const nodes = doc.querySelectorAll(
1184
- tagNames.map(
1185
- (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
1186
- ).join(",")
1187
- );
1188
- nodes.forEach((node) => {
1189
- if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
1190
- node.src = new URL(node.getAttribute("src") ?? "/", url).href;
1191
- }
1192
- if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
1193
- node.setAttribute(
1194
- "href",
1195
- new URL(node.getAttribute("href") ?? "/", url).href
1207
+ function isBooleanScriptAttribute(attr) {
1208
+ return ["async", "defer", "noModule"].includes(attr);
1209
+ }
1210
+ function setAttributesFromProps(el, props) {
1211
+ for (const [p, value] of Object.entries(props)) {
1212
+ if (!Object.hasOwn(props, p))
1213
+ continue;
1214
+ if (ignoreProps.includes(p))
1215
+ continue;
1216
+ if (value === void 0) {
1217
+ continue;
1218
+ }
1219
+ const attr = DOMAttributeNames[p] || p.toLowerCase();
1220
+ if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
1221
+ el[attr] = Boolean(value);
1222
+ } else {
1223
+ el.setAttribute(attr, String(value));
1224
+ }
1225
+ if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
1226
+ el.setAttribute(attr, "");
1227
+ el.removeAttribute(attr);
1228
+ }
1229
+ }
1230
+ }
1231
+
1232
+ // src/shared/client/static-loader.ts
1233
+ async function loadStaticRemoteComponent(scripts, url) {
1234
+ const self = globalThis;
1235
+ if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1236
+ self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1237
+ }
1238
+ if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1239
+ self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1240
+ }
1241
+ const mountUnmountSets = await Promise.all(
1242
+ scripts.map(async (script) => {
1243
+ try {
1244
+ let src = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
1245
+ if (!src && script.textContent) {
1246
+ const blob = new Blob(
1247
+ [
1248
+ script.textContent.replace(
1249
+ /import\.meta\.url/g,
1250
+ JSON.stringify(url)
1251
+ )
1252
+ ],
1253
+ {
1254
+ type: "text/javascript"
1255
+ }
1256
+ );
1257
+ src = URL.createObjectURL(blob);
1258
+ }
1259
+ const mod = await import(
1260
+ /* @vite-ignore */
1261
+ /* webpackIgnore: true */
1262
+ new URL(src, url).href
1196
1263
  );
1197
- }
1198
- if (node.hasAttribute("srcset")) {
1199
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
1200
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1201
- if (!urlPart)
1202
- return entry;
1203
- const absoluteUrl = new URL(urlPart, url).href;
1204
- return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
1205
- }).join(", ");
1206
- if (srcSet) {
1207
- node.setAttribute("srcset", srcSet);
1264
+ if (src.startsWith("blob:")) {
1265
+ URL.revokeObjectURL(src);
1208
1266
  }
1209
- }
1210
- if (node.hasAttribute("imagesrcset")) {
1211
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
1212
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1213
- if (!urlPart)
1214
- return entry;
1215
- const absoluteUrl = new URL(urlPart, url).href;
1216
- return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
1217
- }).join(", ");
1218
- if (srcSet) {
1219
- node.setAttribute("imagesrcset", srcSet);
1267
+ if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1268
+ if (!self.__remote_script_entrypoint_mount__) {
1269
+ self.__remote_script_entrypoint_mount__ = {};
1270
+ }
1271
+ if (!self.__remote_script_entrypoint_mount__[url.href]) {
1272
+ self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1273
+ }
1274
+ self.__remote_script_entrypoint_mount__[url.href]?.add(
1275
+ mod.mount || mod.default?.mount || (() => {
1276
+ })
1277
+ );
1278
+ }
1279
+ if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1280
+ if (!self.__remote_script_entrypoint_unmount__) {
1281
+ self.__remote_script_entrypoint_unmount__ = {};
1282
+ }
1283
+ if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1284
+ self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1285
+ }
1286
+ self.__remote_script_entrypoint_unmount__[url.href]?.add(
1287
+ mod.unmount || mod.default?.unmount || (() => {
1288
+ })
1289
+ );
1220
1290
  }
1291
+ return {
1292
+ mount: mod.mount || mod.default?.mount,
1293
+ unmount: mod.unmount || mod.default?.unmount
1294
+ };
1295
+ } catch (e) {
1296
+ console.error(
1297
+ new RemoteComponentsError(
1298
+ `Error loading remote component script from "${script.src || url.href}".`,
1299
+ { cause: e }
1300
+ )
1301
+ );
1302
+ return {
1303
+ mount: void 0,
1304
+ unmount: void 0
1305
+ };
1221
1306
  }
1222
- });
1223
- }
1307
+ })
1308
+ );
1309
+ return mountUnmountSets.reduce(
1310
+ (acc, { mount, unmount }) => {
1311
+ if (typeof mount === "function") {
1312
+ acc.mount.add(mount);
1313
+ }
1314
+ if (typeof unmount === "function") {
1315
+ acc.unmount.add(unmount);
1316
+ }
1317
+ return acc;
1318
+ },
1319
+ {
1320
+ mount: /* @__PURE__ */ new Set(),
1321
+ unmount: /* @__PURE__ */ new Set()
1322
+ }
1323
+ );
1224
1324
  }
1225
1325
 
1226
1326
  // src/shared/ssr/fetch-headers.ts
@@ -1242,7 +1342,10 @@ function remoteFetchHeaders(additionalHeaders) {
1242
1342
  }
1243
1343
 
1244
1344
  // src/react/index.tsx
1245
- var import_jsx_runtime2 = require("react/jsx-runtime");
1345
+ var import_jsx_runtime2 = (
1346
+ // TODO: remove wrapper div by converting HTML to RSC or React tree
1347
+ require("react/jsx-runtime")
1348
+ );
1246
1349
  var import_react2 = require("react");
1247
1350
  function getRemoteComponentHtml(html) {
1248
1351
  if (typeof document === "undefined")
@@ -1256,7 +1359,7 @@ function getRemoteComponentHtml(html) {
1256
1359
  return ssrRemoteComponentContainer.innerHTML;
1257
1360
  }
1258
1361
  const remoteComponentContainer = temp.querySelectorAll(
1259
- `div[data-bundle][data-route][data-runtime][id^="__vercel_remote_component"],div[data-bundle][data-route],div#__next`
1362
+ `div[data-bundle][data-route][data-runtime][id^="__vercel_remote_component"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
1260
1363
  );
1261
1364
  if (remoteComponentContainer.length > 0) {
1262
1365
  return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
@@ -1321,6 +1424,10 @@ function RemoteComponent({
1321
1424
  );
1322
1425
  const prevSrcRef = (0, import_react.useRef)(null);
1323
1426
  const componentHydrationHtml = (0, import_react.useRef)(null);
1427
+ const prevIsRemoteComponentRef = (0, import_react.useRef)(false);
1428
+ const prevUrlRef = (0, import_react.useRef)(null);
1429
+ const prevRemoteComponentContainerRef = (0, import_react.useRef)(null);
1430
+ const unmountRef = (0, import_react.useRef)(null);
1324
1431
  (0, import_react.useLayoutEffect)(() => {
1325
1432
  if (childrenRef.current.length > 0 && remoteComponent) {
1326
1433
  childrenRef.current.forEach((el) => {
@@ -1433,34 +1540,58 @@ function RemoteComponent({
1433
1540
  }
1434
1541
  const parser = new DOMParser();
1435
1542
  const doc = parser.parseFromString(html, "text/html");
1436
- if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`)) {
1543
+ if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(
1544
+ `div[data-bundle][data-route][id^="${name}"]`
1545
+ ) || doc.querySelectorAll("remote-component:not([src])").length > 1 && !doc.querySelector(`remote-component[name="${name}"]`)) {
1437
1546
  throw multipleRemoteComponentsError(url.href);
1438
1547
  }
1439
1548
  const component = doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component
1440
1549
  doc.querySelector("div[data-bundle][data-route]") ?? // fallback to Next.js Pages Router
1441
- doc.querySelector("div#__next");
1550
+ doc.querySelector("div#__next") ?? // fallback to the remote-component web component
1551
+ doc.querySelector(`remote-component[name="${name}"]:not([src])`) ?? doc.querySelector("remote-component:not([src])");
1442
1552
  const nextData = JSON.parse(
1443
1553
  (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
1444
1554
  );
1445
1555
  const remoteName = component?.getAttribute("id")?.replace(/_ssr$/, "") || (nextData ? "__next" : name);
1446
1556
  const rsc = doc.querySelector(`#${remoteName}_rsc`);
1447
1557
  const bundle = component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default";
1558
+ const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
1448
1559
  const metadata = {
1449
1560
  name: remoteName,
1450
1561
  bundle,
1451
- route: component?.getAttribute("data-route") ?? nextData?.page ?? DEFAULT_ROUTE,
1452
- runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_WEBPACK)
1562
+ route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || DEFAULT_ROUTE),
1563
+ runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_SCRIPT)
1453
1564
  };
1454
1565
  const remoteSharedEl = doc.querySelector(
1455
1566
  `#${remoteName}_shared[data-remote-components-shared]`
1456
1567
  );
1457
1568
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
1458
1569
  remoteSharedEl?.remove();
1459
- if (!component || !(rsc || nextData)) {
1570
+ if (!component || !(rsc || nextData || isRemoteComponent)) {
1460
1571
  throw new RemoteComponentsError(
1461
1572
  `Remote Component not found on ${url.href}.${remoteName !== "__vercel_remote_component" ? `The name for the <RemoteComponent> is "${remoteName}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
1462
1573
  );
1463
1574
  }
1575
+ if (prevIsRemoteComponentRef.current) {
1576
+ if (shadowRoot) {
1577
+ shadowRoot.innerHTML = "";
1578
+ }
1579
+ const self = globalThis;
1580
+ const prevUrl = prevUrlRef.current;
1581
+ if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
1582
+ const unmountPromises = Promise.all(
1583
+ Array.from(unmountRef.current ?? []).map(
1584
+ async (unmount) => unmount(
1585
+ shadowRoot ?? prevRemoteComponentContainerRef.current
1586
+ )
1587
+ )
1588
+ );
1589
+ unmountRef.current = null;
1590
+ await unmountPromises;
1591
+ }
1592
+ }
1593
+ prevIsRemoteComponentRef.current = isRemoteComponent;
1594
+ prevUrlRef.current = url;
1464
1595
  applyOriginToNodes(doc, url);
1465
1596
  const links = Array.from(
1466
1597
  doc.querySelectorAll("link[href]")
@@ -1475,64 +1606,64 @@ function RemoteComponent({
1475
1606
  return acc;
1476
1607
  }, {})
1477
1608
  }));
1478
- const scripts = doc.querySelectorAll(
1479
- "script[src],script[data-src]"
1480
- );
1481
- const inlineScripts = doc.querySelectorAll(
1609
+ const scripts = (isRemoteComponent ? component : doc).querySelectorAll("script[src],script[data-src]");
1610
+ const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
1482
1611
  "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
1483
1612
  );
1484
- const self = globalThis;
1485
- const prevNextScripts = self.__next_s;
1486
- const nextScripts = [];
1487
- self.__next_s = nextScripts;
1488
- await Promise.all(
1489
- Array.from(inlineScripts).filter(
1490
- (script) => !(script.id.endsWith("_shared") && script.getAttribute("type") === "application/json" && typeof script.getAttribute(
1491
- "data-remote-components-shared"
1492
- ) === "string")
1493
- ).map((script) => {
1494
- return new Promise((resolve) => {
1495
- if (script.textContent && !script.textContent.includes("self.__next_f=") && !script.textContent.includes("self.__next_f.push")) {
1496
- if (!script.getAttribute("type") || script.getAttribute("type") === "text/javascript" || script.getAttribute("type") === "application/javascript") {
1497
- const newScript = document.createElement("script");
1498
- const blob = new Blob([script.textContent], {
1499
- type: "application/javascript"
1500
- });
1501
- const blobUrl = URL.createObjectURL(blob);
1502
- newScript.onload = () => {
1613
+ if (!isRemoteComponent) {
1614
+ const self = globalThis;
1615
+ const prevNextScripts = self.__next_s;
1616
+ const nextScripts = [];
1617
+ self.__next_s = nextScripts;
1618
+ await Promise.all(
1619
+ Array.from(inlineScripts).filter(
1620
+ (script) => !(script.id.endsWith("_shared") && script.getAttribute("type") === "application/json" && typeof script.getAttribute(
1621
+ "data-remote-components-shared"
1622
+ ) === "string")
1623
+ ).map((script) => {
1624
+ return new Promise((resolve) => {
1625
+ if (script.textContent && !script.textContent.includes("self.__next_f=") && !script.textContent.includes("self.__next_f.push")) {
1626
+ if (!script.getAttribute("type") || script.getAttribute("type") === "text/javascript" || script.getAttribute("type") === "application/javascript") {
1627
+ const newScript = document.createElement("script");
1628
+ const blob = new Blob([script.textContent], {
1629
+ type: "application/javascript"
1630
+ });
1631
+ const blobUrl = URL.createObjectURL(blob);
1632
+ newScript.onload = () => {
1633
+ resolve(void 0);
1634
+ URL.revokeObjectURL(blobUrl);
1635
+ newScript.remove();
1636
+ };
1637
+ newScript.onerror = () => {
1638
+ URL.revokeObjectURL(blobUrl);
1639
+ newScript.remove();
1640
+ resolve(void 0);
1641
+ };
1642
+ newScript.src = blobUrl;
1643
+ document.body.appendChild(newScript);
1644
+ } else {
1503
1645
  resolve(void 0);
1504
- URL.revokeObjectURL(blobUrl);
1505
- newScript.remove();
1506
- };
1507
- newScript.onerror = () => {
1508
- URL.revokeObjectURL(blobUrl);
1509
- newScript.remove();
1510
- resolve(void 0);
1511
- };
1512
- newScript.src = blobUrl;
1513
- document.body.appendChild(newScript);
1646
+ document.body.appendChild(script);
1647
+ }
1514
1648
  } else {
1515
1649
  resolve(void 0);
1516
- document.body.appendChild(script);
1517
1650
  }
1518
- } else {
1519
- resolve(void 0);
1520
- }
1521
- });
1522
- })
1523
- );
1524
- nextScripts.forEach(([scriptSrc, props]) => {
1525
- const script = document.createElement("script");
1526
- if (scriptSrc) {
1527
- script.src = scriptSrc;
1528
- }
1529
- if (typeof props.children === "string") {
1530
- script.textContent = props.children;
1531
- }
1532
- setAttributesFromProps(script, props);
1533
- document.head.appendChild(script);
1534
- });
1535
- self.__next_s = prevNextScripts;
1651
+ });
1652
+ })
1653
+ );
1654
+ nextScripts.forEach(([scriptSrc, props]) => {
1655
+ const script = document.createElement("script");
1656
+ if (scriptSrc) {
1657
+ script.src = scriptSrc;
1658
+ }
1659
+ if (typeof props.children === "string") {
1660
+ script.textContent = props.children;
1661
+ }
1662
+ setAttributesFromProps(script, props);
1663
+ document.head.appendChild(script);
1664
+ });
1665
+ self.__next_s = prevNextScripts;
1666
+ }
1536
1667
  let rscName;
1537
1668
  if (rsc) {
1538
1669
  rscName = `__remote_component_rsc_${escapeString(url.href)}_${escapeString(remoteName)}`;
@@ -1549,7 +1680,11 @@ function RemoteComponent({
1549
1680
  url: url.href,
1550
1681
  data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
1551
1682
  };
1552
- componentHydrationHtml.current = Array.from(doc.querySelectorAll("link,style")).map((link) => link.outerHTML).join("") + component.innerHTML;
1683
+ componentHydrationHtml.current = `${Array.from(
1684
+ doc.querySelectorAll("link,style")
1685
+ ).map((link) => link.outerHTML).join(
1686
+ ""
1687
+ )}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
1553
1688
  const userShared = await shared;
1554
1689
  if ("__remote_components_missing_shared__" in userShared) {
1555
1690
  userShared.__remote_components_missing_shared__().catch((e) => {
@@ -1560,48 +1695,88 @@ function RemoteComponent({
1560
1695
  remoteShared.__remote_components_missing_shared__
1561
1696
  );
1562
1697
  }
1563
- const result = await loadRemoteComponent({
1564
- url: new URL(url, location.origin),
1565
- name: remoteName,
1566
- rscName,
1567
- bundle,
1568
- route: metadata.route,
1569
- runtime: metadata.runtime,
1570
- data: newData.data,
1571
- nextData,
1572
- scripts: Array.from(scripts).map((script) => {
1573
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
1574
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
1575
- scriptSrc
1576
- )?.groups ?? {
1577
- prefix: void 0,
1578
- id: scriptSrc
1579
- };
1580
- return {
1581
- src: new URL(
1582
- `${prefix ?? ""}${path}`.replace(
1583
- /(?<char>[^:])(?<double>\/\/)/g,
1584
- "$1/"
1585
- ),
1586
- url
1587
- ).href
1588
- };
1589
- }),
1590
- shared: {
1591
- ...sharedPolyfills(userShared),
1592
- ...userShared
1593
- },
1594
- remoteShared,
1595
- container: shadowRoot
1596
- });
1597
- if (rsc) {
1598
- rsc.remove();
1599
- }
1600
- setData(newData);
1601
- if (result.error) {
1602
- setRemoteComponent(result.error);
1698
+ if (isRemoteComponent) {
1699
+ setData(newData);
1700
+ if (shadowRoot) {
1701
+ let shadowRootHtml = component.innerHTML;
1702
+ if (reset) {
1703
+ shadowRootHtml = `<style data-remote-components-reset="">:host { all: initial; }</style>${shadowRootHtml}`;
1704
+ }
1705
+ shadowRoot.innerHTML = shadowRootHtml;
1706
+ setRemoteComponent(null);
1707
+ const { mount, unmount } = await loadStaticRemoteComponent(
1708
+ Array.from(shadowRoot.querySelectorAll("script")),
1709
+ url
1710
+ );
1711
+ unmountRef.current = unmount;
1712
+ await Promise.all(
1713
+ Array.from(mount).map((mountFn) => mountFn(shadowRoot))
1714
+ );
1715
+ } else if (isolate === false) {
1716
+ setRemoteComponent(
1717
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1718
+ "div",
1719
+ {
1720
+ dangerouslySetInnerHTML: { __html: component.innerHTML },
1721
+ ref: prevRemoteComponentContainerRef
1722
+ }
1723
+ )
1724
+ );
1725
+ const { mount, unmount } = await loadStaticRemoteComponent(
1726
+ Array.from(component.querySelectorAll("script")),
1727
+ url
1728
+ );
1729
+ unmountRef.current = unmount;
1730
+ await Promise.all(
1731
+ Array.from(mount).map(
1732
+ (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
1733
+ )
1734
+ );
1735
+ }
1603
1736
  } else {
1604
- setRemoteComponent(result.component);
1737
+ const result = await loadRemoteComponent({
1738
+ url: new URL(url, location.origin),
1739
+ name: remoteName,
1740
+ rscName,
1741
+ bundle,
1742
+ route: metadata.route,
1743
+ runtime: metadata.runtime,
1744
+ data: newData.data,
1745
+ nextData,
1746
+ scripts: Array.from(scripts).map((script) => {
1747
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
1748
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
1749
+ scriptSrc
1750
+ )?.groups ?? {
1751
+ prefix: void 0,
1752
+ id: scriptSrc
1753
+ };
1754
+ return {
1755
+ src: new URL(
1756
+ `${prefix ?? ""}${path}`.replace(
1757
+ /(?<char>[^:])(?<double>\/\/)/g,
1758
+ "$1/"
1759
+ ),
1760
+ url
1761
+ ).href
1762
+ };
1763
+ }),
1764
+ shared: {
1765
+ ...sharedPolyfills(userShared),
1766
+ ...userShared
1767
+ },
1768
+ remoteShared,
1769
+ container: shadowRoot
1770
+ });
1771
+ if (rsc) {
1772
+ rsc.remove();
1773
+ }
1774
+ setData(newData);
1775
+ if (result.error) {
1776
+ setRemoteComponent(result.error);
1777
+ } else {
1778
+ setRemoteComponent(result.component);
1779
+ }
1605
1780
  }
1606
1781
  } catch (error) {
1607
1782
  setRemoteComponent(error);
@@ -1616,7 +1791,8 @@ function RemoteComponent({
1616
1791
  name,
1617
1792
  shared,
1618
1793
  shadowRoot,
1619
- additionalHeaders
1794
+ additionalHeaders,
1795
+ reset
1620
1796
  ]);
1621
1797
  if (remoteComponent instanceof Error) {
1622
1798
  throw remoteComponent;
@@ -1625,7 +1801,7 @@ function RemoteComponent({
1625
1801
  name: data?.name || name,
1626
1802
  bundle: data?.bundle || "default",
1627
1803
  route: data?.route || DEFAULT_ROUTE,
1628
- runtime: data?.runtime || RUNTIME_WEBPACK
1804
+ runtime: prevIsRemoteComponentRef.current ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
1629
1805
  }) });
1630
1806
  const resetStyle = reset ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { "data-remote-components-reset": "", children: `:host { all: initial; }` }) : null;
1631
1807
  const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react2.createElement)(
@@ -1644,6 +1820,24 @@ function RemoteComponent({
1644
1820
  if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {
1645
1821
  shadowRoot.innerHTML = componentHydrationHtml.current;
1646
1822
  componentHydrationHtml.current = null;
1823
+ if (prevIsRemoteComponentRef.current) {
1824
+ loadStaticRemoteComponent(
1825
+ Array.from(shadowRoot.querySelectorAll("script")),
1826
+ url
1827
+ ).then(({ mount }) => {
1828
+ return Promise.all(
1829
+ Array.from(mount).map((mountFn) => mountFn(shadowRoot))
1830
+ );
1831
+ }).catch((e) => {
1832
+ const error = new RemoteComponentsError(
1833
+ `Error mounting remote component from "${url.href}"`,
1834
+ {
1835
+ cause: e
1836
+ }
1837
+ );
1838
+ setRemoteComponent(error);
1839
+ });
1840
+ }
1647
1841
  }
1648
1842
  if (isolate !== false) {
1649
1843
  const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");