remote-components 0.3.5 → 0.3.7

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 (142) hide show
  1. package/dist/app-63L5THIQ.js +12 -0
  2. package/dist/app-63L5THIQ.js.map +1 -0
  3. package/dist/app-A5QE7XRH.cjs +12 -0
  4. package/dist/app-A5QE7XRH.cjs.map +1 -0
  5. package/dist/chunk-52BJ7VFA.js +202 -0
  6. package/dist/chunk-52BJ7VFA.js.map +1 -0
  7. package/dist/chunk-AWWWK2ZY.cjs +670 -0
  8. package/dist/chunk-AWWWK2ZY.cjs.map +1 -0
  9. package/dist/chunk-CTUJSWCM.js +215 -0
  10. package/dist/chunk-CTUJSWCM.js.map +1 -0
  11. package/dist/chunk-D5GNZB6O.js +61 -0
  12. package/dist/chunk-D5GNZB6O.js.map +1 -0
  13. package/dist/chunk-ENYGL5CO.js +11 -0
  14. package/dist/chunk-ENYGL5CO.js.map +1 -0
  15. package/dist/chunk-GAXJTFBV.js +20 -0
  16. package/dist/chunk-GAXJTFBV.js.map +1 -0
  17. package/dist/chunk-GBFUPMMI.js +670 -0
  18. package/dist/chunk-GBFUPMMI.js.map +1 -0
  19. package/dist/chunk-I47KE3EC.cjs +703 -0
  20. package/dist/chunk-I47KE3EC.cjs.map +1 -0
  21. package/dist/chunk-KE7QPAQ4.cjs +21 -0
  22. package/dist/chunk-KE7QPAQ4.cjs.map +1 -0
  23. package/dist/chunk-LCXO7BUY.cjs +57 -0
  24. package/dist/chunk-LCXO7BUY.cjs.map +1 -0
  25. package/dist/chunk-LQ7VQ74E.js +155 -0
  26. package/dist/chunk-LQ7VQ74E.js.map +1 -0
  27. package/dist/chunk-N5VQR2PW.cjs +215 -0
  28. package/dist/chunk-N5VQR2PW.cjs.map +1 -0
  29. package/dist/chunk-NZAB7REE.js +703 -0
  30. package/dist/chunk-NZAB7REE.js.map +1 -0
  31. package/dist/chunk-QKB74MLO.js +709 -0
  32. package/dist/chunk-QKB74MLO.js.map +1 -0
  33. package/dist/chunk-RJW3EZJP.cjs +709 -0
  34. package/dist/chunk-RJW3EZJP.cjs.map +1 -0
  35. package/dist/chunk-RUWR74XQ.cjs +152 -0
  36. package/dist/chunk-RUWR74XQ.cjs.map +1 -0
  37. package/dist/chunk-S2A4TFLS.js +152 -0
  38. package/dist/chunk-S2A4TFLS.js.map +1 -0
  39. package/dist/chunk-SHFJ5OQA.cjs +11 -0
  40. package/dist/chunk-SHFJ5OQA.cjs.map +1 -0
  41. package/dist/chunk-SJM7AAGU.js +358 -0
  42. package/dist/chunk-SJM7AAGU.js.map +1 -0
  43. package/dist/chunk-SZFCBE54.js +57 -0
  44. package/dist/chunk-SZFCBE54.js.map +1 -0
  45. package/dist/chunk-T64P7BAG.cjs +202 -0
  46. package/dist/chunk-T64P7BAG.cjs.map +1 -0
  47. package/dist/chunk-TCFLEBQM.cjs +20 -0
  48. package/dist/chunk-TCFLEBQM.cjs.map +1 -0
  49. package/dist/chunk-TZT7DLO5.cjs +155 -0
  50. package/dist/chunk-TZT7DLO5.cjs.map +1 -0
  51. package/dist/chunk-X6W464D6.cjs +358 -0
  52. package/dist/chunk-X6W464D6.cjs.map +1 -0
  53. package/dist/chunk-X6YKUJKH.js +21 -0
  54. package/dist/chunk-X6YKUJKH.js.map +1 -0
  55. package/dist/chunk-Z2SLBFQL.cjs +61 -0
  56. package/dist/chunk-Z2SLBFQL.cjs.map +1 -0
  57. package/dist/config/nextjs.cjs +74 -355
  58. package/dist/config/nextjs.cjs.map +1 -1
  59. package/dist/config/nextjs.js +25 -271
  60. package/dist/config/nextjs.js.map +1 -1
  61. package/dist/config/webpack.cjs +12 -240
  62. package/dist/config/webpack.cjs.map +1 -1
  63. package/dist/config/webpack.js +6 -207
  64. package/dist/config/webpack.js.map +1 -1
  65. package/dist/host/html.cjs +128 -2494
  66. package/dist/host/html.cjs.map +1 -1
  67. package/dist/host/html.js +45 -2382
  68. package/dist/host/html.js.map +1 -1
  69. package/dist/host/nextjs/app/client-only.cjs +53 -2939
  70. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  71. package/dist/host/nextjs/app/client-only.js +31 -2894
  72. package/dist/host/nextjs/app/client-only.js.map +1 -1
  73. package/dist/host/proxy/client.cjs +8 -38
  74. package/dist/host/proxy/client.cjs.map +1 -1
  75. package/dist/host/proxy/client.js +4 -7
  76. package/dist/host/proxy/client.js.map +1 -1
  77. package/dist/host/proxy.cjs +19 -56
  78. package/dist/host/proxy.cjs.map +1 -1
  79. package/dist/host/proxy.js +8 -20
  80. package/dist/host/proxy.js.map +1 -1
  81. package/dist/host/react.cjs +17 -2870
  82. package/dist/host/react.cjs.map +1 -1
  83. package/dist/host/react.js +13 -2837
  84. package/dist/host/react.js.map +1 -1
  85. package/dist/internal/config/webpack/next-client-pages-loader.cjs +27 -15
  86. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  87. package/dist/internal/config/webpack/next-client-pages-loader.d.ts +3 -5
  88. package/dist/internal/config/webpack/next-client-pages-loader.js +27 -15
  89. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  90. package/dist/internal/host/nextjs/app-client.d.ts +1 -1
  91. package/dist/internal/host/react/context.d.ts +2 -2
  92. package/dist/internal/host/server/fetch-remote-component.cjs +1 -18
  93. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  94. package/dist/internal/host/server/fetch-remote-component.js +1 -18
  95. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  96. package/dist/internal/host/shared/pipeline.d.ts +2 -2
  97. package/dist/internal/runtime/loaders/component-loader.cjs +5 -2
  98. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  99. package/dist/internal/runtime/loaders/component-loader.d.ts +2 -2
  100. package/dist/internal/runtime/loaders/component-loader.js +5 -2
  101. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  102. package/dist/internal/runtime/loaders/static-loader.d.ts +2 -1
  103. package/dist/internal/runtime/namespace.cjs +1 -0
  104. package/dist/internal/runtime/namespace.cjs.map +1 -1
  105. package/dist/internal/runtime/namespace.d.ts +2 -1
  106. package/dist/internal/runtime/namespace.js +1 -0
  107. package/dist/internal/runtime/namespace.js.map +1 -1
  108. package/dist/internal/runtime/turbopack/remote-scope.cjs +1 -5
  109. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  110. package/dist/internal/runtime/turbopack/remote-scope.js +1 -5
  111. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  112. package/dist/internal/runtime/types.d.ts +2 -1
  113. package/dist/internal/utils.cjs +1 -1
  114. package/dist/internal/utils.cjs.map +1 -1
  115. package/dist/internal/utils.d.ts +5 -5
  116. package/dist/internal/utils.js +1 -1
  117. package/dist/internal/utils.js.map +1 -1
  118. package/dist/remote/html.cjs +15 -314
  119. package/dist/remote/html.cjs.map +1 -1
  120. package/dist/remote/html.js +7 -305
  121. package/dist/remote/html.js.map +1 -1
  122. package/dist/remote/middleware.cjs +16 -41
  123. package/dist/remote/middleware.cjs.map +1 -1
  124. package/dist/script-D5AD7HLV.cjs +26 -0
  125. package/dist/script-D5AD7HLV.cjs.map +1 -0
  126. package/dist/script-VPOI7ARP.js +26 -0
  127. package/dist/script-VPOI7ARP.js.map +1 -0
  128. package/dist/{server-handoff-ce13bebc.d.ts → server-handoff-8c89b856.d.ts} +2 -2
  129. package/dist/static-loader-OHSAUD62.js +11 -0
  130. package/dist/static-loader-OHSAUD62.js.map +1 -0
  131. package/dist/static-loader-UDIXK5MV.cjs +11 -0
  132. package/dist/static-loader-UDIXK5MV.cjs.map +1 -0
  133. package/dist/turbopack-5LW6V6IT.js +55 -0
  134. package/dist/turbopack-5LW6V6IT.js.map +1 -0
  135. package/dist/turbopack-KRKECGY2.cjs +55 -0
  136. package/dist/turbopack-KRKECGY2.cjs.map +1 -0
  137. package/dist/{types-59251814.d.ts → types-8b0edd78.d.ts} +7 -0
  138. package/dist/webpack-NPZNXRNL.js +92 -0
  139. package/dist/webpack-NPZNXRNL.js.map +1 -0
  140. package/dist/webpack-TTZDARNY.cjs +92 -0
  141. package/dist/webpack-TTZDARNY.cjs.map +1 -0
  142. package/package.json +9 -2
@@ -1,2841 +1,17 @@
1
- // src/host/react/index.tsx
2
1
  import {
3
- startTransition,
4
- useEffect,
5
- useId,
6
- useLayoutEffect as useLayoutEffect2,
7
- useMemo as useMemo2,
8
- useRef as useRef2,
9
- useState as useState2
10
- } from "react";
11
- import { createPortal } from "react-dom";
12
- import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
13
-
14
- // src/utils/constants.ts
15
- var RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
16
- var CORS_DOCS_URL = "https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components";
17
-
18
- // src/runtime/url/protected-rc-fallback.ts
19
- function isProxiedUrl(url) {
20
- try {
21
- return new URL(url, location.href).pathname === RC_PROTECTED_REMOTE_FETCH_PATHNAME;
22
- } catch {
23
- return false;
24
- }
25
- }
26
-
27
- // src/utils/abort.ts
28
- function isAbortError(error) {
29
- if (error instanceof DOMException && error.name === "AbortError") {
30
- return true;
31
- }
32
- if (error !== null && typeof error === "object" && "name" in error && error.name === "AbortError" && "message" in error && typeof error.message === "string") {
33
- const e = error;
34
- return typeof e.code === "number" || e.constructor?.name === "DOMException";
35
- }
36
- return false;
37
- }
38
-
39
- // src/utils/error.ts
40
- var RemoteComponentsError = class extends Error {
41
- code = "REMOTE_COMPONENTS_ERROR";
42
- constructor(message, options) {
43
- super(message, options);
44
- this.name = "RemoteComponentsError";
45
- }
46
- };
47
- function multipleRemoteComponentsError(url) {
48
- return new RemoteComponentsError(
49
- `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.`
50
- );
51
- }
52
- function failedToFetchRemoteComponentError(url, { status, statusText }, help = "Is the URL correct and accessible?") {
53
- return new RemoteComponentsError(
54
- `Failed to fetch Remote Component from "${url}". ${help}`,
55
- { cause: new Error(`${status} ${statusText}`) }
56
- );
57
- }
58
- async function errorFromFailedFetch(originalUrl, resolvedUrl, res) {
59
- const isProxied = isProxiedUrl(resolvedUrl.href);
60
- if (isProxied && res) {
61
- const body = await res.text().catch(() => "");
62
- return failedProxyFetchError(
63
- originalUrl,
64
- resolvedUrl.href,
65
- res.status,
66
- body
67
- );
68
- }
69
- const fallback = failedToFetchRemoteComponentError(
70
- originalUrl,
71
- res ?? { status: 0, statusText: "No Response" }
72
- );
73
- if (!res)
74
- return fallback;
75
- try {
76
- const body = await res.text();
77
- const parser = new DOMParser();
78
- const doc = parser.parseFromString(body, "text/html");
79
- const errorTemplate = doc.querySelector(
80
- "template[data-next-error-message]"
81
- );
82
- const errorMessage = errorTemplate?.getAttribute("data-next-error-message");
83
- if (errorMessage) {
84
- const error = new RemoteComponentsError(errorMessage);
85
- const errorStack = errorTemplate?.getAttribute("data-next-error-stack");
86
- if (errorStack) {
87
- error.stack = errorStack;
88
- }
89
- return error;
90
- }
91
- } catch (parseError) {
92
- if (isAbortError(parseError))
93
- throw parseError;
94
- }
95
- return fallback;
96
- }
97
- function failedProxiedAssetError(kind, url, resolvedUrl) {
98
- return new RemoteComponentsError(
99
- `Failed to load ${kind} "${url}" via proxy "${resolvedUrl}". Ensure withRemoteComponentsHostProxy middleware is configured, "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" is in the matcher, and the remote URL is included in allowedProxyUrls. See: ${CORS_DOCS_URL}`
100
- );
101
- }
102
- function failedProxyFetchError(originalUrl, proxyUrl, status, responseBody) {
103
- if (status === 404) {
104
- return new RemoteComponentsError(
105
- `Could not proxy the request to "${originalUrl}" \u2014 the proxy endpoint "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" returned 404.
106
-
107
- The host server needs middleware or a route that handles "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}".
108
-
109
- Proxying requires two pieces:
110
- 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>
111
- 2. Middleware or a route for "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" on the host server
112
-
113
- Docs: ${CORS_DOCS_URL}`
114
- );
115
- }
116
- if (status === 403) {
117
- const detail = responseBody ? ` ${responseBody}` : "";
118
- return new RemoteComponentsError(
119
- `Proxied request to "${proxyUrl}" was forbidden.${detail} See: ${CORS_DOCS_URL}`
120
- );
121
- }
122
- return new RemoteComponentsError(
123
- `Proxied request for "${originalUrl}" via "${proxyUrl}" failed with status ${status}. See: ${CORS_DOCS_URL}`
124
- );
125
- }
126
-
127
- // src/utils/logger.ts
128
- var PREFIX = "remote-components";
129
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
130
- function logDebug(location2, message) {
131
- if (DEBUG) {
132
- console.debug(`[${PREFIX}:${location2}]: ${message}`);
133
- }
134
- }
135
- function logWarn(location2, message) {
136
- console.warn(`[${PREFIX}:${location2}]: ${message}`);
137
- }
138
- function logError(location2, message, cause) {
139
- console.error(
140
- new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
141
- cause
142
- })
143
- );
144
- }
145
- function warnCrossOriginFetchError(logLocation, url) {
146
- try {
147
- const parsed = typeof url === "string" ? new URL(url) : url;
148
- if (typeof location === "undefined" || parsed.origin === location.origin) {
149
- return;
150
- }
151
- logWarn(
152
- logLocation,
153
- `Failed to fetch cross-origin resource "${parsed.href}". To load assets from a protected deployment, two steps are required: (1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. See: ${CORS_DOCS_URL}`
154
- );
155
- } catch {
156
- }
157
- }
158
-
159
- // src/host/server/fetch-headers.ts
160
- function remoteFetchHeaders() {
161
- return {
162
- /**
163
- * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.
164
- * If the remote component uses vercel deployment protection, ensure the host and remote vercel
165
- * projects share a common automation bypass secret, and the shared secret is used as the
166
- * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.
167
- */
168
- ...typeof process === "object" && typeof process.env === "object" && typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === "string" ? {
169
- "x-vercel-protection-bypass": process.env.VERCEL_AUTOMATION_BYPASS_SECRET
170
- } : {},
171
- Accept: "text/html"
172
- };
173
- }
174
-
175
- // src/host/server/fetch-with-hooks.ts
176
- async function fetchWithWarning(url, init) {
177
- try {
178
- return await fetch(url, init);
179
- } catch (error) {
180
- warnCrossOriginFetchError("FetchRemoteComponent", url);
181
- throw error;
182
- }
183
- }
184
- async function fetchWithHooks(url, additionalInit, options = {}) {
185
- const {
186
- onRequest,
187
- onResponse,
188
- abortController = new AbortController()
189
- } = options;
190
- const signal = abortController.signal;
191
- const hookOptions = {
192
- signal,
193
- abort: (reason) => abortController.abort(reason)
194
- };
195
- const init = {
196
- method: "GET",
197
- headers: remoteFetchHeaders(),
198
- signal,
199
- ...additionalInit
200
- };
201
- const res = await onRequest?.(url, init, hookOptions) ?? await fetchWithWarning(url, init);
202
- return await onResponse?.(url, res, hookOptions) ?? res;
203
- }
204
-
205
- // src/host/server/get-client-or-server-url.ts
206
- function getClientOrServerUrl(src, serverFallback) {
207
- const fallback = typeof location !== "undefined" ? location.href : serverFallback;
208
- if (!src) {
209
- return new URL(fallback);
210
- }
211
- return typeof src === "string" ? new URL(src, fallback) : src;
212
- }
213
-
214
- // src/host/shared/lifecycle.ts
215
- function makeReactEmitter(callbacks) {
216
- return {
217
- beforeLoad(src) {
218
- callbacks.onBeforeLoad?.(src);
219
- },
220
- load(src) {
221
- callbacks.onLoad?.(src);
222
- },
223
- error(error, _src) {
224
- callbacks.onError?.(error);
225
- },
226
- change(info) {
227
- callbacks.onChange?.(info);
228
- }
229
- };
230
- }
231
-
232
- // src/utils/index.ts
233
- function escapeString(str) {
234
- return str.replace(/[^a-z0-9]/g, "_");
235
- }
236
- function computeScopedName(name, options) {
237
- return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
238
- }
239
- var attrToProp = {
240
- fetchpriority: "fetchPriority",
241
- crossorigin: "crossOrigin",
242
- imagesrcset: "imageSrcSet",
243
- imagesizes: "imageSizes",
244
- srcset: "srcSet"
245
- };
246
-
247
- // src/runtime/constants.ts
248
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
249
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
250
- var DEFAULT_ROUTE = "/";
251
- var RUNTIME_WEBPACK = "webpack";
252
- var RUNTIME_TURBOPACK = "turbopack";
253
- var RUNTIME_SCRIPT = "script";
254
- function getBundleKey(bundle) {
255
- return escapeString(bundle);
256
- }
257
-
258
- // src/runtime/namespace.ts
259
- var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
260
- var LEGACY_ALIASES = [
261
- { global: "__remote_component_scopes__", prop: "scopes" },
262
- {
263
- global: "__remote_components_turbopack_chunk_loader_promise__",
264
- prop: "chunkCache"
265
- },
266
- { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
267
- { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
268
- { global: "__remote_bundle_url__", prop: "bundleUrls" },
269
- { global: "__rc_module_registry__", prop: "moduleRegistry" },
270
- {
271
- global: "__remote_component_host_shared_modules__",
272
- prop: "hostSharedModules"
273
- },
274
- { global: "__remote_next_css__", prop: "cssCache" }
275
- ];
276
- function getNamespace() {
277
- const g = globalThis;
278
- const existing = g.__remote_components__;
279
- if (existing) {
280
- return existing;
281
- }
282
- const ns = {
283
- scopes: /* @__PURE__ */ new Map(),
284
- chunkCache: {},
285
- mountFns: {},
286
- unmountFns: {},
287
- bundleUrls: {},
288
- moduleRegistry: {},
289
- dispatcherRuntime: void 0,
290
- hostSharedModules: {},
291
- cssCache: {},
292
- shadowRoots: {}
293
- };
294
- const nsRecord = ns;
295
- for (const { global, prop } of LEGACY_ALIASES) {
296
- const legacyValue = g[global];
297
- if (legacyValue != null) {
298
- nsRecord[prop] = legacyValue;
299
- }
300
- g[global] = ns[prop];
301
- }
302
- const gRecord = g;
303
- for (const key of Object.keys(gRecord)) {
304
- if (key.startsWith(SHADOW_ROOT_PREFIX)) {
305
- const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
306
- ns.shadowRoots[suffix] = gRecord[key];
307
- delete gRecord[key];
308
- }
309
- }
310
- g.__remote_components__ = ns;
311
- return ns;
312
- }
313
-
314
- // src/runtime/patterns.ts
315
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
316
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
317
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
318
- function collapseDoubleSlashes(path) {
319
- return path.replace(DOUBLE_SLASH_RE, "/");
320
- }
321
-
322
- // src/runtime/turbopack/remote-scope.ts
323
- function getRegistry() {
324
- return getNamespace().scopes;
325
- }
326
- function createScope(name, url, runtime, resolveClientUrl) {
327
- const isCrossOrigin = url.origin !== location.origin;
328
- const scopedName = computeScopedName(name, {
329
- remoteHost: url.host,
330
- isCrossOrigin
331
- });
332
- const globalKey = getBundleKey(scopedName);
333
- return {
334
- name,
335
- scopedName,
336
- globalKey,
337
- url,
338
- runtime,
339
- resolveClientUrl,
340
- moduleCache: {},
341
- sharedModules: {},
342
- moduleGlobal: {},
343
- turbopackModules: []
344
- };
345
- }
346
- function registerScope(scope) {
347
- const registry = getRegistry();
348
- registry.set(scope.scopedName, scope);
349
- if (scope.scopedName !== scope.name) {
350
- const existing = registry.get(scope.name);
351
- if (existing && existing.scopedName !== scope.scopedName) {
352
- logWarn(
353
- "RemoteScope",
354
- `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
355
- );
356
- }
357
- registry.set(scope.name, scope);
358
- }
359
- logDebug(
360
- "RemoteScope",
361
- `Registered scope "${scope.scopedName}" (${registry.size} total)`
362
- );
363
- }
364
- function getScope(name) {
365
- return getRegistry().get(name);
366
- }
367
- function formatRemoteId(scope, path) {
368
- return `[${scope.scopedName}] ${path}`;
369
- }
370
- function parseRemoteId(id) {
371
- const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
372
- if (groups?.bundle && groups.id) {
373
- return {
374
- bundle: groups.bundle,
375
- path: groups.id,
376
- prefix: groups.prefix ?? ""
377
- };
378
- }
379
- return { bundle: "default", path: id, prefix: "" };
380
- }
381
-
382
- // src/host/shared/remote-image-loader.ts
383
- function createRemoteImageLoader(bundle, resolveClientUrl) {
384
- const loader = Object.assign(
385
- ({
386
- config,
387
- src,
388
- width,
389
- quality
390
- }) => {
391
- const q = quality ?? 75;
392
- const remoteOrigin = getScope(bundle)?.url.origin ?? "";
393
- const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
394
- const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
395
- const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
396
- return resolveClientUrl?.(url) ?? url;
397
- },
398
- // Signals to getImgProps that this is a default loader (not a user-defined
399
- // one), enabling srcSet generation with device/image sizes from the config.
400
- { __next_img_default: true }
401
- );
402
- return loader;
403
- }
404
-
405
- // src/host/shared/polyfill.tsx
406
- import { jsx } from "react/jsx-runtime";
407
- function sharedPolyfills(shared, resolveClientUrl) {
408
- const hostShared = getNamespace().hostSharedModules;
409
- const polyfill = {
410
- "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
411
- useRouter() {
412
- return {
413
- push: (routerUrl) => {
414
- history.pushState({}, "", routerUrl);
415
- },
416
- replace: (routerUrl) => {
417
- history.replaceState({}, "", routerUrl);
418
- },
419
- back: () => {
420
- history.back();
421
- }
422
- };
423
- },
424
- usePathname() {
425
- return location.pathname;
426
- },
427
- useParams() {
428
- return {};
429
- },
430
- useSearchParams() {
431
- return new URLSearchParams(location.search);
432
- },
433
- useSelectedLayoutSegment() {
434
- return null;
435
- },
436
- useSelectedLayoutSegments() {
437
- return [];
438
- },
439
- __esModule: true
440
- })),
441
- "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
442
- default: ({
443
- scroll: _,
444
- replace,
445
- prefetch,
446
- onNavigate,
447
- children,
448
- ...props
449
- }) => {
450
- if (prefetch) {
451
- logWarn(
452
- "Polyfill",
453
- "Next.js Link prefetch is not supported in remote components"
454
- );
455
- }
456
- return /* @__PURE__ */ jsx(
457
- "a",
458
- {
459
- ...props,
460
- href: props.href,
461
- onClick: (e) => {
462
- e.preventDefault();
463
- let preventDefaulted = false;
464
- e.preventDefault = () => {
465
- preventDefaulted = true;
466
- e.defaultPrevented = true;
467
- };
468
- if (typeof props.onClick === "function") {
469
- props.onClick(e);
470
- }
471
- onNavigate?.(e);
472
- if (preventDefaulted) {
473
- return;
474
- }
475
- if (replace) {
476
- history.replaceState({}, "", props.href);
477
- } else {
478
- history.pushState({}, "", props.href);
479
- }
480
- },
481
- suppressHydrationWarning: true,
482
- children: children ?? null
483
- }
484
- );
485
- },
486
- useLinkStatus() {
487
- return { pending: false };
488
- },
489
- __esModule: true
490
- })),
491
- "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
492
- default: () => {
493
- throw new Error("Next.js <Form> component not implemented");
494
- },
495
- __esModule: true
496
- })),
497
- // Instead of replacing next/image entirely, we let the real Next.js Image
498
- // component load from the remote bundle and only replace its default loader.
499
- // This gives us full next/image fidelity (fill, priority, srcSet, blur
500
- // placeholders, error handling) while routing image optimization through the
501
- // remote app's /_next/image endpoint.
502
- "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
503
- default: createRemoteImageLoader(bundle, resolveClientUrl),
504
- __esModule: true
505
- })),
506
- "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
507
- // TODO: implement <Script> component for non-Next.js host applications
508
- // do not throw an error for now
509
- default: () => null,
510
- __esModule: true
511
- })),
512
- "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
513
- // TODO: incomplete implementation
514
- Promise.resolve({
515
- useRouter() {
516
- return {
517
- push: (routerUrl) => {
518
- history.pushState({}, "", routerUrl);
519
- },
520
- replace: (routerUrl) => {
521
- history.replaceState({}, "", routerUrl);
522
- },
523
- back: () => {
524
- history.back();
525
- }
526
- };
527
- },
528
- __esModule: true
529
- })
530
- )),
531
- "next/dist/build/polyfills/process": () => Promise.resolve({
532
- default: {
533
- env: {
534
- NODE_ENV: "production"
535
- }
536
- },
537
- __esModule: true
538
- })
539
- };
540
- polyfill["next/navigation"] = polyfill["next/dist/client/components/navigation"];
541
- polyfill["next/link"] = polyfill["next/dist/client/app-dir/link"];
542
- polyfill["next/form"] = polyfill["next/dist/client/app-dir/form"];
543
- polyfill["next/dist/esm/shared/lib/image-loader"] = polyfill["next/dist/shared/lib/image-loader"];
544
- polyfill["next/script"] = polyfill["next/dist/client/script"];
545
- return polyfill;
546
- }
547
-
548
- // src/host/shared/shared-module-resolver.ts
549
- var CORE_REACT_PATH_MAP = {
550
- react: "/react/index.js",
551
- "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
552
- "react/jsx-runtime": "/react/jsx-runtime.js",
553
- "react-dom": "/react-dom/index.js",
554
- "react-dom/client": "/react-dom/client.js"
555
- };
556
- var VENDOR_SHARED = Object.fromEntries(
557
- Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
558
- );
559
- function buildCoreShared(userShared) {
560
- return {
561
- react: async () => (await import("react")).default,
562
- "react-dom": async () => (await import("react-dom")).default,
563
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
564
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
565
- "react-dom/client": async () => (await import("react-dom/client")).default,
566
- ...userShared
567
- };
568
- }
569
- function buildHostShared(userShared, resolveClientUrl, options) {
570
- const self = globalThis;
571
- const result = {
572
- ...sharedPolyfills(userShared, resolveClientUrl),
573
- ...self.__remote_component_host_shared_modules__,
574
- ...userShared
575
- };
576
- if (options?.includeRemoteComponentShared) {
577
- Object.assign(result, self.__remote_component_shared__);
578
- }
579
- return result;
580
- }
581
- async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
582
- const resolve = {
583
- ...reactModules,
584
- ...Object.entries(remoteShared).reduce(
585
- (acc, [key, value]) => {
586
- if (typeof hostShared[value] !== "undefined") {
587
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
588
- } else {
589
- logDebug(
590
- callerTag,
591
- `Remote requests "${value}" but host doesn't provide it`
592
- );
593
- }
594
- return acc;
595
- },
596
- {}
597
- )
598
- };
599
- await Promise.all(
600
- Object.entries(resolve).map(async ([key, value]) => {
601
- if (typeof value === "function") {
602
- resolve[key] = await value(bundle);
603
- }
604
- return Promise.resolve(value);
605
- })
606
- );
607
- return resolve;
608
- }
609
-
610
- // src/runtime/html/html-spec.ts
611
- var ORIGIN_REWRITE_TAGS = [
612
- "img",
613
- "source",
614
- "video",
615
- "audio",
616
- "track",
617
- "iframe",
618
- "embed",
619
- "script",
620
- "link"
621
- ];
622
- var ID_SUFFIX_RSC = "_rsc";
623
- var ID_SUFFIX_SSR = "_ssr";
624
- var ID_SUFFIX_SHARED = "_shared";
625
- var DATA_BUNDLE = "data-bundle";
626
- var DATA_ROUTE = "data-route";
627
- var DATA_RUNTIME = "data-runtime";
628
- var DATA_TYPE = "data-type";
629
- var DATA_SRC = "data-src";
630
- var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
631
- var TAG_REMOTE_COMPONENT = "remote-component";
632
- var NEXT_DATA_ID = "__NEXT_DATA__";
633
- var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
634
- var NEXT_CONTAINER_ID = "__next";
635
-
636
- // src/runtime/html/rewrite-srcset.ts
637
- function rewriteSrcset(srcset, base, resolve) {
638
- return srcset.split(",").map((entry) => {
639
- const [url, descriptor] = entry.trim().split(/\s+/);
640
- if (!url)
641
- return entry;
642
- const absoluteUrl = new URL(url, base).href;
643
- const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
644
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
645
- }).join(", ");
646
- }
647
-
648
- // src/runtime/html/apply-origin.ts
649
- function applyOriginToNodes(doc, url, resolveClientUrl) {
650
- if (url.origin !== location.origin) {
651
- const nodes = doc.querySelectorAll(
652
- ORIGIN_REWRITE_TAGS.map(
653
- (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
654
- ).join(",")
655
- );
656
- nodes.forEach((node) => {
657
- if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
658
- const absoluteSrc = new URL(node.getAttribute("src") ?? "/", url).href;
659
- const isScript = node.tagName.toLowerCase() === "script";
660
- node.src = isScript ? absoluteSrc : resolveClientUrl?.(absoluteSrc) ?? absoluteSrc;
661
- }
662
- if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
663
- const absoluteHref = new URL(node.getAttribute("href") ?? "/", url).href;
664
- node.setAttribute(
665
- "href",
666
- resolveClientUrl?.(absoluteHref) ?? absoluteHref
667
- );
668
- }
669
- if (node.hasAttribute("srcset")) {
670
- const raw = node.getAttribute("srcset");
671
- if (raw) {
672
- const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
673
- node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
674
- }
675
- }
676
- if (node.hasAttribute("imagesrcset")) {
677
- const raw = node.getAttribute("imagesrcset");
678
- if (raw) {
679
- const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
680
- node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
681
- }
682
- }
683
- });
684
- }
685
- }
686
-
687
- // src/runtime/metadata.ts
688
- var VALID_RUNTIMES = /* @__PURE__ */ new Set(["webpack", "turbopack", "script"]);
689
- var VALID_TYPES = /* @__PURE__ */ new Set([
690
- "nextjs",
691
- "remote-component",
692
- "unknown"
693
- ]);
694
- function isRuntime(value) {
695
- return VALID_RUNTIMES.has(value);
696
- }
697
- function isComponentType(value) {
698
- return VALID_TYPES.has(value);
699
- }
700
- function toRuntime(value) {
701
- return value && isRuntime(value) ? value : "webpack";
702
- }
703
- function toComponentType(value) {
704
- return value && isComponentType(value) ? value : "unknown";
705
- }
706
- function buildMetadata(attrs, url) {
707
- const id = attrs.id || DEFAULT_COMPONENT_NAME;
708
- const bundle = attrs.bundle || process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION || DEFAULT_BUNDLE_NAME;
709
- return {
710
- name: attrs.name || id.replace(/_ssr$/, ""),
711
- bundle,
712
- route: attrs.route || url.pathname || DEFAULT_ROUTE,
713
- runtime: toRuntime(attrs.runtime),
714
- id,
715
- type: toComponentType(attrs.type)
716
- };
717
- }
718
-
719
- // src/runtime/html/parse-remote-html.ts
720
- function validateSingleComponent(doc, name, url) {
721
- if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
722
- `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
723
- ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
724
- throw multipleRemoteComponentsError(url);
725
- }
726
- }
727
- function findComponentElement(doc, name) {
728
- return doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`) ?? doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ?? doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]:not([src])`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`);
729
- }
730
- function parseNextData(doc) {
731
- return JSON.parse(
732
- (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
733
- );
734
- }
735
- function resolveComponentName(component, nextData, fallbackName) {
736
- const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
737
- const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
738
- return { name, isRemoteComponent };
739
- }
740
- function extractRemoteShared(doc, name, nextData) {
741
- const remoteSharedEl = doc.querySelector(
742
- `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
743
- );
744
- const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
745
- remoteSharedEl?.remove();
746
- return remoteShared;
747
- }
748
- function validateComponentFound(component, rsc, nextData, isRemoteComponent, url, name) {
749
- if (!component || !(rsc || nextData || isRemoteComponent)) {
750
- throw new RemoteComponentsError(
751
- `Remote Component not found on ${url}.${name !== DEFAULT_COMPONENT_NAME ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
752
- );
753
- }
754
- }
755
- function extractLinks(doc, component) {
756
- return Array.from(doc.querySelectorAll("link[href]")).filter(
757
- (link) => !component.contains(link)
758
- );
759
- }
760
- function extractScripts(doc, component, isRemoteComponent) {
761
- return Array.from(
762
- (isRemoteComponent ? component : doc).querySelectorAll(
763
- `script[src],script[${DATA_SRC}]`
764
- )
765
- );
766
- }
767
- function parseRemoteComponentDocument(doc, name, url) {
768
- validateSingleComponent(doc, name, url.href);
769
- const component = findComponentElement(doc, name);
770
- const nextData = parseNextData(doc);
771
- const { name: resolvedName, isRemoteComponent } = resolveComponentName(
772
- component,
773
- nextData,
774
- name
775
- );
776
- const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
777
- const metadata = buildMetadata(
778
- {
779
- name: resolvedName,
780
- bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
781
- route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
782
- runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
783
- id: component?.getAttribute("id"),
784
- type: component?.getAttribute(DATA_TYPE)
785
- },
786
- url
787
- );
788
- const remoteShared = extractRemoteShared(doc, resolvedName, nextData);
789
- validateComponentFound(
790
- component,
791
- rsc,
792
- nextData,
793
- isRemoteComponent,
794
- url.href,
795
- resolvedName
796
- );
797
- const links = extractLinks(doc, component);
798
- const scripts = extractScripts(doc, component, isRemoteComponent);
799
- return {
800
- component,
801
- name: resolvedName,
802
- isRemoteComponent,
803
- metadata,
804
- nextData,
805
- rsc,
806
- remoteShared,
807
- links,
808
- scripts
809
- };
810
- }
811
-
812
- // src/runtime/loaders/component-loader.ts
813
- import * as React from "react";
814
- import * as JSXDevRuntime from "react/jsx-dev-runtime";
815
- import * as JSXRuntime from "react/jsx-runtime";
816
- import * as ReactDOM from "react-dom";
817
- import * as ReactDOMClient from "react-dom/client";
818
-
819
- // src/config/webpack/apply-shared-modules.ts
820
- var DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
821
- function applySharedModules(bundle, resolve) {
822
- logDebug(
823
- "SharedModules",
824
- `applySharedModules called for bundle: "${bundle}"`
825
- );
826
- logDebug(
827
- "SharedModules",
828
- `Shared modules to resolve: ${Object.keys(resolve)}`
829
- );
830
- const self = globalThis;
831
- const scope = getScope(bundle);
832
- const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
833
- if (webpackBundle) {
834
- const modulePaths = Object.keys(
835
- self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
836
- );
837
- logDebug(
838
- "SharedModules",
839
- `Available module paths for bundle "${bundle}": ${modulePaths}`
840
- );
841
- for (const [key, value] of Object.entries(resolve)) {
842
- const exactIds = modulePaths.filter((p) => p === key);
843
- const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
844
- if (ids.length === 0) {
845
- logDebug(
846
- "SharedModules",
847
- `No matching module path found for shared module "${key}"`
848
- );
849
- }
850
- for (const id of ids) {
851
- if (webpackBundle.m) {
852
- const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
853
- if (resolvedId !== id) {
854
- logDebug(
855
- "SharedModules",
856
- `Mapped module id: "${id}" -> "${resolvedId}"`
857
- );
858
- }
859
- webpackBundle.m[resolvedId] = (module) => {
860
- module.exports = value;
861
- };
862
- } else {
863
- logWarn(
864
- "SharedModules",
865
- `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
866
- );
867
- }
868
- }
869
- }
870
- } else {
871
- logWarn(
872
- "SharedModules",
873
- `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
874
- );
875
- logDebug(
876
- "SharedModules",
877
- `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
878
- );
879
- }
880
- }
881
-
882
- // src/config/webpack/next-client-pages-loader.ts
883
- function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
884
- const self = globalThis;
885
- const nextCssOriginal = document.querySelector(
886
- `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
887
- );
888
- if (nextCssOriginal) {
889
- nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
890
- }
891
- const nextCss = document.createElement("noscript");
892
- nextCss.id = "__next_css__DO_NOT_USE__";
893
- nextCss.setAttribute("data-bundle", bundle);
894
- nextCss.setAttribute("data-route", route);
895
- const nextCssEnd = document.createElement("noscript");
896
- nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
897
- nextCssEnd.setAttribute("data-bundle", bundle);
898
- nextCssEnd.setAttribute("data-route", route);
899
- document.head.appendChild(nextCssEnd);
900
- document.head.appendChild(nextCss);
901
- const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
902
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
903
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
904
- (key) => key.includes("/next/dist/client/page-loader.js")
905
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
906
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
907
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
908
- (key) => key.includes("/next/dist/client/page-loader.js")
909
- ) ?? ""] ?? -1;
910
- const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
911
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
912
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
913
- (key) => key.includes("/next/dist/client/page-loader.js")
914
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
915
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
916
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
917
- (key) => key.includes("/next/dist/client/page-loader.js")
918
- ) ?? ""] ?? -1;
919
- if (!(componentLoaderChunk && appLoaderChunk)) {
920
- throw new RemoteComponentsError(
921
- `Next.js client pages loader not found in bundle "${bundle}".`
922
- );
923
- }
924
- const __NEXT_P_ORIGINAL = self.__NEXT_P;
925
- const selfOriginal = self;
926
- delete selfOriginal.__NEXT_P;
927
- self.__remote_webpack_require__?.[bundle]?.(
928
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
929
- );
930
- if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
931
- self.__remote_webpack_require__?.[bundle]?.(
932
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
933
- );
934
- }
935
- if (self.__NEXT_P) {
936
- const [, componentLoader] = self.__NEXT_P[0] ?? [
937
- void 0,
938
- () => ({ default: null })
939
- ];
940
- const [, appLoader] = self.__NEXT_P[2] ?? [
941
- void 0,
942
- () => ({
943
- default: null
944
- })
945
- ];
946
- const { default: Component } = componentLoader();
947
- const { default: App } = appLoader();
948
- const cssCache = getNamespace().cssCache;
949
- if (!cssCache[bundle]) {
950
- const cssRE = /\.s?css$/;
951
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
952
- self.__remote_webpack_require__?.[bundle]?.(id);
953
- });
954
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
955
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
956
- if (id) {
957
- self.__remote_webpack_require__?.[bundle]?.(id);
958
- }
959
- });
960
- const elements = [];
961
- let node = nextCss.previousSibling;
962
- while (node && node !== nextCssEnd) {
963
- elements.push(node);
964
- node.remove();
965
- node = nextCss.previousSibling;
966
- }
967
- cssCache[bundle] = elements;
968
- }
969
- if (styleContainer) {
970
- const elements = cssCache[bundle];
971
- elements.forEach((el) => {
972
- styleContainer.appendChild(el.cloneNode(true));
973
- });
974
- } else {
975
- const elements = cssCache[bundle];
976
- elements.forEach((el) => {
977
- document.head.appendChild(el);
978
- });
979
- }
980
- delete self.__NEXT_P;
981
- self.__NEXT_P = __NEXT_P_ORIGINAL;
982
- if (nextCssOriginal) {
983
- nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
984
- }
985
- nextCss.remove();
986
- nextCssEnd.remove();
987
- return { Component, App };
988
- }
989
- return { Component: null, App: null };
990
- }
991
-
992
- // src/runtime/rsc.ts
993
- import { ReadableStream } from "web-streams-polyfill";
994
- function fixPayload(payload) {
995
- if (Array.isArray(payload)) {
996
- if (payload[0] === "$") {
997
- fixPayload(payload[3]);
998
- if (payload.length === 4) {
999
- payload.push(null, null, 1);
1000
- }
1001
- } else {
1002
- for (const item of payload) {
1003
- fixPayload(item);
1004
- }
1005
- }
1006
- } else if (typeof payload === "object" && payload !== null) {
1007
- for (const key in payload) {
1008
- fixPayload(payload[key]);
1009
- }
1010
- }
1011
- }
1012
- function buildRSCChunks(rscName, data) {
1013
- const chunks = [];
1014
- for (const chunk of data) {
1015
- for (const line of chunk.split("\n")) {
1016
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1017
- if (match?.groups?.rsc) {
1018
- chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1019
- }
1020
- }
1021
- }
1022
- return chunks;
1023
- }
1024
- function createRSCStream(rscName, data) {
1025
- return new ReadableStream({
1026
- type: "bytes",
1027
- start(controller) {
1028
- const encoder = new TextEncoder();
1029
- const self = globalThis;
1030
- if (data.length > 0) {
1031
- const parsed = buildRSCChunks(rscName, data);
1032
- if (parsed.length > 0) {
1033
- self[rscName] = self[rscName] ?? [];
1034
- self[rscName].push(...parsed);
1035
- }
1036
- }
1037
- const allChunks = (self[rscName] ?? [`0:[null]
1038
- `]).join("");
1039
- self[rscName] = null;
1040
- allChunks.split("\n").forEach((chunk) => {
1041
- if (chunk.length > 0) {
1042
- const { before, id, prefix, payload } = /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
1043
- chunk
1044
- )?.groups ?? {};
1045
- if (payload) {
1046
- const jsonPayload = JSON.parse(payload);
1047
- fixPayload(jsonPayload);
1048
- const reconstruct = `${before ?? ""}${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
1049
- controller.enqueue(encoder.encode(`${reconstruct}
1050
- `));
1051
- } else {
1052
- controller.enqueue(encoder.encode(`${chunk}
1053
- `));
1054
- }
1055
- } else {
1056
- controller.enqueue(encoder.encode(`${chunk}
1057
- `));
1058
- }
1059
- });
1060
- controller.close();
1061
- }
1062
- });
1063
- }
1064
-
1065
- // src/runtime/rsc-imports.ts
1066
- async function importRSCClientBrowser() {
1067
- try {
1068
- return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1069
- } catch {
1070
- const mod = await import("react-server-dom-webpack/client.browser");
1071
- return mod.default ?? mod;
1072
- }
1073
- }
1074
-
1075
- // src/runtime/turbopack/patterns.ts
1076
- var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1077
- function stripQuotes(value) {
1078
- if (value.startsWith('"') && value.endsWith('"')) {
1079
- return value.slice(1, -1);
1080
- }
1081
- return value;
1082
- }
1083
- function extractGroup(re, input, group) {
1084
- const raw = re.exec(input)?.groups?.[group];
1085
- return raw ? stripQuotes(raw) : void 0;
1086
- }
1087
- var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1088
- var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1089
- `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1090
- );
1091
- var ASYNC_MODULE_LOADER_RE = new RegExp(
1092
- `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1093
- );
1094
- var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1095
- `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1096
- );
1097
- var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1098
-
1099
- // src/runtime/turbopack/chunk-loader.ts
1100
- function loadChunkWithScope(scope, chunkId) {
1101
- logDebug(
1102
- "ChunkLoader",
1103
- `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1104
- );
1105
- const self = globalThis;
1106
- const ns = getNamespace();
1107
- const { bundle, path, prefix } = parseRemoteId(chunkId);
1108
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1109
- if (remoteRuntime === RUNTIME_WEBPACK) {
1110
- return Promise.resolve(void 0);
1111
- }
1112
- const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1113
- const url = new URL(rawPath, scope.url).href;
1114
- if (url.endsWith(".css")) {
1115
- return;
1116
- }
1117
- if (ns.chunkCache[url]) {
1118
- logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1119
- return ns.chunkCache[url];
1120
- }
1121
- const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1122
- if (resolvedUrl !== url) {
1123
- logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1124
- }
1125
- ns.chunkCache[url] = new Promise((resolve, reject) => {
1126
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1127
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1128
- if (hasTurbopack) {
1129
- return handleTurbopackChunk(code, scope, url);
1130
- }
1131
- }).then(resolve).catch((error) => {
1132
- const isProxied = isProxiedUrl(resolvedUrl);
1133
- if (isProxied) {
1134
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1135
- } else {
1136
- warnCrossOriginFetchError("ChunkLoader", url);
1137
- reject(error);
1138
- }
1139
- });
1140
- });
1141
- return ns.chunkCache[url];
1142
- }
1143
- function createChunkDispatcher() {
1144
- return function __chunk_dispatcher__(chunkId, scriptBundle) {
1145
- logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1146
- const { bundle } = parseRemoteId(chunkId);
1147
- const bundleName = bundle || scriptBundle || "default";
1148
- const scope = getScope(bundleName);
1149
- logDebug(
1150
- "ChunkDispatcher",
1151
- `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1152
- );
1153
- if (!scope) {
1154
- logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1155
- return Promise.resolve(void 0);
1156
- }
1157
- return loadChunkWithScope(scope, chunkId);
1158
- };
1159
- }
1160
- async function handleTurbopackChunk(code, scope, url) {
1161
- if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1162
- const preloadLinks = document.querySelectorAll(
1163
- `link[rel="preload"][href="${new URL(url).pathname}"]`
1164
- );
1165
- preloadLinks.forEach((preloadLink) => preloadLink.remove());
1166
- return;
1167
- }
1168
- const self = globalThis;
1169
- const { globalKey } = scope;
1170
- const transformedCode = code.replace(
1171
- /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1172
- `globalThis["TURBOPACK_${globalKey}"]`
1173
- ).replace(
1174
- /self\[\s*["']TURBOPACK["']\s*\]/g,
1175
- `self["TURBOPACK_${globalKey}"]`
1176
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1177
- /TURBOPACK_WORKER_LOCATION/g,
1178
- `TURBOPACK_WORKER_LOCATION_${globalKey}`
1179
- ).replace(
1180
- /TURBOPACK_NEXT_CHUNK_URLS/g,
1181
- `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1182
- ).replace(
1183
- /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1184
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1185
- ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1186
- /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1187
- `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1188
- );
1189
- if (!self[`TURBOPACK_${globalKey}`]) {
1190
- const wrapPush = (target) => {
1191
- const originalPush = target.push;
1192
- if (typeof originalPush !== "function")
1193
- return target;
1194
- target.push = (...items) => {
1195
- for (const item of items) {
1196
- if (Array.isArray(item)) {
1197
- for (const entry of item) {
1198
- scope.turbopackModules.push(entry);
1199
- }
1200
- } else {
1201
- scope.turbopackModules.push(item);
1202
- }
1203
- }
1204
- return originalPush.apply(target, items);
1205
- };
1206
- return target;
1207
- };
1208
- const globalProp = `TURBOPACK_${globalKey}`;
1209
- let currentValue = wrapPush([]);
1210
- Object.defineProperty(self, globalProp, {
1211
- get() {
1212
- return currentValue;
1213
- },
1214
- set(newValue) {
1215
- if (newValue && typeof newValue === "object") {
1216
- wrapPush(newValue);
1217
- }
1218
- currentValue = newValue;
1219
- },
1220
- configurable: true,
1221
- enumerable: true
1222
- });
1223
- }
1224
- await new Promise((scriptResolve, scriptReject) => {
1225
- const blob = new Blob([transformedCode], {
1226
- type: "application/javascript; charset=UTF-8"
1227
- });
1228
- const scriptUrl = URL.createObjectURL(blob);
1229
- const script = document.createElement("script");
1230
- script.setAttribute("data-turbopack-src", url);
1231
- script.src = scriptUrl;
1232
- script.async = true;
1233
- script.onload = () => {
1234
- URL.revokeObjectURL(scriptUrl);
1235
- scriptResolve(void 0);
1236
- script.remove();
1237
- };
1238
- script.onerror = () => {
1239
- URL.revokeObjectURL(scriptUrl);
1240
- scriptReject(
1241
- new RemoteComponentsError(
1242
- `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
1243
- )
1244
- );
1245
- script.remove();
1246
- };
1247
- document.head.appendChild(script);
1248
- });
1249
- const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1250
- const loadChunkPromises = [];
1251
- while (chunkLists?.length) {
1252
- const { chunks } = chunkLists.shift() ?? { chunks: [] };
1253
- if (chunks.length > 0) {
1254
- for (const id of chunks) {
1255
- const baseUrl = url.slice(0, url.indexOf("/_next"));
1256
- const chunkLoadResult = loadChunkWithScope(
1257
- scope,
1258
- formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1259
- );
1260
- if (chunkLoadResult) {
1261
- loadChunkPromises.push(chunkLoadResult);
1262
- }
1263
- }
1264
- }
1265
- }
1266
- if (loadChunkPromises.length > 0) {
1267
- await Promise.all(loadChunkPromises);
1268
- }
1269
- }
1270
-
1271
- // src/runtime/turbopack/shared-modules.ts
1272
- var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1273
- function getTurbopackModules(scope) {
1274
- if (scope.turbopackModules.length > 0) {
1275
- return scope.turbopackModules;
1276
- }
1277
- const self = globalThis;
1278
- const raw = self[`TURBOPACK_${scope.globalKey}`];
1279
- if (!raw)
1280
- return void 0;
1281
- if (Array.isArray(raw)) {
1282
- return raw.flat();
1283
- }
1284
- return Object.entries(raw).flat();
1285
- }
1286
- async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1287
- const allModules = getTurbopackModules(scope);
1288
- logDebug(
1289
- "SharedModules",
1290
- `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1291
- );
1292
- let sharedModuleInitializer = null;
1293
- if (allModules) {
1294
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1295
- if (typeof idOrFunc !== "function") {
1296
- return false;
1297
- }
1298
- const funcCode = idOrFunc.toString();
1299
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1300
- });
1301
- if (sharedModuleInitializerIndex > 0) {
1302
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1303
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1304
- const sharedModuleId = extractGroup(
1305
- REMOTE_SHARED_ASSIGNMENT_RE,
1306
- sharedModuleInitializerCode,
1307
- "sharedModuleId"
1308
- );
1309
- if (sharedModuleId) {
1310
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1311
- scope,
1312
- sharedModuleId,
1313
- formatRemoteId(scope, String(sharedModuleInitializerId))
1314
- );
1315
- sharedModuleInitializer = sharedModuleInitializerInstance;
1316
- }
1317
- }
1318
- if (sharedModuleInitializer) {
1319
- const { shared } = await sharedModuleInitializer;
1320
- const sharedModuleIds = extractSharedModuleIds(shared, scope);
1321
- logDebug(
1322
- "SharedModules",
1323
- `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1324
- );
1325
- return Promise.all(
1326
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1327
- if (hostShared[module]) {
1328
- scope.sharedModules[id] = await hostShared[module](scope.name);
1329
- } else {
1330
- logError(
1331
- "SharedModules",
1332
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1333
- );
1334
- }
1335
- })
1336
- );
1337
- }
1338
- logWarn(
1339
- "SharedModules",
1340
- `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1341
- );
1342
- } else {
1343
- logWarn(
1344
- "SharedModules",
1345
- `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1346
- );
1347
- }
1348
- return Promise.all(
1349
- Object.entries(remoteShared).map(async ([id, module]) => {
1350
- if (hostShared[module]) {
1351
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1352
- scope.sharedModules[normalizedId] = await hostShared[module](
1353
- scope.name
1354
- );
1355
- } else {
1356
- logError(
1357
- "SharedModules",
1358
- `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1359
- );
1360
- }
1361
- })
1362
- );
1363
- }
1364
- function extractSharedModuleIds(shared, scope) {
1365
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1366
- const asyncSharedModuleId = extractGroup(
1367
- ASYNC_MODULE_LOADER_RE,
1368
- value.toString(),
1369
- "asyncSharedModuleId"
1370
- );
1371
- if (asyncSharedModuleId) {
1372
- const asyncSharedModule = findModuleInit(
1373
- getTurbopackModules(scope),
1374
- asyncSharedModuleId
1375
- );
1376
- if (asyncSharedModule) {
1377
- const sharedModuleId = extractGroup(
1378
- ASYNC_MODULE_CALLBACK_RE,
1379
- asyncSharedModule.toString(),
1380
- "sharedModuleId"
1381
- );
1382
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1383
- "__remote_shared_module_",
1384
- ""
1385
- );
1386
- }
1387
- }
1388
- return acc;
1389
- }, {});
1390
- }
1391
- function getSharedModule(scope, id) {
1392
- const idStr = String(id);
1393
- if (scope.sharedModules[idStr] !== void 0) {
1394
- return scope.sharedModules[idStr];
1395
- }
1396
- for (const [key, value] of Object.entries(scope.sharedModules)) {
1397
- if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1398
- return value;
1399
- }
1400
- }
1401
- return null;
1402
- }
1403
-
1404
- // src/runtime/turbopack/module.ts
1405
- function requireModule(scope, moduleId, fullId) {
1406
- const idStr = String(moduleId);
1407
- if (scope.moduleCache[idStr])
1408
- return scope.moduleCache[idStr];
1409
- const sharedModule = getSharedModule(scope, moduleId);
1410
- if (sharedModule)
1411
- return sharedModule;
1412
- return handleTurbopackModule(
1413
- scope,
1414
- idStr,
1415
- fullId ?? formatRemoteId(scope, idStr)
1416
- );
1417
- }
1418
- function handleTurbopackModule(scope, moduleId, id) {
1419
- if (scope.moduleCache[moduleId]) {
1420
- return scope.moduleCache[moduleId];
1421
- }
1422
- const modules = getTurbopackModules(scope);
1423
- if (!modules) {
1424
- logError(
1425
- "TurbopackModule",
1426
- `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1427
- );
1428
- }
1429
- const moduleInit = findModuleInit(modules, moduleId);
1430
- const exports = {};
1431
- const moduleExports = { exports };
1432
- if (typeof moduleInit !== "function") {
1433
- throw new Error(
1434
- `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1435
- );
1436
- }
1437
- scope.moduleCache[moduleId] = moduleExports.exports;
1438
- moduleInit(
1439
- createTurbopackContext(
1440
- scope,
1441
- exports,
1442
- moduleExports,
1443
- modules,
1444
- moduleInit,
1445
- id
1446
- ),
1447
- moduleExports,
1448
- exports
1449
- );
1450
- if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1451
- scope.moduleCache[moduleId] = moduleExports.exports;
1452
- }
1453
- return moduleExports.exports;
1454
- }
1455
- function findModuleInit(modules, moduleId) {
1456
- if (!modules || typeof modules !== "object")
1457
- return;
1458
- if (!Array.isArray(modules)) {
1459
- const key = moduleId in modules ? moduleId : Object.keys(modules).find((k) => k.startsWith(moduleId));
1460
- return key !== void 0 ? modules[key] : void 0;
1461
- }
1462
- const flat = modules.flat();
1463
- let idx = flat.findIndex((e) => String(e) === String(moduleId));
1464
- if (idx < 0) {
1465
- idx = flat.findIndex(
1466
- (e) => typeof e === "string" && e.startsWith(moduleId)
1467
- );
1468
- }
1469
- if (idx >= 0) {
1470
- return flat.slice(idx + 1).find((e) => typeof e === "function");
1471
- }
1472
- for (const entry of flat) {
1473
- if (!entry || typeof entry !== "object")
1474
- continue;
1475
- const obj = entry;
1476
- if (moduleId in obj)
1477
- return obj[moduleId];
1478
- const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1479
- if (prefixKey)
1480
- return obj[prefixKey];
1481
- }
1482
- return void 0;
1483
- }
1484
- function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1485
- const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1486
- return {
1487
- // HMR not implemented for Remote Components
1488
- k: {
1489
- register() {
1490
- },
1491
- registerExports() {
1492
- },
1493
- signature() {
1494
- return (fn) => fn;
1495
- }
1496
- },
1497
- // ESM exports setup
1498
- s(bindings, esmId) {
1499
- let mod = exports;
1500
- if (typeof esmId === "string" || typeof esmId === "number") {
1501
- if (!scope.moduleCache[esmId]) {
1502
- scope.moduleCache[esmId] = {};
1503
- }
1504
- mod = scope.moduleCache[esmId];
1505
- }
1506
- Object.defineProperty(mod, "__esModule", { value: true });
1507
- if (Array.isArray(bindings)) {
1508
- let i = 0;
1509
- while (i < bindings.length) {
1510
- const propName = bindings[i++];
1511
- const tagOrFunc = bindings[i++];
1512
- if (typeof tagOrFunc === "number") {
1513
- Object.defineProperty(mod, propName, {
1514
- value: bindings[i++],
1515
- enumerable: true,
1516
- writable: false
1517
- });
1518
- } else {
1519
- const getterFn = tagOrFunc;
1520
- if (typeof bindings[i] === "function") {
1521
- const setterFn = bindings[i++];
1522
- Object.defineProperty(mod, propName, {
1523
- get: getterFn,
1524
- set: setterFn,
1525
- enumerable: true
1526
- });
1527
- } else {
1528
- Object.defineProperty(mod, propName, {
1529
- get: getterFn,
1530
- enumerable: true
1531
- });
1532
- }
1533
- }
1534
- }
1535
- }
1536
- },
1537
- // import — resolves directly via scope, no global dispatch
1538
- i(importId) {
1539
- let mod;
1540
- if (typeof importId === "string") {
1541
- const { exportSource, exportName } = /\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(
1542
- importId
1543
- )?.groups ?? {};
1544
- const normalizedId = importId.replace(
1545
- /\s+<export(?<specifier>.*)>$/,
1546
- ""
1547
- );
1548
- mod = scopedRequire(normalizedId);
1549
- if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1550
- if (exportSource === "*") {
1551
- mod[exportName] = mod;
1552
- } else {
1553
- mod[exportName] = mod[exportSource];
1554
- }
1555
- }
1556
- } else {
1557
- mod = scopedRequire(importId);
1558
- }
1559
- if (typeof mod !== "object" || mod === null) {
1560
- mod = { default: mod };
1561
- } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1562
- // mod.toString() directly throws. Use Object.prototype.toString
1563
- // to safely detect them.
1564
- Object.prototype.toString.call(mod) !== "[object Module]") {
1565
- try {
1566
- mod.default = mod;
1567
- } catch {
1568
- }
1569
- }
1570
- return mod;
1571
- },
1572
- // require — resolves directly via scope
1573
- r(requireId) {
1574
- return scopedRequire(requireId);
1575
- },
1576
- // value exports
1577
- v(value) {
1578
- if (typeof value === "function") {
1579
- exports.default = value((vid) => scopedRequire(vid));
1580
- } else {
1581
- moduleExports.exports = value;
1582
- }
1583
- },
1584
- // async module initializer
1585
- async a(mod) {
1586
- let result;
1587
- await mod(
1588
- () => {
1589
- },
1590
- (value) => result = value
1591
- );
1592
- exports.default = result;
1593
- },
1594
- // async module loader — resolves directly via scope
1595
- async A(Aid) {
1596
- const mod = scopedRequire(Aid);
1597
- return mod.default((parentId) => scopedRequire(parentId));
1598
- },
1599
- // dynamic import tracking — no-op for remote components
1600
- j() {
1601
- },
1602
- // chunk loader — loads directly via scope, no global dispatch
1603
- l(url) {
1604
- const flatModules = Array.isArray(modules) ? modules : [];
1605
- const moduleInitIndex = flatModules.indexOf(moduleInit);
1606
- if (moduleInitIndex !== -1) {
1607
- const scriptIndex = flatModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
1608
- if (scriptIndex !== -1) {
1609
- const script = flatModules[scriptIndex];
1610
- const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1611
- const nextIndex = scriptSrc.indexOf("/_next");
1612
- const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1613
- const chunkUrl = `${baseUrl}/_next/${url}`;
1614
- return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1615
- }
1616
- }
1617
- throw new Error(
1618
- `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1619
- );
1620
- },
1621
- // globalThis substitute shared across all modules in this scope
1622
- g: scope.moduleGlobal,
1623
- m: moduleExports,
1624
- e: exports
1625
- };
1626
- }
1627
-
1628
- // src/runtime/turbopack/remote-scope-setup.ts
1629
- async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1630
- const self = globalThis;
1631
- const ns = getNamespace();
1632
- const bundleName = bundle ?? "default";
1633
- const existingScope = getScope(bundleName);
1634
- if (existingScope && existingScope.url.origin === url.origin) {
1635
- logDebug(
1636
- "WebpackRuntime",
1637
- `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1638
- );
1639
- existingScope.resolveClientUrl = resolveClientUrl;
1640
- if (runtime === RUNTIME_TURBOPACK) {
1641
- await Promise.allSettled(
1642
- scripts.map(
1643
- (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1644
- )
1645
- );
1646
- }
1647
- return existingScope;
1648
- }
1649
- const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1650
- registerScope(scope);
1651
- if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1652
- scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1653
- }
1654
- ns.bundleUrls[bundleName] = url;
1655
- if (scope.scopedName !== bundleName) {
1656
- ns.bundleUrls[scope.scopedName] = url;
1657
- }
1658
- self.__webpack_get_script_filename__ = () => null;
1659
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1660
- if (willCreateDispatchers) {
1661
- if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1662
- self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1663
- self.__original_webpack_require__ = self.__webpack_require__;
1664
- }
1665
- self.__webpack_chunk_load__ = createChunkDispatcher();
1666
- self.__webpack_require__ = createModuleDispatcher(runtime);
1667
- ns.dispatcherRuntime = runtime;
1668
- self.__webpack_require_type__ = runtime;
1669
- if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1670
- self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1671
- self.__remote_webpack_require__[bundleName].type = "turbopack";
1672
- }
1673
- }
1674
- if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1675
- self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1676
- }
1677
- if (runtime === RUNTIME_TURBOPACK) {
1678
- const results = await Promise.allSettled(
1679
- scripts.map((script) => {
1680
- if (script.src) {
1681
- return loadChunkWithScope(scope, script.src);
1682
- }
1683
- return Promise.resolve(void 0);
1684
- })
1685
- );
1686
- for (const result of results) {
1687
- if (result.status === "rejected") {
1688
- logWarn(
1689
- "WebpackRuntime",
1690
- `Initial chunk load failed: ${String(result.reason)}`
1691
- );
1692
- }
1693
- }
1694
- }
1695
- return scope;
1696
- }
1697
- function createModuleDispatcher(runtime) {
1698
- return (id) => {
1699
- const self = globalThis;
1700
- const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1701
- bundle: "default",
1702
- id
1703
- };
1704
- const bundleName = bundle ?? "default";
1705
- const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1706
- logDebug(
1707
- "ModuleDispatcher",
1708
- `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1709
- );
1710
- try {
1711
- if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1712
- const scope2 = getScope(bundle);
1713
- if (scope2?.webpackRequire)
1714
- return scope2.webpackRequire(moduleId);
1715
- return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1716
- }
1717
- const scope = getScope(bundleName);
1718
- if (scope) {
1719
- return requireModule(scope, moduleId ?? id, id);
1720
- }
1721
- throw new Error(
1722
- `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1723
- );
1724
- } catch (requireError) {
1725
- logWarn(
1726
- "ModuleDispatcher",
1727
- `Module require failed: ${String(requireError)}`
1728
- );
1729
- if (typeof self.__original_webpack_require__ !== "function") {
1730
- throw new RemoteComponentsError(
1731
- `Module "${id}" not found in remote component bundle "${bundleName}".`,
1732
- {
1733
- cause: requireError instanceof Error ? requireError : void 0
1734
- }
1735
- );
1736
- }
1737
- try {
1738
- logDebug(
1739
- "ModuleDispatcher",
1740
- "Falling back to original webpack require"
1741
- );
1742
- return self.__original_webpack_require__(id);
1743
- } catch (originalError) {
1744
- throw new RemoteComponentsError(
1745
- `Module "${id}" not found in remote component bundle "${bundleName}".`,
1746
- { cause: originalError instanceof Error ? originalError : void 0 }
1747
- );
1748
- }
1749
- }
1750
- };
1751
- }
1752
-
1753
- // src/runtime/loaders/script-loader.ts
1754
- async function loadScripts(scripts, resolveClientUrl) {
1755
- await Promise.all(
1756
- scripts.map((script) => {
1757
- return new Promise((resolve, reject) => {
1758
- const newSrc = new URL(
1759
- // remove the remote component bundle name identifier from the script src
1760
- script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
1761
- location.origin
1762
- ).href;
1763
- const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1764
- const alreadyLoaded = Array.from(
1765
- document.querySelectorAll("script[src]")
1766
- ).some((s) => s.src === resolvedSrc);
1767
- if (alreadyLoaded) {
1768
- resolve();
1769
- return;
1770
- }
1771
- const newScript = document.createElement("script");
1772
- newScript.onload = () => resolve();
1773
- newScript.onerror = () => {
1774
- const isProxied = isProxiedUrl(resolvedSrc);
1775
- if (isProxied) {
1776
- reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
1777
- } else {
1778
- warnCrossOriginFetchError("ScriptLoader", newSrc);
1779
- reject(
1780
- new RemoteComponentsError(
1781
- `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
1782
- )
1783
- );
1784
- }
1785
- };
1786
- newScript.src = resolvedSrc;
1787
- newScript.async = true;
1788
- document.head.appendChild(newScript);
1789
- });
1790
- })
1791
- );
1792
- }
1793
-
1794
- // src/runtime/loaders/component-loader.ts
1795
- async function loadRemoteComponent({
1796
- url,
1797
- name,
1798
- rscName,
1799
- bundle,
1800
- route = "/",
1801
- runtime = "webpack",
1802
- data,
1803
- nextData,
1804
- scripts = [],
1805
- shared = Promise.resolve({}),
1806
- remoteShared = {},
1807
- container,
1808
- resolveClientUrl
1809
- }) {
1810
- try {
1811
- if (runtime === "webpack") {
1812
- const self = globalThis;
1813
- if (!self.__DISABLE_WEBPACK_EXEC__) {
1814
- self.__DISABLE_WEBPACK_EXEC__ = {};
1815
- }
1816
- self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
1817
- await loadScripts(scripts, resolveClientUrl);
1818
- }
1819
- const hostShared = await shared;
1820
- logDebug(
1821
- "ComponentLoader",
1822
- `loadRemoteComponent: bundle="${bundle}", name="${name}"`
1823
- );
1824
- logDebug(
1825
- "ComponentLoader",
1826
- `Host shared modules available: ${Object.keys(hostShared)}`
1827
- );
1828
- logDebug(
1829
- "ComponentLoader",
1830
- `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1831
- );
1832
- const scope = await setupRemoteScope(
1833
- runtime,
1834
- scripts,
1835
- url,
1836
- bundle,
1837
- resolveClientUrl
1838
- );
1839
- if (runtime === "turbopack") {
1840
- await initializeSharedModules(
1841
- scope,
1842
- buildCoreShared(hostShared),
1843
- remoteShared
1844
- );
1845
- }
1846
- if (bundle) {
1847
- const resolve = await buildWebpackResolve(
1848
- hostShared,
1849
- remoteShared,
1850
- bundle,
1851
- {
1852
- "/react/index.js": React,
1853
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1854
- "/react/jsx-runtime.js": JSXRuntime,
1855
- "/react-dom/index.js": ReactDOM,
1856
- "/react-dom/client.js": ReactDOMClient
1857
- },
1858
- "ComponentLoader"
1859
- );
1860
- applySharedModules(bundle, resolve);
1861
- } else {
1862
- logWarn(
1863
- "ComponentLoader",
1864
- "No bundle specified, skipping shared module setup"
1865
- );
1866
- }
1867
- if (data.length > 0) {
1868
- return await loadRSCComponent(rscName ?? name, data);
1869
- } else if (nextData) {
1870
- return loadNextPagesComponent(bundle, route, nextData, name, container);
1871
- }
1872
- return loadRSCComponent(rscName ?? name, [`0:[null]
1873
- `]);
1874
- } catch (error) {
1875
- return {
1876
- component: null,
1877
- error: new RemoteComponentsError(
1878
- `Failed to load remote component "${name}".`,
1879
- {
1880
- cause: error instanceof Error ? error : new Error(String(error))
1881
- }
1882
- )
1883
- };
1884
- }
1885
- }
1886
- async function loadRSCComponent(rscName, data) {
1887
- const { createFromReadableStream } = await importRSCClientBrowser();
1888
- if (typeof createFromReadableStream !== "function") {
1889
- throw new RemoteComponentsError(
1890
- 'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
1891
- );
1892
- }
1893
- const stream = createRSCStream(rscName, data);
1894
- const component = createFromReadableStream(stream);
1895
- return { component };
1896
- }
1897
- function loadNextPagesComponent(bundle, route, nextData, name, container) {
1898
- const { Component, App } = nextClientPagesLoader(bundle, route, container);
1899
- if (!Component) {
1900
- throw new RemoteComponentsError(
1901
- `Remote Component "${name}" is trying to load the component for route "${route}" but it is not available.`
1902
- );
1903
- }
1904
- const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
1905
- return { component };
1906
- }
1907
-
1908
- // src/runtime/loaders/static-loader.ts
1909
- async function importViaCallback(absoluteSrc, resolveClientUrl) {
1910
- const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;
1911
- const fetchUrl = new URL(resolvedUrl, location.href).href;
1912
- const response = await fetch(fetchUrl);
1913
- if (!response.ok)
1914
- throw new Error(`Proxied fetch failed: ${response.status}`);
1915
- const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
1916
- /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
1917
- (_, keyword, quote, relativePath) => {
1918
- const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
1919
- const resolvedImportUrl = new URL(
1920
- resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,
1921
- location.href
1922
- ).href;
1923
- return `${keyword} ${quote}${resolvedImportUrl}${quote}`;
1924
- }
1925
- );
1926
- const moduleBlobUrl = URL.createObjectURL(
1927
- new Blob([content], { type: "text/javascript" })
1928
- );
1929
- const wrapperContent = [
1930
- `import*as m from${JSON.stringify(moduleBlobUrl)};`,
1931
- `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,
1932
- `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`
1933
- ].join("");
1934
- const wrapperBlobUrl = URL.createObjectURL(
1935
- new Blob([wrapperContent], { type: "text/javascript" })
1936
- );
1937
- const scriptEl = document.createElement("script");
1938
- scriptEl.type = "module";
1939
- scriptEl.src = wrapperBlobUrl;
1940
- try {
1941
- await new Promise((resolve, reject) => {
1942
- scriptEl.onload = () => resolve();
1943
- scriptEl.onerror = () => reject(new Error(`Failed to load module for ${absoluteSrc}`));
1944
- document.head.appendChild(scriptEl);
1945
- });
1946
- } finally {
1947
- scriptEl.remove();
1948
- URL.revokeObjectURL(moduleBlobUrl);
1949
- URL.revokeObjectURL(wrapperBlobUrl);
1950
- }
1951
- const registry = getNamespace().moduleRegistry;
1952
- const mod = registry[absoluteSrc] ?? {};
1953
- delete registry[absoluteSrc];
1954
- return mod;
1955
- }
1956
- async function importDirectly(absoluteSrc) {
1957
- try {
1958
- return await import(
1959
- /* @vite-ignore */
1960
- /* webpackIgnore: true */
1961
- absoluteSrc
1962
- );
1963
- } catch (importError) {
1964
- if (!absoluteSrc.startsWith("blob:")) {
1965
- warnCrossOriginFetchError("StaticLoader", absoluteSrc);
1966
- }
1967
- throw importError;
1968
- }
1969
- }
1970
- function resolveScriptSrc(script, url) {
1971
- const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
1972
- if (!rawSrc && script.textContent) {
1973
- return URL.createObjectURL(
1974
- new Blob(
1975
- [script.textContent.replace(/import\.meta\.url/g, JSON.stringify(url))],
1976
- { type: "text/javascript" }
1977
- )
1978
- );
1979
- }
1980
- return rawSrc;
1981
- }
1982
- async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1983
- const ns = getNamespace();
1984
- if (ns.mountFns[url.href]) {
1985
- ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1986
- }
1987
- if (ns.unmountFns[url.href]) {
1988
- ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1989
- }
1990
- const mountUnmountSets = await Promise.all(
1991
- scripts.map(async (script) => {
1992
- try {
1993
- const src = resolveScriptSrc(script, url);
1994
- const absoluteSrc = new URL(src, url).href;
1995
- const mod = resolveClientUrl ? await importViaCallback(absoluteSrc, resolveClientUrl) : await importDirectly(absoluteSrc);
1996
- if (src.startsWith("blob:")) {
1997
- URL.revokeObjectURL(src);
1998
- }
1999
- if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
2000
- if (!ns.mountFns[url.href]) {
2001
- ns.mountFns[url.href] = /* @__PURE__ */ new Set();
2002
- }
2003
- ns.mountFns[url.href]?.add(
2004
- mod.mount || mod.default?.mount || (() => {
2005
- })
2006
- );
2007
- }
2008
- if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
2009
- if (!ns.unmountFns[url.href]) {
2010
- ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
2011
- }
2012
- ns.unmountFns[url.href]?.add(
2013
- mod.unmount || mod.default?.unmount || (() => {
2014
- })
2015
- );
2016
- }
2017
- return {
2018
- mount: mod.mount || mod.default?.mount,
2019
- unmount: mod.unmount || mod.default?.unmount
2020
- };
2021
- } catch (e) {
2022
- logError(
2023
- "StaticLoader",
2024
- `Error loading remote component script from "${script.src || url.href}".`,
2025
- e
2026
- );
2027
- return {
2028
- mount: void 0,
2029
- unmount: void 0
2030
- };
2031
- }
2032
- })
2033
- );
2034
- return mountUnmountSets.reduce(
2035
- (acc, { mount, unmount }) => {
2036
- if (typeof mount === "function") {
2037
- acc.mount.add(mount);
2038
- }
2039
- if (typeof unmount === "function") {
2040
- acc.unmount.add(unmount);
2041
- }
2042
- return acc;
2043
- },
2044
- {
2045
- mount: /* @__PURE__ */ new Set(),
2046
- unmount: /* @__PURE__ */ new Set()
2047
- }
2048
- );
2049
- }
2050
-
2051
- // src/host/shared/pipeline.ts
2052
- function preparePipeline(input) {
2053
- const parser = new DOMParser();
2054
- const doc = parser.parseFromString(input.html, "text/html");
2055
- const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2056
- const remoteShared = input.remoteShared ?? parsed.remoteShared;
2057
- if ("__remote_components_missing_shared__" in remoteShared) {
2058
- throw new RemoteComponentsError(
2059
- remoteShared.__remote_components_missing_shared__
2060
- );
2061
- }
2062
- applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2063
- const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2064
- return { doc, parsed, scriptDescriptors };
2065
- }
2066
- async function loadPrepared(input) {
2067
- const { prepared, url, signal, resolveClientUrl, container, rscName } = input;
2068
- const { doc, parsed, scriptDescriptors } = prepared;
2069
- if (signal.aborted) {
2070
- return { status: "aborted" };
2071
- }
2072
- const userShared = await input.shared;
2073
- if (signal.aborted) {
2074
- return { status: "aborted" };
2075
- }
2076
- if (parsed.isRemoteComponent) {
2077
- return loadStaticPath({
2078
- parsed,
2079
- doc,
2080
- url,
2081
- resolveClientUrl
2082
- });
2083
- }
2084
- return loadDynamicPath({
2085
- parsed,
2086
- doc,
2087
- url,
2088
- scriptDescriptors,
2089
- shared: userShared,
2090
- resolveClientUrl,
2091
- container,
2092
- rscName
2093
- });
2094
- }
2095
- function buildScriptDescriptors(scripts, url) {
2096
- return scripts.map((script) => {
2097
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2098
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2099
- prefix: void 0,
2100
- id: scriptSrc
2101
- };
2102
- return {
2103
- src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2104
- };
2105
- });
2106
- }
2107
- async function loadStaticPath(input) {
2108
- const { parsed, doc, url, resolveClientUrl } = input;
2109
- const scripts = Array.from(
2110
- parsed.component.querySelectorAll("script")
2111
- );
2112
- const { mount, unmount } = await loadStaticRemoteComponent(
2113
- scripts,
2114
- url,
2115
- resolveClientUrl
2116
- );
2117
- return {
2118
- status: "static",
2119
- mount,
2120
- unmount,
2121
- metadata: parsed.metadata,
2122
- parsed,
2123
- doc
2124
- };
2125
- }
2126
- async function loadDynamicPath(input) {
2127
- const {
2128
- parsed,
2129
- doc,
2130
- url,
2131
- scriptDescriptors,
2132
- shared,
2133
- resolveClientUrl,
2134
- container
2135
- } = input;
2136
- const rscName = input.rscName ?? (parsed.rsc ? `__remote_component_rsc_${escapeString(url.href)}_${escapeString(parsed.name)}` : void 0);
2137
- const rscData = parsed.rsc ? (parsed.rsc.textContent || "").split("\n").filter(Boolean) : [];
2138
- const result = await loadRemoteComponent({
2139
- url,
2140
- name: parsed.name,
2141
- rscName,
2142
- bundle: parsed.metadata.bundle,
2143
- route: parsed.metadata.route,
2144
- runtime: parsed.metadata.runtime,
2145
- data: rscData,
2146
- nextData: parsed.nextData,
2147
- scripts: scriptDescriptors,
2148
- shared: buildHostShared(shared, resolveClientUrl),
2149
- remoteShared: parsed.remoteShared,
2150
- container,
2151
- resolveClientUrl
2152
- });
2153
- if (result.error) {
2154
- return { status: "error", error: result.error };
2155
- }
2156
- return {
2157
- status: "loaded",
2158
- component: result.component,
2159
- metadata: parsed.metadata,
2160
- parsed,
2161
- doc
2162
- };
2163
- }
2164
-
2165
- // src/host/shared/state.ts
2166
- function createHostState() {
2167
- return {
2168
- stage: "idle",
2169
- prevSrc: void 0,
2170
- prevUrl: void 0,
2171
- prevName: void 0,
2172
- prevIsRemoteComponent: false,
2173
- abortController: void 0
2174
- };
2175
- }
2176
-
2177
- // src/host/utils/resolve-name-from-src.ts
2178
- function resolveNameFromSrc(src, defaultName) {
2179
- if (!src) {
2180
- return defaultName;
2181
- }
2182
- const hash = typeof src === "string" ? src : src.hash;
2183
- const hashIndex = hash.indexOf("#");
2184
- if (hashIndex < 0) {
2185
- return defaultName;
2186
- }
2187
- const name = hash.slice(hashIndex + 1);
2188
- return name || defaultName;
2189
- }
2190
-
2191
- // src/runtime/html/set-attributes-from-props.ts
2192
- var DOMAttributeNames = {
2193
- acceptCharset: "accept-charset",
2194
- className: "class",
2195
- htmlFor: "for",
2196
- httpEquiv: "http-equiv",
2197
- noModule: "noModule"
2198
- };
2199
- var ignoreProps = [
2200
- "onLoad",
2201
- "onReady",
2202
- "dangerouslySetInnerHTML",
2203
- "children",
2204
- "onError",
2205
- "strategy",
2206
- "stylesheets"
2207
- ];
2208
- function isBooleanScriptAttribute(attr) {
2209
- return ["async", "defer", "noModule"].includes(attr);
2210
- }
2211
- function setAttributesFromProps(el, props) {
2212
- for (const [p, value] of Object.entries(props)) {
2213
- if (!Object.hasOwn(props, p))
2214
- continue;
2215
- if (ignoreProps.includes(p))
2216
- continue;
2217
- if (value === void 0) {
2218
- continue;
2219
- }
2220
- const attr = DOMAttributeNames[p] || p.toLowerCase();
2221
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
2222
- el[attr] = Boolean(value);
2223
- } else {
2224
- el.setAttribute(attr, String(value));
2225
- }
2226
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
2227
- el.setAttribute(attr, "");
2228
- el.removeAttribute(attr);
2229
- }
2230
- }
2231
- }
2232
-
2233
- // src/host/react/hooks/use-resolve-client-url.ts
2234
- import { useMemo } from "react";
2235
- import { useRemoteComponentsContext } from "#internal/host/react/context";
2236
-
2237
- // src/runtime/url/resolve-client-url.ts
2238
- function withRemoteSrc(resolveClientUrl, remoteSrc) {
2239
- const remoteOrigin = parseOrigin(remoteSrc);
2240
- return (url) => {
2241
- const urlOrigin = parseOrigin(url);
2242
- if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
2243
- return void 0;
2244
- }
2245
- return resolveClientUrl(remoteSrc, url);
2246
- };
2247
- }
2248
- function parseOrigin(url) {
2249
- try {
2250
- return new URL(url).origin;
2251
- } catch {
2252
- return void 0;
2253
- }
2254
- }
2255
-
2256
- // src/runtime/url/default-resolve-client-url.ts
2257
- function bindResolveClientUrl(prop, remoteSrc) {
2258
- return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
2259
- }
2260
-
2261
- // src/host/react/hooks/use-resolve-client-url.ts
2262
- function useResolveClientUrl(prop, urlHref) {
2263
- const { resolveClientUrl: contextValue } = useRemoteComponentsContext();
2264
- const raw = prop ?? contextValue;
2265
- return useMemo(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2266
- }
2267
-
2268
- // src/host/react/hooks/use-shadow-root.ts
2269
- import { useLayoutEffect, useRef, useState } from "react";
2270
- function useShadowRoot({
2271
- isolate,
2272
- mode,
2273
- keySuffix
2274
- }) {
2275
- const shadowRootContainerRef = useRef(null);
2276
- const [shadowRoot, setShadowRoot] = useState(() => {
2277
- const shadowRoots = getNamespace().shadowRoots;
2278
- const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2279
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2280
- )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2281
- shadowRoots[keySuffix] = null;
2282
- return ssrShadowRoot;
2283
- });
2284
- useLayoutEffect(() => {
2285
- const shadowRoots = getNamespace().shadowRoots;
2286
- if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2287
- let shadowRootElement = null;
2288
- const element = document.querySelector(
2289
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2290
- );
2291
- shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2292
- if (!shadowRootElement && element) {
2293
- try {
2294
- shadowRootElement = element.attachShadow({ mode });
2295
- shadowRoots[keySuffix] = shadowRootElement;
2296
- } catch {
2297
- }
2298
- }
2299
- if (shadowRootElement) {
2300
- shadowRootElement.querySelectorAll("*:not(link)").forEach((node) => {
2301
- node.remove();
2302
- });
2303
- setShadowRoot(shadowRootElement);
2304
- }
2305
- } else if (isolate === false && shadowRoot) {
2306
- shadowRoots[keySuffix] = null;
2307
- setShadowRoot(null);
2308
- }
2309
- }, [isolate, shadowRoot, mode, keySuffix]);
2310
- return { shadowRoot, shadowRootContainerRef };
2311
- }
2312
-
2313
- // src/host/react/utils/extract-remote-html.ts
2314
- var DUMMY_FALLBACK = "http://remote-components-dummy-fallback";
2315
- function getRemoteComponentHtml(html) {
2316
- if (typeof document === "undefined")
2317
- return html;
2318
- const parser = new DOMParser();
2319
- const temp = parser.parseFromString(html, "text/html");
2320
- const ssrRemoteComponentContainer = temp.querySelector(
2321
- 'div[id^="__REMOTE_COMPONENT"]'
2322
- );
2323
- if (ssrRemoteComponentContainer) {
2324
- return ssrRemoteComponentContainer.innerHTML;
2325
- }
2326
- const remoteComponentContainer = temp.querySelectorAll(
2327
- `div[data-bundle][data-route][data-runtime][id^="${DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2328
- );
2329
- if (remoteComponentContainer.length > 0) {
2330
- return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
2331
- }
2332
- return "";
2333
- }
2334
-
2335
- // src/host/react/index.tsx
2336
- import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
2337
- import { createElement as createElement2 } from "react";
2338
- function ConsumeRemoteComponent({
2339
- src,
2340
- isolate,
2341
- mode = "open",
2342
- reset,
2343
- credentials: credentialsProp,
2344
- name: nameProp = DEFAULT_COMPONENT_NAME,
2345
- shared: sharedProp,
2346
- children,
2347
- onBeforeLoad,
2348
- onLoad,
2349
- onError,
2350
- onChange,
2351
- onRequest,
2352
- onResponse,
2353
- resolveClientUrl: resolveClientUrlProp
2354
- }) {
2355
- const instanceId = useId();
2356
- const { credentials: contextCredentials, shared: contextShared } = useRemoteComponentsContext2();
2357
- const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2358
- const shared = sharedProp ?? contextShared ?? {};
2359
- const emitter = useMemo2(
2360
- () => makeReactEmitter({ onBeforeLoad, onLoad, onError, onChange }),
2361
- [onBeforeLoad, onLoad, onError, onChange]
2362
- );
2363
- const name = useMemo2(
2364
- () => resolveNameFromSrc(src, nameProp),
2365
- [src, nameProp]
2366
- );
2367
- const [data, setData] = useState2(
2368
- null
2369
- );
2370
- const url = useMemo2(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2371
- const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);
2372
- const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
2373
- const keySuffix = `${escapeString(id)}_${escapeString(
2374
- data?.name ?? name
2375
- )}_${escapeString(instanceId)}`;
2376
- const [remoteComponent, setRemoteComponent] = useState2(null);
2377
- const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
2378
- isolate,
2379
- mode,
2380
- keySuffix
2381
- });
2382
- const htmlRef = useRef2(
2383
- typeof document !== "undefined" ? document.querySelector(
2384
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2385
- )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ?? document.querySelector(`div[data-bundle][data-route][id^="${name}"]`)?.innerHTML ?? document.querySelector("div[data-bundle][data-route]")?.innerHTML : null
2386
- );
2387
- const endTemplateRef = useRef2(null);
2388
- const childrenRef = useRef2(
2389
- typeof document !== "undefined" ? (() => {
2390
- let el = document.querySelector(`template[id="${name}_start"]`);
2391
- const elements = [];
2392
- while (el && el.id !== `${name}_end`) {
2393
- if (el.id !== `${name}_start` && !el.getAttribute("data-remote-component")) {
2394
- elements.push(el);
2395
- }
2396
- el = el.nextElementSibling;
2397
- }
2398
- return elements;
2399
- })() : []
2400
- );
2401
- const hostStateRef = useRef2(createHostState());
2402
- const componentHydrationHtml = useRef2(null);
2403
- const prevRemoteComponentContainerRef = useRef2(null);
2404
- const unmountRef = useRef2(null);
2405
- useLayoutEffect2(() => {
2406
- return () => {
2407
- delete getNamespace().shadowRoots[keySuffix];
2408
- };
2409
- }, [keySuffix]);
2410
- useLayoutEffect2(() => {
2411
- if (childrenRef.current.length > 0 && remoteComponent) {
2412
- childrenRef.current.forEach((el) => {
2413
- el.remove();
2414
- });
2415
- childrenRef.current = [];
2416
- }
2417
- }, [remoteComponent]);
2418
- useLayoutEffect2(() => {
2419
- if (shadowRoot && remoteComponent) {
2420
- const resetStyles = shadowRoot.querySelectorAll(
2421
- "style[data-remote-components-reset]"
2422
- );
2423
- if (resetStyles.length > 1) {
2424
- resetStyles.forEach((style, index) => {
2425
- if (index > 0 && style.getAttribute("data-remote-components-reset") !== "react") {
2426
- style.remove();
2427
- }
2428
- });
2429
- }
2430
- htmlRef.current = null;
2431
- let el = shadowRoot.childNodes[0] ?? null;
2432
- while (el && (!("id" in el) || el.id !== `${name}_start`)) {
2433
- const nextEl = el.nextSibling;
2434
- if (el.nodeName !== "LINK" && el.nodeName !== "STYLE") {
2435
- el.parentNode?.removeChild(el);
2436
- }
2437
- el = nextEl;
2438
- }
2439
- }
2440
- }, [shadowRoot, remoteComponent, name]);
2441
- useEffect(() => {
2442
- if (src && src !== hostStateRef.current.prevSrc) {
2443
- const previousSrc = hostStateRef.current.prevSrc;
2444
- const previousName = hostStateRef.current.prevName;
2445
- hostStateRef.current.prevSrc = src;
2446
- if (previousSrc !== null) {
2447
- htmlRef.current = null;
2448
- }
2449
- hostStateRef.current.abortController?.abort();
2450
- hostStateRef.current.abortController = new AbortController();
2451
- const { signal } = hostStateRef.current.abortController;
2452
- emitter.beforeLoad(src);
2453
- hostStateRef.current.stage = "loading";
2454
- startTransition(async () => {
2455
- try {
2456
- let html = getRemoteComponentHtml(
2457
- htmlRef.current ?? (endTemplateRef.current?.previousElementSibling?.tagName === "div" ? endTemplateRef.current.previousElementSibling.innerHTML : "")
2458
- );
2459
- if (!html && src) {
2460
- const fetchInit = {
2461
- credentials
2462
- };
2463
- const resolvedUrl = new URL(
2464
- resolveClientUrl?.(url.href) ?? url.href,
2465
- location.href
2466
- );
2467
- const res = await fetchWithHooks(resolvedUrl, fetchInit, {
2468
- onRequest,
2469
- onResponse,
2470
- abortController: hostStateRef.current.abortController
2471
- });
2472
- if (!res || !res.ok) {
2473
- throw await errorFromFailedFetch(url.href, resolvedUrl, res);
2474
- }
2475
- const remoteHtml = await res.text();
2476
- if (signal.aborted)
2477
- return;
2478
- htmlRef.current = remoteHtml;
2479
- html = getRemoteComponentHtml(remoteHtml);
2480
- }
2481
- if (signal.aborted)
2482
- return;
2483
- const userShared = await shared;
2484
- if (signal.aborted)
2485
- return;
2486
- const prepared = preparePipeline({
2487
- html,
2488
- name,
2489
- url,
2490
- shared: userShared,
2491
- resolveClientUrl
2492
- });
2493
- const { doc, parsed } = prepared;
2494
- const {
2495
- component,
2496
- name: remoteName,
2497
- isRemoteComponent,
2498
- metadata,
2499
- rsc,
2500
- remoteShared,
2501
- links: linkElements
2502
- } = parsed;
2503
- if (hostStateRef.current.prevIsRemoteComponent) {
2504
- if (shadowRoot) {
2505
- shadowRoot.innerHTML = "";
2506
- }
2507
- const prevUrl = hostStateRef.current.prevUrl;
2508
- if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2509
- const unmountPromises = Promise.all(
2510
- Array.from(unmountRef.current ?? []).map(
2511
- async (unmount) => unmount(
2512
- shadowRoot ?? prevRemoteComponentContainerRef.current
2513
- )
2514
- )
2515
- );
2516
- unmountRef.current = null;
2517
- await unmountPromises;
2518
- }
2519
- }
2520
- hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;
2521
- hostStateRef.current.prevUrl = url;
2522
- hostStateRef.current.prevName = remoteName;
2523
- const links = linkElements.map((link) => ({
2524
- href: new URL(link.getAttribute("href") ?? link.href, url).href,
2525
- ...link.getAttributeNames().reduce((acc, key) => {
2526
- if (key !== "href") {
2527
- acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
2528
- }
2529
- return acc;
2530
- }, {})
2531
- }));
2532
- const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
2533
- "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
2534
- );
2535
- if (!isRemoteComponent) {
2536
- const self = globalThis;
2537
- const prevNextScripts = self.__next_s;
2538
- const nextScripts = [];
2539
- self.__next_s = nextScripts;
2540
- await Promise.all(
2541
- Array.from(inlineScripts).filter(
2542
- (script) => !(script.id.endsWith("_shared") && script.getAttribute("type") === "application/json" && typeof script.getAttribute(
2543
- "data-remote-components-shared"
2544
- ) === "string")
2545
- ).map((script) => {
2546
- return new Promise((resolve) => {
2547
- if (script.textContent && !script.textContent.includes("self.__next_f=") && !script.textContent.includes("self.__next_f.push")) {
2548
- if (!script.getAttribute("type") || script.getAttribute("type") === "text/javascript" || script.getAttribute("type") === "application/javascript") {
2549
- const newScript = document.createElement("script");
2550
- const blob = new Blob([script.textContent], {
2551
- type: "application/javascript"
2552
- });
2553
- const blobUrl = URL.createObjectURL(blob);
2554
- newScript.onload = () => {
2555
- resolve(void 0);
2556
- URL.revokeObjectURL(blobUrl);
2557
- newScript.remove();
2558
- };
2559
- newScript.onerror = () => {
2560
- URL.revokeObjectURL(blobUrl);
2561
- newScript.remove();
2562
- resolve(void 0);
2563
- };
2564
- newScript.src = blobUrl;
2565
- document.body.appendChild(newScript);
2566
- } else {
2567
- resolve(void 0);
2568
- document.body.appendChild(script);
2569
- }
2570
- } else {
2571
- resolve(void 0);
2572
- }
2573
- });
2574
- })
2575
- );
2576
- nextScripts.forEach(([scriptSrc, props]) => {
2577
- const script = document.createElement("script");
2578
- if (scriptSrc) {
2579
- script.src = scriptSrc;
2580
- }
2581
- if (typeof props.children === "string") {
2582
- script.textContent = props.children;
2583
- }
2584
- setAttributesFromProps(script, props);
2585
- document.head.appendChild(script);
2586
- });
2587
- self.__next_s = prevNextScripts;
2588
- }
2589
- const rscName = rsc ? `__remote_component_rsc_${escapeString(id)}_${escapeString(
2590
- remoteName
2591
- )}` : void 0;
2592
- if (rsc) {
2593
- rsc.textContent = rsc.textContent?.replace(
2594
- new RegExp(`self\\["${remoteName}"\\]`, "g"),
2595
- `self["${rscName}"]`
2596
- ) ?? "";
2597
- document.body.appendChild(rsc);
2598
- }
2599
- const newData = {
2600
- ...metadata,
2601
- links,
2602
- remoteShared,
2603
- src: typeof src === "string" ? src : src.href,
2604
- serverUrl: url.href,
2605
- data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
2606
- };
2607
- componentHydrationHtml.current = `${Array.from(
2608
- doc.querySelectorAll("link,style")
2609
- ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
2610
- if (isRemoteComponent) {
2611
- if (previousSrc !== void 0) {
2612
- emitter.change({
2613
- previousSrc: previousSrc ?? null,
2614
- nextSrc: src,
2615
- previousName,
2616
- nextName: remoteName
2617
- });
2618
- }
2619
- setData(newData);
2620
- if (shadowRoot) {
2621
- const shadowRootHtml = reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>${component.innerHTML}` : component.innerHTML;
2622
- shadowRoot.innerHTML = shadowRootHtml;
2623
- htmlRef.current = null;
2624
- setRemoteComponent(null);
2625
- const { mount, unmount } = await loadStaticRemoteComponent(
2626
- Array.from(shadowRoot.querySelectorAll("script")),
2627
- url,
2628
- resolveClientUrl
2629
- );
2630
- unmountRef.current = unmount;
2631
- await Promise.all(
2632
- Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2633
- );
2634
- emitter.load(src);
2635
- } else if (isolate === false) {
2636
- setRemoteComponent(
2637
- // TODO: remove wrapper div by converting HTML to RSC or React tree
2638
- /* @__PURE__ */ jsx2(
2639
- "div",
2640
- {
2641
- dangerouslySetInnerHTML: { __html: component.innerHTML },
2642
- ref: prevRemoteComponentContainerRef
2643
- }
2644
- )
2645
- );
2646
- htmlRef.current = null;
2647
- const { mount, unmount } = await loadStaticRemoteComponent(
2648
- Array.from(component.querySelectorAll("script")),
2649
- url,
2650
- resolveClientUrl
2651
- );
2652
- unmountRef.current = unmount;
2653
- await Promise.all(
2654
- Array.from(mount).map(
2655
- (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
2656
- )
2657
- );
2658
- emitter.load(src);
2659
- }
2660
- hostStateRef.current.stage = "loaded";
2661
- } else {
2662
- const result = await loadPrepared({
2663
- prepared,
2664
- url,
2665
- signal,
2666
- shared: userShared,
2667
- resolveClientUrl,
2668
- container: shadowRoot,
2669
- rscName
2670
- });
2671
- if (rsc) {
2672
- rsc.remove();
2673
- }
2674
- setData(newData);
2675
- if (previousSrc !== void 0) {
2676
- emitter.change({
2677
- previousSrc: previousSrc ?? null,
2678
- nextSrc: src,
2679
- previousName,
2680
- nextName: remoteName
2681
- });
2682
- }
2683
- if (result.status === "aborted") {
2684
- return;
2685
- }
2686
- if (result.status === "error") {
2687
- hostStateRef.current.stage = "error";
2688
- setRemoteComponent(result.error);
2689
- emitter.error(result.error);
2690
- } else if (result.status === "loaded") {
2691
- hostStateRef.current.stage = "loaded";
2692
- setRemoteComponent(result.component);
2693
- emitter.load(src);
2694
- }
2695
- }
2696
- } catch (error) {
2697
- if (isAbortError(error)) {
2698
- hostStateRef.current.stage = "idle";
2699
- return;
2700
- }
2701
- hostStateRef.current.stage = "error";
2702
- setRemoteComponent(error);
2703
- emitter.error(error);
2704
- }
2705
- });
2706
- }
2707
- }, [
2708
- url,
2709
- src,
2710
- isolate,
2711
- credentials,
2712
- name,
2713
- shared,
2714
- shadowRoot,
2715
- reset,
2716
- id,
2717
- emitter.beforeLoad,
2718
- emitter.load,
2719
- emitter.error,
2720
- emitter.change,
2721
- onRequest,
2722
- onResponse,
2723
- resolveClientUrl
2724
- ]);
2725
- if (remoteComponent instanceof Error) {
2726
- throw remoteComponent;
2727
- }
2728
- const metadataJson = /* @__PURE__ */ jsx2("script", { "data-remote-component": true, type: "application/json", children: JSON.stringify({
2729
- name: data?.name || name,
2730
- bundle: data?.bundle || "default",
2731
- route: data?.route || DEFAULT_ROUTE,
2732
- runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2733
- }) });
2734
- const resetStyle = reset ? /* @__PURE__ */ jsx2("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2735
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement2(
2736
- "link",
2737
- {
2738
- ...link,
2739
- href: new URL(link.href, url).href,
2740
- key: JSON.stringify(link)
2741
- }
2742
- )) || null;
2743
- const componentToRender = /* @__PURE__ */ jsxs(Fragment, { children: [
2744
- resetStyle,
2745
- linksToRender,
2746
- remoteComponent ?? children
2747
- ] });
2748
- if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {
2749
- shadowRoot.innerHTML = componentHydrationHtml.current;
2750
- componentHydrationHtml.current = null;
2751
- if (hostStateRef.current.prevIsRemoteComponent) {
2752
- loadStaticRemoteComponent(
2753
- Array.from(shadowRoot.querySelectorAll("script")),
2754
- url,
2755
- resolveClientUrl
2756
- ).then(({ mount }) => {
2757
- return Promise.all(
2758
- Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2759
- );
2760
- }).then(() => {
2761
- if (src) {
2762
- emitter.load(src);
2763
- }
2764
- }).catch((e) => {
2765
- const error = new RemoteComponentsError(
2766
- `Error mounting remote component from "${url.href}"`,
2767
- {
2768
- cause: e
2769
- }
2770
- );
2771
- setRemoteComponent(error);
2772
- emitter.error(error);
2773
- });
2774
- }
2775
- }
2776
- if (isolate !== false) {
2777
- const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");
2778
- if (shadowRemoteComponentHtml) {
2779
- shadowRemoteComponentHtml.remove();
2780
- }
2781
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2782
- metadataJson,
2783
- /* @__PURE__ */ jsxs(
2784
- "div",
2785
- {
2786
- "data-remote-component-id": `shadowroot_${keySuffix}`,
2787
- id: `shadowroot_${data?.name ?? name}`,
2788
- ref: shadowRootContainerRef,
2789
- children: [
2790
- typeof document === "undefined" ? (
2791
- // eslint-disable-next-line react/no-unknown-property
2792
- /* @__PURE__ */ jsxs("template", { shadowrootmode: mode, children: [
2793
- typeof document === "undefined" ? /* @__PURE__ */ jsx2(
2794
- "div",
2795
- {
2796
- dangerouslySetInnerHTML: {
2797
- __html: `<img
2798
- alt="" decoding="async" style="display:none"
2799
- src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2800
- onload="(function(el){
2801
- // Capture the shadow root during SSR hydration so the client-side
2802
- // useShadowRoot hook can find it.
2803
- const root = el.getRootNode();
2804
- globalThis.__remote_components_shadowroot_${keySuffix}=root;
2805
- el.parentElement.remove();
2806
- })(this)"
2807
- />`
2808
- }
2809
- }
2810
- ) : null,
2811
- resetStyle,
2812
- linksToRender,
2813
- children
2814
- ] })
2815
- ) : null,
2816
- shadowRoot && remoteComponent ? createPortal(
2817
- /* @__PURE__ */ jsxs(Fragment, { children: [
2818
- /* @__PURE__ */ jsx2("template", { id: `${name}_start` }),
2819
- resetStyle,
2820
- linksToRender,
2821
- remoteComponent,
2822
- /* @__PURE__ */ jsx2("template", { id: `${name}_end`, ref: endTemplateRef })
2823
- ] }),
2824
- shadowRoot
2825
- ) : null
2826
- ]
2827
- }
2828
- )
2829
- ] });
2830
- }
2831
- htmlRef.current = null;
2832
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2833
- /* @__PURE__ */ jsx2("template", { id: `${name}_start` }),
2834
- metadataJson,
2835
- componentToRender,
2836
- /* @__PURE__ */ jsx2("template", { id: `${name}_end`, ref: endTemplateRef })
2837
- ] });
2838
- }
2
+ ConsumeRemoteComponent
3
+ } from "../chunk-GBFUPMMI.js";
4
+ import "../chunk-NZAB7REE.js";
5
+ import "../chunk-SZFCBE54.js";
6
+ import "../chunk-QKB74MLO.js";
7
+ import "../chunk-52BJ7VFA.js";
8
+ import "../chunk-LQ7VQ74E.js";
9
+ import "../chunk-SJM7AAGU.js";
10
+ import "../chunk-D5GNZB6O.js";
11
+ import "../chunk-S2A4TFLS.js";
12
+ import "../chunk-GAXJTFBV.js";
13
+ import "../chunk-X6YKUJKH.js";
14
+ import "../chunk-ENYGL5CO.js";
2839
15
  export {
2840
16
  ConsumeRemoteComponent
2841
17
  };