remote-components 0.0.5 → 0.0.6

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 (43) hide show
  1. package/dist/next/client.cjs +738 -0
  2. package/dist/next/client.cjs.map +1 -0
  3. package/dist/next/client.d.ts +11 -0
  4. package/dist/next/client.js +704 -0
  5. package/dist/next/client.js.map +1 -0
  6. package/dist/next/remote/render-client.cjs +19 -2
  7. package/dist/next/remote/render-client.cjs.map +1 -1
  8. package/dist/next/remote/render-client.js +10 -3
  9. package/dist/next/remote/render-client.js.map +1 -1
  10. package/dist/next/{host → server}/app-client.cjs +19 -3
  11. package/dist/next/server/app-client.cjs.map +1 -0
  12. package/dist/next/{host → server}/app-client.d.ts +1 -1
  13. package/dist/next/{host → server}/app-client.js +9 -3
  14. package/dist/next/server/app-client.js.map +1 -0
  15. package/dist/next/server/app-server.cjs.map +1 -0
  16. package/dist/next/server/app-server.js.map +1 -0
  17. package/dist/next/server/pages-client.cjs.map +1 -0
  18. package/dist/next/server/pages-client.js.map +1 -0
  19. package/dist/next/server/pages-server.cjs.map +1 -0
  20. package/dist/next/server/pages-server.js.map +1 -0
  21. package/dist/shared/client/remote-component.cjs +4 -3
  22. package/dist/shared/client/remote-component.cjs.map +1 -1
  23. package/dist/shared/client/remote-component.d.ts +2 -2
  24. package/dist/shared/client/remote-component.js +4 -3
  25. package/dist/shared/client/remote-component.js.map +1 -1
  26. package/package.json +37 -9
  27. package/dist/next/host/app-client.cjs.map +0 -1
  28. package/dist/next/host/app-client.js.map +0 -1
  29. package/dist/next/host/app-server.cjs.map +0 -1
  30. package/dist/next/host/app-server.js.map +0 -1
  31. package/dist/next/host/pages-client.cjs.map +0 -1
  32. package/dist/next/host/pages-client.js.map +0 -1
  33. package/dist/next/host/pages-server.cjs.map +0 -1
  34. package/dist/next/host/pages-server.js.map +0 -1
  35. /package/dist/next/{host → server}/app-server.cjs +0 -0
  36. /package/dist/next/{host → server}/app-server.d.ts +0 -0
  37. /package/dist/next/{host → server}/app-server.js +0 -0
  38. /package/dist/next/{host → server}/pages-client.cjs +0 -0
  39. /package/dist/next/{host → server}/pages-client.d.ts +0 -0
  40. /package/dist/next/{host → server}/pages-client.js +0 -0
  41. /package/dist/next/{host → server}/pages-server.cjs +0 -0
  42. /package/dist/next/{host → server}/pages-server.d.ts +0 -0
  43. /package/dist/next/{host → server}/pages-server.js +0 -0
@@ -0,0 +1,738 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/next/client/index.tsx
32
+ var client_exports = {};
33
+ __export(client_exports, {
34
+ RemoteComponent: () => RemoteComponent
35
+ });
36
+ module.exports = __toCommonJS(client_exports);
37
+ var import_react = require("react");
38
+ var import_react_dom = require("react-dom");
39
+
40
+ // src/shared/client/component-loader.ts
41
+ var React = __toESM(require("react"), 1);
42
+ var ReactDOM = __toESM(require("react-dom"), 1);
43
+ var ReactDOMClient = __toESM(require("react-dom/client"), 1);
44
+ var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
45
+ var JSXRuntime = __toESM(require("react/jsx-runtime"), 1);
46
+
47
+ // src/shared/webpack/shared-modules.ts
48
+ function applySharedModules(bundle, resolve) {
49
+ const self = globalThis;
50
+ if (self.__remote_webpack_require__?.[bundle]) {
51
+ const modulePaths = Object.keys(
52
+ self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
53
+ );
54
+ for (const [key, value] of Object.entries(resolve)) {
55
+ const ids = modulePaths.filter((p) => p.includes(key));
56
+ for (let id of ids) {
57
+ const webpackBundle = self.__remote_webpack_require__[bundle];
58
+ if (webpackBundle.m) {
59
+ if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {
60
+ id = `${self.__remote_webpack_module_map__[bundle][id]}`;
61
+ }
62
+ webpackBundle.m[id] = (module2) => {
63
+ module2.exports = value;
64
+ };
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ // src/shared/webpack/next-client-pages-loader.ts
72
+ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
73
+ const self = globalThis;
74
+ const nextCssOriginal = document.getElementById("__next_css__DO_NOT_USE__");
75
+ if (nextCssOriginal) {
76
+ nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
77
+ }
78
+ const nextCss = document.createElement("noscript");
79
+ nextCss.id = "__next_css__DO_NOT_USE__";
80
+ const lastNode = document.head.childNodes[document.head.childNodes.length - 1];
81
+ document.head.appendChild(nextCss);
82
+ const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
83
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}`)
84
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
85
+ (key) => key.includes("/next/dist/client/page-loader.js")
86
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
87
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}`)
88
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
89
+ (key) => key.includes("/next/dist/client/page-loader.js")
90
+ ) ?? ""] ?? -1;
91
+ const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
92
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
93
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
94
+ (key) => key.includes("/next/dist/client/page-loader.js")
95
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
96
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
97
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
98
+ (key) => key.includes("/next/dist/client/page-loader.js")
99
+ ) ?? ""] ?? -1;
100
+ if (!(componentLoaderChunk && appLoaderChunk)) {
101
+ throw new Error(
102
+ `Next.js client pages loader not found in bundle "${bundle}"`
103
+ );
104
+ }
105
+ const __NEXT_P_ORIGINAL = self.__NEXT_P;
106
+ const selfOriginal = self;
107
+ delete selfOriginal.__NEXT_P;
108
+ self.__remote_webpack_require__?.[bundle]?.(
109
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
110
+ );
111
+ if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
112
+ self.__remote_webpack_require__?.[bundle]?.(
113
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
114
+ );
115
+ }
116
+ if (self.__NEXT_P) {
117
+ const [, componentLoader] = self.__NEXT_P[0] ?? [
118
+ void 0,
119
+ () => ({ default: null })
120
+ ];
121
+ const [, appLoader] = self.__NEXT_P[2] ?? [
122
+ void 0,
123
+ () => ({
124
+ default: null
125
+ })
126
+ ];
127
+ const { default: Component } = componentLoader();
128
+ const { default: App } = appLoader();
129
+ const cssRE = /\.s?css$/;
130
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
131
+ self.__remote_webpack_require__?.[bundle]?.(id);
132
+ });
133
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
134
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
135
+ if (id) {
136
+ self.__remote_webpack_require__?.[bundle]?.(id);
137
+ }
138
+ });
139
+ if (styleContainer) {
140
+ let node = nextCss.previousSibling;
141
+ while (node && node !== lastNode) {
142
+ styleContainer.appendChild(node);
143
+ node = nextCss.previousSibling;
144
+ }
145
+ }
146
+ delete self.__NEXT_P;
147
+ self.__NEXT_P = __NEXT_P_ORIGINAL;
148
+ if (nextCssOriginal) {
149
+ nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
150
+ }
151
+ return { Component, App };
152
+ }
153
+ return { Component: null, App: null };
154
+ }
155
+
156
+ // src/shared/client/const.ts
157
+ var DEFAULT_ROUTE = "/";
158
+ var RUNTIME_WEBPACK = "webpack";
159
+ var RUNTIME_TURBOPACK = "turbopack";
160
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
161
+ function getBundleKey(bundle) {
162
+ return bundle.replace(/-/g, "_");
163
+ }
164
+
165
+ // src/shared/client/webpack-adapter.ts
166
+ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}) {
167
+ const self = globalThis;
168
+ if (!self.__remote_bundle_url__) {
169
+ self.__remote_bundle_url__ = {};
170
+ }
171
+ self.__remote_bundle_url__[bundle ?? "default"] = url;
172
+ await initializeSharedModules(bundle ?? "default", shared, remoteShared);
173
+ if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
174
+ if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
175
+ self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
176
+ self.__original_webpack_require__ = self.__webpack_require__;
177
+ }
178
+ self.__webpack_chunk_load__ = createChunkLoader(runtime);
179
+ self.__webpack_require__ = createModuleRequire(runtime);
180
+ self.__webpack_require_type__ = runtime;
181
+ if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
182
+ const remoteBundle = bundle ?? "default";
183
+ self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
184
+ self.__remote_webpack_require__[remoteBundle].type = "turbopack";
185
+ }
186
+ }
187
+ if (runtime === RUNTIME_TURBOPACK) {
188
+ await Promise.all(
189
+ scripts.map((script) => {
190
+ if (script.src) {
191
+ return self.__webpack_chunk_load__?.(script.src, bundle);
192
+ }
193
+ return Promise.resolve(void 0);
194
+ })
195
+ );
196
+ }
197
+ }
198
+ function createChunkLoader(runtime) {
199
+ return function __turbopack_chunk_load__(chunkId, scriptBundle) {
200
+ const self = globalThis;
201
+ const {
202
+ bundle,
203
+ id: path,
204
+ prefix
205
+ } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
206
+ bundle: scriptBundle ?? "",
207
+ id: chunkId
208
+ };
209
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
210
+ if (remoteRuntime === RUNTIME_WEBPACK) {
211
+ return Promise.resolve(void 0);
212
+ }
213
+ const url = new URL(
214
+ path ? `${prefix ?? ""}${path}`.replace(
215
+ /(?<char>[^:])(?<double>\/\/)/g,
216
+ "$1/"
217
+ ) : "/",
218
+ self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
219
+ ).href;
220
+ if (url.endsWith(".css")) {
221
+ return;
222
+ }
223
+ return new Promise((resolve, reject) => {
224
+ fetch(url).then((res) => res.text()).then((code) => {
225
+ if (code.includes("globalThis.TURBOPACK")) {
226
+ return handleTurbopackChunk(code, bundle ?? "", url);
227
+ }
228
+ }).then(resolve).catch(reject);
229
+ });
230
+ };
231
+ }
232
+ async function handleTurbopackChunk(code, bundle, url) {
233
+ if (code.includes("/next/dist/client/app-next-turbopack.js") && code.includes("importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS")) {
234
+ const preloadLinks = document.querySelectorAll(
235
+ `link[rel="preload"][href="${new URL(url).pathname}"]`
236
+ );
237
+ preloadLinks.forEach((preloadLink) => preloadLink.remove());
238
+ return;
239
+ }
240
+ const self = globalThis;
241
+ const bundleKey = getBundleKey(bundle);
242
+ const transformedCode = code.replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(
243
+ /TURBOPACK_WORKER_LOCATION/g,
244
+ `TURBOPACK_WORKER_LOCATION_${bundleKey}`
245
+ ).replace(
246
+ /TURBOPACK_NEXT_CHUNK_URLS/g,
247
+ `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
248
+ ).replace(
249
+ /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
250
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
251
+ ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
252
+ /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
253
+ `//# sourceMappingURL=${new URL(
254
+ ".",
255
+ new URL(
256
+ url,
257
+ self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
258
+ )
259
+ ).href}$1$2.js.map`
260
+ );
261
+ await new Promise((scriptResolve, scriptReject) => {
262
+ const blob = new Blob([transformedCode], {
263
+ type: "application/javascript; charset=UTF-8"
264
+ });
265
+ const scriptUrl = URL.createObjectURL(blob);
266
+ const script = document.createElement("script");
267
+ script.src = scriptUrl;
268
+ script.async = true;
269
+ script.onload = () => {
270
+ URL.revokeObjectURL(scriptUrl);
271
+ scriptResolve(void 0);
272
+ };
273
+ script.onerror = (error) => {
274
+ URL.revokeObjectURL(scriptUrl);
275
+ scriptReject(
276
+ new Error(
277
+ `Failed to load script: ${error instanceof Error ? error.message : String(error)}`
278
+ )
279
+ );
280
+ };
281
+ document.head.appendChild(script);
282
+ });
283
+ const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
284
+ const loadChunkLists = [];
285
+ while (chunkLists?.length) {
286
+ const { chunks } = chunkLists.shift() ?? { chunks: [] };
287
+ if (chunks.length > 0) {
288
+ chunks.forEach((id) => {
289
+ const chunkLoadResult = self.__webpack_chunk_load__?.(
290
+ `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
291
+ );
292
+ if (chunkLoadResult) {
293
+ loadChunkLists.push(chunkLoadResult);
294
+ }
295
+ });
296
+ }
297
+ }
298
+ if (loadChunkLists.length > 0) {
299
+ await Promise.all(loadChunkLists);
300
+ }
301
+ }
302
+ function createModuleRequire(runtime) {
303
+ return (id) => {
304
+ const self = globalThis;
305
+ const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? { bundle: "default", id };
306
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
307
+ try {
308
+ if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
309
+ return self.__remote_webpack_require__?.[bundle]?.(moduleId);
310
+ }
311
+ const sharedModule = getSharedModule(bundle ?? "default", moduleId ?? id);
312
+ if (sharedModule) {
313
+ return sharedModule;
314
+ }
315
+ if (bundle && moduleId) {
316
+ return handleTurbopackModule(bundle, moduleId, id);
317
+ }
318
+ throw new Error(`Module ${id} not found`);
319
+ } catch {
320
+ try {
321
+ return self.__original_webpack_require__?.(id);
322
+ } catch {
323
+ throw new Error(
324
+ `Module ${id} not found in remote component bundle ${bundle}`
325
+ );
326
+ }
327
+ }
328
+ };
329
+ }
330
+ function initializeSharedModules(bundle, shared = {}, remoteShared = {}) {
331
+ const self = globalThis;
332
+ self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
333
+ if (!self.__remote_shared_modules__[bundle]) {
334
+ self.__remote_shared_modules__[bundle] = {};
335
+ }
336
+ return Promise.all(
337
+ Object.entries(remoteShared).map(async ([id, module2]) => {
338
+ if (self.__remote_shared_modules__?.[bundle]) {
339
+ self.__remote_shared_modules__[bundle][id.replace("[app-ssr]", "[app-client]")] = await (shared[module2] ?? (() => Promise.resolve(
340
+ new Proxy(
341
+ {},
342
+ {
343
+ get(_, prop) {
344
+ if (prop !== "then") {
345
+ console.warn(
346
+ `Shared dependency "${module2}" not found for "${bundle}" when trying to import "${prop}".`
347
+ );
348
+ }
349
+ }
350
+ }
351
+ )
352
+ )))();
353
+ }
354
+ })
355
+ );
356
+ }
357
+ function getSharedModule(bundle, id) {
358
+ const self = globalThis;
359
+ for (const [key, value] of Object.entries(
360
+ self.__remote_shared_modules__?.[bundle] ?? {}
361
+ )) {
362
+ if (id.includes(key)) {
363
+ return value;
364
+ }
365
+ }
366
+ return null;
367
+ }
368
+ function handleTurbopackModule(bundle, moduleId, id) {
369
+ const self = globalThis;
370
+ const bundleKey = getBundleKey(bundle);
371
+ const modules = self[`TURBOPACK_${bundleKey}`]?.find((mod) => moduleId in mod[1])?.[1];
372
+ const moduleInit = modules?.[moduleId];
373
+ if (typeof moduleInit !== "function") {
374
+ throw new Error(
375
+ `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
376
+ );
377
+ }
378
+ const exports = {};
379
+ moduleInit({
380
+ // HMR not implemented for Remote Components
381
+ k: {
382
+ register() {
383
+ },
384
+ registerExports() {
385
+ },
386
+ signature() {
387
+ return () => {
388
+ };
389
+ }
390
+ },
391
+ s(m) {
392
+ for (const [key, value] of Object.entries(m)) {
393
+ exports[key] = value;
394
+ }
395
+ },
396
+ i(iid) {
397
+ return self.__webpack_require__?.(`[${bundle}] ${iid}`);
398
+ },
399
+ r(rid) {
400
+ return self.__webpack_require__?.(`[${bundle}] ${rid}`);
401
+ },
402
+ m: {
403
+ exports
404
+ }
405
+ });
406
+ for (const [key, value] of Object.entries(exports)) {
407
+ if (typeof value === "function") {
408
+ exports[key] = value();
409
+ }
410
+ }
411
+ return exports;
412
+ }
413
+
414
+ // src/shared/client/script-loader.ts
415
+ async function loadScripts(scripts) {
416
+ await Promise.all(
417
+ scripts.map((script) => {
418
+ return new Promise((resolve, reject) => {
419
+ const newSrc = new URL(
420
+ // remove the remote component bundle name identifier from the script src
421
+ script.src.replace(/\/_next\/\[.+\](?<whitespace>%20| )/, "/_next/"),
422
+ location.origin
423
+ ).href;
424
+ const newScript = document.createElement("script");
425
+ newScript.onload = () => {
426
+ resolve();
427
+ };
428
+ newScript.onerror = () => {
429
+ reject(
430
+ new Error(
431
+ `Failed to load script ${script.src} for remote component`
432
+ )
433
+ );
434
+ };
435
+ newScript.src = newSrc;
436
+ newScript.async = true;
437
+ document.head.appendChild(newScript);
438
+ });
439
+ })
440
+ );
441
+ }
442
+
443
+ // src/shared/client/rsc.ts
444
+ function fixPayload(payload) {
445
+ if (Array.isArray(payload)) {
446
+ if (payload[0] === "$") {
447
+ fixPayload(payload[3]);
448
+ if (payload.length === 4) {
449
+ payload.push(null, null, 1);
450
+ }
451
+ } else {
452
+ for (const item of payload) {
453
+ fixPayload(item);
454
+ }
455
+ }
456
+ } else if (typeof payload === "object" && payload !== null) {
457
+ for (const key in payload) {
458
+ fixPayload(payload[key]);
459
+ }
460
+ }
461
+ }
462
+ function createRSCStream(name, data) {
463
+ return new ReadableStream({
464
+ type: "bytes",
465
+ start(controller) {
466
+ const encoder = new TextEncoder();
467
+ const self = globalThis;
468
+ if (!self[name] && data.length > 0) {
469
+ data.forEach((chunk) => {
470
+ const lines = chunk.split("\n");
471
+ for (const line of lines) {
472
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
473
+ if (match?.groups?.rsc) {
474
+ self[name] = self[name] ?? [];
475
+ self[name].push(JSON.parse(`"${match.groups.rsc}"`));
476
+ }
477
+ }
478
+ });
479
+ }
480
+ const allChunks = (self[name] ?? [`0:[null]
481
+ `]).join("");
482
+ allChunks.split("\n").forEach((chunk) => {
483
+ if (chunk.length > 0) {
484
+ const { id, prefix, payload } = /(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
485
+ chunk
486
+ )?.groups ?? {};
487
+ if (payload) {
488
+ const jsonPayload = JSON.parse(payload);
489
+ fixPayload(jsonPayload);
490
+ const reconstruct = `${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
491
+ controller.enqueue(encoder.encode(`${reconstruct}
492
+ `));
493
+ } else {
494
+ controller.enqueue(encoder.encode(`${chunk}
495
+ `));
496
+ }
497
+ } else {
498
+ controller.enqueue(encoder.encode(`${chunk}
499
+ `));
500
+ }
501
+ });
502
+ controller.close();
503
+ }
504
+ });
505
+ }
506
+
507
+ // src/shared/client/component-loader.ts
508
+ async function loadRemoteComponent({
509
+ url,
510
+ name,
511
+ bundle,
512
+ route = "/",
513
+ runtime = "webpack",
514
+ data,
515
+ nextData,
516
+ scripts = [],
517
+ shared = Promise.resolve({}),
518
+ remoteShared = {},
519
+ container
520
+ }) {
521
+ try {
522
+ if (runtime === "webpack") {
523
+ const self = globalThis;
524
+ self.__DISABLE_WEBPACK_EXEC__ = true;
525
+ await loadScripts(scripts);
526
+ }
527
+ await setupWebpackRuntime(
528
+ runtime,
529
+ scripts,
530
+ url,
531
+ bundle,
532
+ await shared,
533
+ remoteShared
534
+ );
535
+ if (bundle) {
536
+ const resolve = {
537
+ "/react/index.js": React,
538
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
539
+ "/react/jsx-runtime.js": JSXRuntime,
540
+ "/react-dom/index.js": ReactDOM,
541
+ "/react-dom/client.js": ReactDOMClient
542
+ };
543
+ applySharedModules(bundle, resolve);
544
+ }
545
+ if (data.length > 0) {
546
+ return await loadRSCComponent(name, data);
547
+ } else if (nextData) {
548
+ return loadNextPagesComponent(bundle, route, nextData, name, container);
549
+ }
550
+ return loadRSCComponent(name, [`0:[null]
551
+ `]);
552
+ } catch (error) {
553
+ return {
554
+ component: null,
555
+ error: error instanceof Error ? error : new Error(String(error))
556
+ };
557
+ }
558
+ }
559
+ async function loadRSCComponent(name, data) {
560
+ const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
561
+ const stream = createRSCStream(name, data);
562
+ const component = createFromReadableStream(stream);
563
+ return { component };
564
+ }
565
+ function loadNextPagesComponent(bundle, route, nextData, name, container) {
566
+ const { Component, App } = nextClientPagesLoader(bundle, route, container);
567
+ if (!Component) {
568
+ throw new Error(
569
+ `Remote component ${name} is trying to load the component for route ${route} but it is not available.`
570
+ );
571
+ }
572
+ const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
573
+ return { component };
574
+ }
575
+
576
+ // src/next/client/index.tsx
577
+ var import_jsx_runtime = require("react/jsx-runtime");
578
+ async function tryImportShared() {
579
+ try {
580
+ const { shared } = await import("@remote-component/shared/host");
581
+ return shared;
582
+ } catch {
583
+ return {};
584
+ }
585
+ }
586
+ function RemoteComponent({
587
+ src,
588
+ isolate,
589
+ credentials = "same-origin",
590
+ name = "__vercel_remote_component",
591
+ children
592
+ }) {
593
+ const [data, setData] = (0, import_react.useState)(null);
594
+ const [remoteComponent, setRemoteComponent] = (0, import_react.useState)(null);
595
+ const shadowRootContainerRef = (0, import_react.useRef)(null);
596
+ const [shadowRoot, setShadowRoot] = (0, import_react.useState)(null);
597
+ (0, import_react.useEffect)(() => {
598
+ if (shadowRootContainerRef.current) {
599
+ const shadow = shadowRootContainerRef.current.attachShadow({
600
+ mode: "open"
601
+ });
602
+ setShadowRoot(shadow);
603
+ }
604
+ }, [shadowRootContainerRef]);
605
+ const url = (0, import_react.useMemo)(
606
+ () => typeof document !== "undefined" ? new URL(src, location.href) : new URL(src),
607
+ [src]
608
+ );
609
+ (0, import_react.useEffect)(() => {
610
+ let mounted = true;
611
+ (async () => {
612
+ const fetchInit = {
613
+ method: "GET",
614
+ headers: {
615
+ Accept: "text/html",
616
+ // pass the public address of the remote component to the server used for module map mutation
617
+ "Vercel-Remote-Component-Url": url.href
618
+ },
619
+ credentials
620
+ };
621
+ const res = await fetch(url, fetchInit);
622
+ if (!res.ok) {
623
+ throw new Error(
624
+ `Failed to fetch remote component "${name}": ${res.status}`
625
+ );
626
+ }
627
+ const html = await res.text();
628
+ const doc = document.createElement("div");
629
+ doc.innerHTML = html;
630
+ const component = doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component
631
+ doc.querySelector("div[data-bundle][data-route]") ?? // fallback to Next.js Pages Router
632
+ doc.querySelector("div#__next");
633
+ const nextData = JSON.parse(
634
+ (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
635
+ );
636
+ const remoteName = component?.getAttribute("id")?.replace(/_ssr$/, "") || (nextData ? "__next" : name);
637
+ const rsc = doc.querySelector(`#${remoteName}_rsc`);
638
+ const bundle = component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default";
639
+ const metadata = {
640
+ name: remoteName,
641
+ bundle,
642
+ route: component?.getAttribute("data-route") ?? nextData?.page ?? DEFAULT_ROUTE,
643
+ runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_WEBPACK)
644
+ };
645
+ const remoteSharedEl = doc.querySelector(`#${remoteName}_shared`);
646
+ const remoteShared = JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {};
647
+ remoteSharedEl?.parentElement?.removeChild(remoteSharedEl);
648
+ if (!component || !(rsc || nextData)) {
649
+ throw new Error(`Failed to find component with id "${remoteName}"`);
650
+ }
651
+ const links = Array.from(
652
+ doc.querySelectorAll("link[href]")
653
+ ).map((link) => ({
654
+ rel: link.rel,
655
+ href: new URL(link.getAttribute("href") ?? link.href, url).href,
656
+ as: link.getAttribute("as") || void 0
657
+ }));
658
+ const scripts = doc.querySelectorAll(
659
+ "script[src],script[data-src]"
660
+ );
661
+ if (mounted) {
662
+ if (rsc) {
663
+ document.body.appendChild(rsc);
664
+ }
665
+ const newData = {
666
+ ...metadata,
667
+ links,
668
+ remoteShared,
669
+ url: url.href,
670
+ data: rsc ? (rsc.textContent ?? "").split("\n").filter(Boolean) : []
671
+ };
672
+ setData(newData);
673
+ loadRemoteComponent({
674
+ url: new URL(url, location.origin),
675
+ name,
676
+ bundle,
677
+ route: metadata.route,
678
+ runtime: metadata.runtime,
679
+ data: newData.data,
680
+ nextData: void 0,
681
+ scripts: Array.from(scripts).map((script) => ({
682
+ src: new URL(
683
+ script.getAttribute("data-src") || script.getAttribute("src") || script.src,
684
+ url
685
+ ).href
686
+ })),
687
+ shared: tryImportShared(),
688
+ remoteShared,
689
+ container: void 0
690
+ }).then((result) => {
691
+ if (mounted) {
692
+ if (result.error) {
693
+ setRemoteComponent(result.error);
694
+ } else {
695
+ setRemoteComponent(result.component);
696
+ }
697
+ }
698
+ }).catch((error) => {
699
+ if (mounted) {
700
+ setRemoteComponent(error);
701
+ }
702
+ });
703
+ }
704
+ })().catch((error) => {
705
+ if (mounted) {
706
+ setRemoteComponent(error);
707
+ }
708
+ });
709
+ return () => {
710
+ mounted = false;
711
+ };
712
+ }, [url, src, isolate, credentials, name]);
713
+ if (remoteComponent instanceof Error) {
714
+ throw remoteComponent;
715
+ }
716
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
717
+ "link",
718
+ {
719
+ as: link.as,
720
+ href: new URL(link.href, url).href,
721
+ rel: link.rel
722
+ },
723
+ `${link.href}_${link.rel}`
724
+ )) || null;
725
+ const componentToRender = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
726
+ linksToRender,
727
+ remoteComponent ?? children
728
+ ] });
729
+ if (isolate !== false) {
730
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { id: `shadowroot_${name}`, ref: shadowRootContainerRef, children: shadowRoot ? (0, import_react_dom.createPortal)(componentToRender, shadowRoot) : null });
731
+ }
732
+ return componentToRender;
733
+ }
734
+ // Annotate the CommonJS export names for ESM import in node:
735
+ 0 && (module.exports = {
736
+ RemoteComponent
737
+ });
738
+ //# sourceMappingURL=client.cjs.map