remote-components 0.2.2 → 0.3.1

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 (100) hide show
  1. package/dist/config/nextjs.cjs +2 -4
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.d.ts +1 -1
  4. package/dist/config/nextjs.js +2 -4
  5. package/dist/config/nextjs.js.map +1 -1
  6. package/dist/host/html.cjs +128 -112
  7. package/dist/host/html.cjs.map +1 -1
  8. package/dist/host/html.js +128 -115
  9. package/dist/host/html.js.map +1 -1
  10. package/dist/host/nextjs/app/client-only.cjs +233 -259
  11. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  12. package/dist/host/nextjs/app/client-only.js +234 -260
  13. package/dist/host/nextjs/app/client-only.js.map +1 -1
  14. package/dist/host/nextjs/app.cjs +5 -6
  15. package/dist/host/nextjs/app.cjs.map +1 -1
  16. package/dist/host/nextjs/app.js +5 -6
  17. package/dist/host/nextjs/app.js.map +1 -1
  18. package/dist/host/nextjs/pages.cjs +7 -19
  19. package/dist/host/nextjs/pages.cjs.map +1 -1
  20. package/dist/host/nextjs/pages.js +11 -20
  21. package/dist/host/nextjs/pages.js.map +1 -1
  22. package/dist/host/react.cjs +101 -93
  23. package/dist/host/react.cjs.map +1 -1
  24. package/dist/host/react.js +101 -93
  25. package/dist/host/react.js.map +1 -1
  26. package/dist/internal/host/nextjs/app-client.cjs +3 -8
  27. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  28. package/dist/internal/host/nextjs/app-client.js +4 -9
  29. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  30. package/dist/internal/host/nextjs/dom-flight.cjs +16 -7
  31. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  32. package/dist/internal/host/nextjs/dom-flight.d.ts +2 -2
  33. package/dist/internal/host/nextjs/dom-flight.js +16 -7
  34. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  35. package/dist/internal/host/nextjs/image-shared.cjs +25 -15
  36. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  37. package/dist/internal/host/nextjs/image-shared.d.ts +19 -6
  38. package/dist/internal/host/nextjs/image-shared.js +24 -14
  39. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  40. package/dist/internal/host/react/hooks/use-resolve-client-url.cjs +1 -5
  41. package/dist/internal/host/react/hooks/use-resolve-client-url.cjs.map +1 -1
  42. package/dist/internal/host/react/hooks/use-resolve-client-url.d.ts +1 -4
  43. package/dist/internal/host/react/hooks/use-resolve-client-url.js +1 -5
  44. package/dist/internal/host/react/hooks/use-resolve-client-url.js.map +1 -1
  45. package/dist/internal/host/server/fetch-remote-component.cjs +164 -149
  46. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  47. package/dist/internal/host/server/fetch-remote-component.js +166 -149
  48. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  49. package/dist/internal/host/shared/polyfill.cjs +10 -65
  50. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  51. package/dist/internal/host/shared/polyfill.d.ts +1 -3
  52. package/dist/internal/host/shared/polyfill.js +9 -63
  53. package/dist/internal/host/shared/polyfill.js.map +1 -1
  54. package/dist/internal/host/shared/remote-image-loader.cjs +53 -0
  55. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -0
  56. package/dist/internal/host/shared/remote-image-loader.d.ts +30 -0
  57. package/dist/internal/host/shared/remote-image-loader.js +29 -0
  58. package/dist/internal/host/shared/remote-image-loader.js.map +1 -0
  59. package/dist/internal/runtime/constants.cjs +6 -6
  60. package/dist/internal/runtime/constants.cjs.map +1 -1
  61. package/dist/internal/runtime/constants.d.ts +3 -3
  62. package/dist/internal/runtime/constants.js +4 -4
  63. package/dist/internal/runtime/constants.js.map +1 -1
  64. package/dist/internal/runtime/html/parse-remote-html.cjs +11 -15
  65. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  66. package/dist/internal/runtime/html/parse-remote-html.d.ts +2 -12
  67. package/dist/internal/runtime/html/parse-remote-html.js +17 -15
  68. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  69. package/dist/internal/runtime/loaders/script-loader.cjs +2 -2
  70. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  71. package/dist/internal/runtime/loaders/script-loader.js +1 -1
  72. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  73. package/dist/internal/runtime/metadata.cjs +42 -0
  74. package/dist/internal/runtime/metadata.cjs.map +1 -1
  75. package/dist/internal/runtime/metadata.d.ts +21 -1
  76. package/dist/internal/runtime/metadata.js +38 -0
  77. package/dist/internal/runtime/metadata.js.map +1 -1
  78. package/dist/internal/runtime/patterns.cjs +38 -0
  79. package/dist/internal/runtime/patterns.cjs.map +1 -0
  80. package/dist/internal/runtime/patterns.d.ts +5 -0
  81. package/dist/internal/runtime/patterns.js +12 -0
  82. package/dist/internal/runtime/patterns.js.map +1 -0
  83. package/dist/internal/runtime/turbopack/chunk-loader.cjs +4 -3
  84. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  85. package/dist/internal/runtime/turbopack/chunk-loader.js +1 -1
  86. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  87. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +11 -2
  88. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  89. package/dist/internal/runtime/turbopack/webpack-runtime.js +10 -2
  90. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  91. package/dist/remote/nextjs/app.cjs +2 -1
  92. package/dist/remote/nextjs/app.cjs.map +1 -1
  93. package/dist/remote/nextjs/app.js +2 -1
  94. package/dist/remote/nextjs/app.js.map +1 -1
  95. package/package.json +1 -1
  96. package/dist/internal/host/nextjs/image-impl.cjs +0 -64
  97. package/dist/internal/host/nextjs/image-impl.cjs.map +0 -1
  98. package/dist/internal/host/nextjs/image-impl.d.ts +0 -10
  99. package/dist/internal/host/nextjs/image-impl.js +0 -40
  100. package/dist/internal/host/nextjs/image-impl.js.map +0 -1
@@ -37,11 +37,149 @@ var import_skeleton = require("#internal/host/nextjs/skeleton");
37
37
  var import_fetch_with_hooks = require("#internal/host/server/fetch-with-hooks");
38
38
  var import_get_client_src = require("#internal/host/server/get-client-src");
39
39
  var import_get_ssr_relative_path_base_url = require("#internal/host/server/get-ssr-relative-path-base-url");
40
+ var import_metadata = require("#internal/runtime/metadata");
40
41
  var import_error = require("#internal/utils/error");
41
- const CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;
42
- async function fetchRemoteComponent(src, options = {
43
- rsc: false
44
- }) {
42
+ async function buildRscComponent(rsc, serverUrl) {
43
+ const componentRSC = `0:${JSON.stringify(rsc)}
44
+ `;
45
+ const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.edge");
46
+ return createFromReadableStream(
47
+ new ReadableStream({
48
+ type: "bytes",
49
+ start(controller) {
50
+ const encoder = new TextEncoder();
51
+ controller.enqueue(encoder.encode(componentRSC));
52
+ controller.close();
53
+ }
54
+ }),
55
+ {
56
+ serverConsumerManifest: {
57
+ moduleLoading: {
58
+ prefix: serverUrl.origin,
59
+ crossOrigin: true
60
+ },
61
+ moduleMap: {}
62
+ }
63
+ }
64
+ );
65
+ }
66
+ function buildSkeletonResponse(serverUrl, metadata, skeletonComponent) {
67
+ return {
68
+ name: "remote-component-skeleton",
69
+ serverUrl,
70
+ metadata: {
71
+ ...metadata,
72
+ type: "remote-component"
73
+ },
74
+ rsc: (0, import_skeleton.getSkeletonMessage)(),
75
+ scripts: [],
76
+ links: [],
77
+ hydrationData: [],
78
+ nextData: void 0,
79
+ component: skeletonComponent,
80
+ html: (0, import_skeleton.getSkeletonHtml)(serverUrl.href),
81
+ remoteShared: {}
82
+ };
83
+ }
84
+ function visitFragment(fragment, serverUrl, remoteName) {
85
+ const scriptSrcSet = /* @__PURE__ */ new Set();
86
+ const scriptTextSet = /* @__PURE__ */ new Set();
87
+ const scripts = [];
88
+ const linkKeySet = /* @__PURE__ */ new Set();
89
+ const links = [];
90
+ const hydrationData = [];
91
+ const htmlChunks = /* @__PURE__ */ new Set();
92
+ let metadata;
93
+ let nextData;
94
+ let remoteShared = {};
95
+ let hasRSC = false;
96
+ let hasShared = false;
97
+ let error;
98
+ const rsc = (0, import_dom_flight.visit)(fragment, {
99
+ url: serverUrl,
100
+ name: remoteName,
101
+ onMetadata(attrs) {
102
+ const incoming = (0, import_metadata.buildMetadata)(attrs, serverUrl);
103
+ if (!remoteName && metadata && metadata.id !== incoming.id && incoming.id !== "__next" && metadata.id !== "__next" && !nextData) {
104
+ throw (0, import_error.multipleRemoteComponentsError)(serverUrl.href);
105
+ }
106
+ metadata = incoming;
107
+ },
108
+ onScript(attrs) {
109
+ const clientSrc = (0, import_get_client_src.getClientSrc)(attrs.src, serverUrl.href);
110
+ const textContent = typeof attrs.textContent === "string" ? attrs.textContent : void 0;
111
+ if (textContent) {
112
+ if (!scriptTextSet.has(textContent)) {
113
+ scriptTextSet.add(textContent);
114
+ scripts.push({ src: "", textContent });
115
+ }
116
+ } else if (!scriptSrcSet.has(clientSrc)) {
117
+ scriptSrcSet.add(clientSrc);
118
+ scripts.push({ src: clientSrc });
119
+ }
120
+ },
121
+ onLink(attrs) {
122
+ const relativeAttrs = {
123
+ ...attrs,
124
+ href: (0, import_get_client_src.getClientSrc)(attrs.href, serverUrl.href)
125
+ };
126
+ const linkKey = `${relativeAttrs.href}::${attrs.rel}`;
127
+ if (!linkKeySet.has(linkKey)) {
128
+ linkKeySet.add(linkKey);
129
+ links.push(relativeAttrs);
130
+ }
131
+ },
132
+ onRSC(chunk) {
133
+ hydrationData.push(chunk);
134
+ hasRSC = true;
135
+ },
136
+ onNextData(data) {
137
+ nextData = data;
138
+ },
139
+ onHTML(chunk) {
140
+ if (!htmlChunks.has(chunk)) {
141
+ htmlChunks.add(chunk);
142
+ }
143
+ },
144
+ onShared(_shared) {
145
+ remoteShared = _shared;
146
+ hasShared = true;
147
+ },
148
+ onError(message, stack) {
149
+ error = new import_error.RemoteComponentsError(message);
150
+ if (stack) {
151
+ error.stack = stack;
152
+ }
153
+ }
154
+ });
155
+ if (error) {
156
+ throw error;
157
+ }
158
+ if (metadata) {
159
+ if (!hasRSC && !nextData && metadata.type === "nextjs") {
160
+ throw new import_error.RemoteComponentsError(
161
+ `The Remote Component at "${serverUrl.href}" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`
162
+ );
163
+ }
164
+ if (metadata.type === "nextjs" && !hasShared && !nextData?.props.__REMOTE_COMPONENT__?.shared) {
165
+ throw new import_error.RemoteComponentsError(
166
+ `No shared dependencies found for Remote Component at "${serverUrl.href}". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`
167
+ );
168
+ }
169
+ }
170
+ const resolvedShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared;
171
+ return {
172
+ rsc,
173
+ metadata,
174
+ scripts,
175
+ links,
176
+ hydrationData,
177
+ nextData,
178
+ remoteShared: resolvedShared,
179
+ html: Array.from(htmlChunks).join("")
180
+ };
181
+ }
182
+ async function fetchRemoteComponent(src, options = {}) {
45
183
  const ssrRelativePathBaseUrl = (0, import_get_ssr_relative_path_base_url.getSSRRelativePathBaseUrl)();
46
184
  const serverUrl = new URL(src, ssrRelativePathBaseUrl);
47
185
  const tags = [
@@ -94,122 +232,36 @@ async function fetchRemoteComponent(src, options = {
94
232
  parser.tokenizer.write(decoder.decode(chunk), false);
95
233
  }
96
234
  const fragment = parser.getFragment();
97
- let metadata = {
98
- bundle: CURRENT_ZONE ?? "__vercel_remote_component",
99
- route: "/",
100
- runtime: "webpack",
101
- id: "__vercel_remote_component",
102
- type: "unknown"
103
- };
104
- let remoteShared = {};
105
- const scripts = [];
106
- const links = [];
107
- const hydrationData = [];
108
- let nextData;
109
- let html = "";
110
235
  const remoteName = options.name || (serverUrl.hash ? serverUrl.hash.substring(1) : void 0);
111
- let hasRemoteComponent = false;
112
- let hasRSC = false;
113
- let hasShared = false;
114
- let hasMultipleRemoteComponents = false;
115
- let error;
116
- const rsc = (0, import_dom_flight.visit)(fragment, {
117
- url: serverUrl,
118
- name: remoteName,
119
- onMetadata(_metadata) {
120
- if (hasRemoteComponent && metadata.id !== _metadata.id && _metadata.id !== "__next" && metadata.id !== "__next" && !nextData) {
121
- hasMultipleRemoteComponents = true;
122
- }
123
- metadata = _metadata;
124
- hasRemoteComponent = true;
125
- },
126
- onScript(attrs) {
127
- const clientSrc = (0, import_get_client_src.getClientSrc)(attrs.src, serverUrl.href);
128
- if (!scripts.find(
129
- (it) => it.src === clientSrc || attrs.textContent && it.textContent === attrs.textContent
130
- )) {
131
- scripts.push(
132
- typeof attrs.textContent === "string" ? {
133
- src: "",
134
- textContent: attrs.textContent
135
- } : {
136
- src: clientSrc
137
- }
138
- );
139
- }
140
- },
141
- onLink(attrs) {
142
- const relativeAttrs = {
143
- ...attrs,
144
- href: (0, import_get_client_src.getClientSrc)(attrs.href, serverUrl.href)
145
- };
146
- if (!links.find(
147
- (it) => it.href === relativeAttrs.href && it.rel === attrs.rel
148
- )) {
149
- links.push(relativeAttrs);
150
- }
151
- },
152
- onRSC(chunk) {
153
- hydrationData.push(chunk);
154
- hasRSC = true;
155
- },
156
- onNextData(data) {
157
- nextData = data;
158
- if (data.props.__REMOTE_COMPONENT__) {
159
- Object.assign(metadata, data.props.__REMOTE_COMPONENT__);
160
- metadata.id = "__next";
161
- metadata.route = data.page ?? "/";
162
- }
163
- },
164
- onHTML(_html) {
165
- if (!html.includes(_html)) {
166
- html += _html;
167
- }
168
- },
169
- onShared(_shared) {
170
- remoteShared = _shared;
171
- hasShared = true;
172
- },
173
- onError(message, stack) {
174
- error = new import_error.RemoteComponentsError(message);
175
- if (stack) {
176
- error.stack = stack;
177
- }
178
- }
179
- });
180
- if (error) {
181
- throw error;
182
- }
183
- if (!hasRemoteComponent) {
236
+ const {
237
+ rsc,
238
+ metadata,
239
+ scripts,
240
+ links,
241
+ hydrationData,
242
+ nextData,
243
+ remoteShared,
244
+ html
245
+ } = visitFragment(fragment, serverUrl, remoteName);
246
+ if (!metadata) {
184
247
  const isSSGBuild = process.env.NEXT_PHASE === "phase-production-build";
185
248
  const isSSRRelativePathBase = serverUrl.host === new URL(ssrRelativePathBaseUrl).host;
186
249
  const isPreview = process.env.VERCEL_TARGET_ENV === "preview";
187
250
  if (isSSGBuild && isSSRRelativePathBase && isPreview && options.appRouter) {
188
- const skeletonMessage = (0, import_skeleton.getSkeletonMessage)();
189
- const skeletonHtml = (0, import_skeleton.getSkeletonHtml)(serverUrl.href);
190
251
  let skeletonComponent;
191
252
  if (options.rsc) {
192
253
  const { createElement } = await import("react");
193
254
  skeletonComponent = createElement("div", {
194
- dangerouslySetInnerHTML: { __html: skeletonHtml }
255
+ dangerouslySetInnerHTML: {
256
+ __html: (0, import_skeleton.getSkeletonHtml)(serverUrl.href)
257
+ }
195
258
  });
196
259
  }
197
- return {
198
- name: "remote-component-skeleton",
260
+ return buildSkeletonResponse(
199
261
  serverUrl,
200
- metadata: {
201
- ...metadata,
202
- type: "remote-component"
203
- },
204
- rsc: skeletonMessage,
205
- scripts: [],
206
- links: [],
207
- hydrationData: [],
208
- nextData: void 0,
209
- component: skeletonComponent,
210
- html: skeletonHtml,
211
- remoteShared: {}
212
- };
262
+ (0, import_metadata.buildMetadata)({}, serverUrl),
263
+ skeletonComponent
264
+ );
213
265
  }
214
266
  throw (0, import_error.failedToFetchRemoteComponentError)(
215
267
  serverUrl.href,
@@ -217,47 +269,10 @@ async function fetchRemoteComponent(src, options = {
217
269
  `No Remote Component found. Make sure the remote URL is correct and contains a Remote Component.`
218
270
  );
219
271
  }
220
- if (hasMultipleRemoteComponents && !remoteName) {
221
- throw (0, import_error.multipleRemoteComponentsError)(serverUrl.href);
222
- }
223
- if (!hasRSC && !nextData && metadata.type === "nextjs") {
224
- throw new import_error.RemoteComponentsError(
225
- `The Remote Component at "${serverUrl.href}" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`
226
- );
227
- }
228
- if (metadata.type === "nextjs" && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
229
- !hasShared && !nextData?.props.__REMOTE_COMPONENT__?.shared) {
230
- throw new import_error.RemoteComponentsError(
231
- `No shared dependencies found for Remote Component at "${serverUrl.href}". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`
232
- );
233
- }
234
- let component;
235
- if (options.rsc) {
236
- const componentRSC = `0:${JSON.stringify(rsc)}
237
- `;
238
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.edge");
239
- component = await createFromReadableStream(
240
- new ReadableStream({
241
- type: "bytes",
242
- start(controller) {
243
- const encoder = new TextEncoder();
244
- controller.enqueue(encoder.encode(componentRSC));
245
- controller.close();
246
- }
247
- }),
248
- {
249
- serverConsumerManifest: {
250
- moduleLoading: {
251
- prefix: serverUrl.origin,
252
- crossOrigin: true
253
- },
254
- moduleMap: {}
255
- }
256
- }
257
- );
258
- }
272
+ const name = remoteName || metadata.name;
273
+ const component = options.rsc ? await buildRscComponent(rsc, serverUrl) : void 0;
259
274
  return {
260
- name: remoteName || metadata.id.replace(/_ssr$/, ""),
275
+ name,
261
276
  serverUrl,
262
277
  metadata,
263
278
  rsc,
@@ -267,7 +282,7 @@ async function fetchRemoteComponent(src, options = {
267
282
  nextData,
268
283
  component,
269
284
  html,
270
- remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared
285
+ remoteShared
271
286
  };
272
287
  }
273
288
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/host/server/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport { visit } from '#internal/host/nextjs/dom-flight';\nimport {\n getSkeletonHtml,\n getSkeletonMessage,\n} from '#internal/host/nextjs/skeleton';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientSrc } from '#internal/host/server/get-client-src';\nimport { getSSRRelativePathBaseUrl } from '#internal/host/server/get-ssr-relative-path-base-url';\nimport type {\n LinkDescriptor,\n ScriptDescriptor,\n} from '#internal/host/shared/asset-descriptors';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport type { RemoteComponentMetadata } from '#internal/runtime/metadata';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport type { FetchRemoteComponentResponse, NextData } from './types';\n\nconst CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n options: {\n name?: string;\n rsc?: boolean;\n /** Whether this is being called from Next.js App Router. Used to enable skeleton fallback during SSG builds. */\n appRouter?: boolean;\n onRequest?: OnRequestHook;\n onResponse?: OnResponseHook;\n } = {\n rsc: false,\n },\n): Promise<FetchRemoteComponentResponse> {\n const ssrRelativePathBaseUrl = getSSRRelativePathBaseUrl();\n const serverUrl = new URL(src, ssrRelativePathBaseUrl);\n\n const tags = [\n '_vc_rc:fetch-remote-component',\n // the max size of a next cache tag is 256 characters\n serverUrl.host.slice(0, 256),\n // use the suffix so this tag is unique if multiple remote\n // components have the same host, but unique pathnames / query params\n (typeof src === 'string' ? src : src.href).slice(-256),\n ];\n if (options.name) {\n tags.push(options.name.slice(-256));\n }\n\n const fetchInit = {\n next: {\n tags,\n },\n };\n\n const res = await fetchWithHooks(serverUrl, fetchInit, {\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n });\n\n // If there is an error in the remote, parse and extract the remote error (except 404 and 401).\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(serverUrl.href, res);\n }\n\n if (res.status === 401) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n 'If you are using Deployment Protection, ensure the automation bypass environment variable secret in the host matches an automation bypass value in the remote. See https://remote-components-docs.vercel.sh/docs/concepts/cors-external-urls#deployment-protection for details.',\n );\n }\n\n if (res.status === 404) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n 'Check if you can open it in the browser.',\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n `Response body is empty. Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n let metadata: RemoteComponentMetadata = {\n bundle: CURRENT_ZONE ?? '__vercel_remote_component',\n route: '/',\n runtime: 'webpack',\n id: '__vercel_remote_component',\n type: 'unknown',\n };\n let remoteShared: Record<string, string> = {};\n const scripts: ScriptDescriptor[] = [];\n const links: LinkDescriptor[] = [];\n const hydrationData: string[] = [];\n let nextData: NextData | undefined;\n let html = '';\n\n const remoteName =\n options.name || (serverUrl.hash ? serverUrl.hash.substring(1) : undefined);\n // convert the parsed HTML fragment into an RSC flight data\n // and extract the metadata, scripts, links and remote component RSC flight data\n let hasRemoteComponent = false;\n let hasRSC = false;\n let hasShared = false;\n let hasMultipleRemoteComponents = false;\n let error: RemoteComponentsError | undefined;\n const rsc = visit(fragment, {\n url: serverUrl,\n name: remoteName,\n onMetadata(_metadata) {\n // Skip multiple component detection for Pages Router (__next) since it only supports one remote component per page\n if (\n hasRemoteComponent &&\n metadata.id !== _metadata.id &&\n _metadata.id !== '__next' &&\n metadata.id !== '__next' &&\n !nextData\n ) {\n hasMultipleRemoteComponents = true;\n }\n metadata = _metadata;\n hasRemoteComponent = true;\n },\n onScript(attrs) {\n const clientSrc = getClientSrc(attrs.src, serverUrl.href);\n if (\n !scripts.find(\n (it) =>\n it.src === clientSrc ||\n (attrs.textContent && it.textContent === attrs.textContent),\n )\n ) {\n scripts.push(\n typeof attrs.textContent === 'string'\n ? {\n src: '',\n textContent: attrs.textContent,\n }\n : {\n src: clientSrc,\n },\n );\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: getClientSrc(attrs.href, serverUrl.href),\n };\n if (\n !links.find(\n (it) => it.href === relativeAttrs.href && it.rel === attrs.rel,\n )\n ) {\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n\n // use the Next.js Pages Router props data to extract remote component metadata\n if (data.props.__REMOTE_COMPONENT__) {\n Object.assign(metadata, data.props.__REMOTE_COMPONENT__);\n // only a singleton remote component is supported per page when using the Next.js Pages Router\n metadata.id = '__next';\n metadata.route = data.page ?? '/';\n }\n },\n onHTML(_html) {\n if (!html.includes(_html)) {\n html += _html;\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRemoteComponent) {\n // For microfrontend builds during run time, the host and remote build\n // may be happening concurrently. In this case, the request will 404.\n // We want to allow the build to continue with a placeholder remote\n // component. Once the build completes, vercel will automatically revalidate\n // ISR and fetch the built remote component.\n const isSSGBuild = process.env.NEXT_PHASE === 'phase-production-build';\n // If the remote component is part of a microfrontend, the src provided\n // will be relative.\n const isSSRRelativePathBase =\n serverUrl.host === new URL(ssrRelativePathBaseUrl).host;\n // Only want this skeleton behaviour in previews to unblock development.\n // For production, the remote component should already be built.\n const isPreview = process.env.VERCEL_TARGET_ENV === 'preview';\n\n if (isSSGBuild && isSSRRelativePathBase && isPreview && options.appRouter) {\n const skeletonMessage = getSkeletonMessage();\n const skeletonHtml = getSkeletonHtml(serverUrl.href);\n\n let skeletonComponent: React.ReactNode | undefined;\n if (options.rsc) {\n const { createElement } = await import('react');\n skeletonComponent = createElement('div', {\n dangerouslySetInnerHTML: { __html: skeletonHtml },\n });\n }\n\n return {\n name: 'remote-component-skeleton',\n serverUrl,\n metadata: {\n ...metadata,\n type: 'remote-component',\n },\n rsc: skeletonMessage,\n scripts: [],\n links: [],\n hydrationData: [],\n nextData: undefined,\n component: skeletonComponent,\n html: skeletonHtml,\n remoteShared: {},\n };\n }\n\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n `No Remote Component found. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hasMultipleRemoteComponents && !remoteName) {\n throw multipleRemoteComponentsError(serverUrl.href);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new RemoteComponentsError(\n `The Remote Component at \"${serverUrl.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new RemoteComponentsError(\n `No shared dependencies found for Remote Component at \"${serverUrl.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n\n let component: React.ReactNode | undefined;\n\n // only create a React component if requested\n if (options.rsc) {\n // RSC flight data for the static HTML in a single RSC line\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n\n // create a React tree from the RSC flight data\n component = await createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: serverUrl.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n }\n\n return {\n name: remoteName || metadata.id.replace(/_ssr$/, ''),\n serverUrl,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmD;AACnD,wBAAsB;AACtB,sBAGO;AACP,8BAA+B;AAC/B,4BAA6B;AAC7B,4CAA0C;AAU1C,mBAIO;AAGP,MAAM,eAAe,QAAQ,IAAI;AAEjC,eAAsB,qBACpB,KACA,UAOI;AAAA,EACF,KAAK;AACP,GACuC;AACvC,QAAM,6BAAyB,iEAA0B;AACzD,QAAM,YAAY,IAAI,IAAI,KAAK,sBAAsB;AAErD,QAAM,OAAO;AAAA,IACX;AAAA;AAAA,IAEA,UAAU,KAAK,MAAM,GAAG,GAAG;AAAA;AAAA;AAAA,KAG1B,OAAO,QAAQ,WAAW,MAAM,IAAI,MAAM,MAAM,IAAI;AAAA,EACvD;AACA,MAAI,QAAQ,MAAM;AAChB,SAAK,KAAK,QAAQ,KAAK,MAAM,IAAI,CAAC;AAAA,EACpC;AAEA,QAAM,YAAY;AAAA,IAChB,MAAM;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,UAAM,wCAAe,WAAW,WAAW;AAAA,IACrD,WAAW,QAAQ;AAAA,IACnB,YAAY,QAAQ;AAAA,EACtB,CAAC;AAGD,MAAI,CAAC,IAAI,MAAM,CAAC,IAAI,MAAM;AACxB,cAAM,gDAAkC,UAAU,MAAM,GAAG;AAAA,EAC7D;AAEA,MAAI,IAAI,WAAW,KAAK;AACtB,cAAM;AAAA,MACJ,UAAU;AAAA,MACV;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,WAAW,KAAK;AACtB,cAA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,OAAO,YAAY,CAAC;AAC/C,qBAAW,MAAM;AAAA,QACnB;AAAA,MACF,CAAC;AAAA,MACD;AAAA,QACE,wBAAwB;AAAA,UACtB,eAAe;AAAA,YACb,QAAQ,UAAU;AAAA,YAClB,aAAa;AAAA,UACf;AAAA,UACA,WAAW,CAAC;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM,cAAc,SAAS,GAAG,QAAQ,SAAS,EAAE;AAAA,IACnD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,UAAU,MAAM,sBAAsB,UAAU;AAAA,EAChE;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/host/server/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport { type RSC, visit } from '#internal/host/nextjs/dom-flight';\nimport {\n getSkeletonHtml,\n getSkeletonMessage,\n} from '#internal/host/nextjs/skeleton';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientSrc } from '#internal/host/server/get-client-src';\nimport { getSSRRelativePathBaseUrl } from '#internal/host/server/get-ssr-relative-path-base-url';\nimport type {\n LinkDescriptor,\n ScriptDescriptor,\n} from '#internal/host/shared/asset-descriptors';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport {\n buildMetadata,\n type RawMetadataAttrs,\n type RemoteComponentMetadata,\n} from '#internal/runtime/metadata';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport type { FetchRemoteComponentResponse, NextData } from './types';\n\n/**\n * Converts RSC flight data into a React element tree using the edge streaming\n * runtime. The manifest tells React how to resolve module references back to\n * the remote origin.\n */\nasync function buildRscComponent(\n rsc: RSC | RSC[] | string | null,\n serverUrl: URL,\n): Promise<React.ReactNode> {\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n return createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: serverUrl.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n}\n\nfunction buildSkeletonResponse(\n serverUrl: URL,\n metadata: RemoteComponentMetadata,\n skeletonComponent: React.ReactNode | undefined,\n): FetchRemoteComponentResponse {\n return {\n name: 'remote-component-skeleton',\n serverUrl,\n metadata: {\n ...metadata,\n type: 'remote-component',\n },\n rsc: getSkeletonMessage(),\n scripts: [],\n links: [],\n hydrationData: [],\n nextData: undefined,\n component: skeletonComponent,\n html: getSkeletonHtml(serverUrl.href),\n remoteShared: {},\n };\n}\n\n/**\n * Walks the parsed HTML fragment and extracts all remote component data:\n * metadata, scripts, links, hydration data, Next.js data, shared deps, and HTML.\n */\nfunction visitFragment(\n fragment: DefaultTreeAdapterMap['documentFragment'],\n serverUrl: URL,\n remoteName: string | undefined,\n) {\n const scriptSrcSet = new Set<string>();\n const scriptTextSet = new Set<string>();\n const scripts: ScriptDescriptor[] = [];\n\n const linkKeySet = new Set<string>();\n const links: LinkDescriptor[] = [];\n\n const hydrationData: string[] = [];\n const htmlChunks = new Set<string>();\n\n let metadata: RemoteComponentMetadata | undefined;\n let nextData: NextData | undefined;\n let remoteShared: Record<string, string> = {};\n let hasRSC = false;\n let hasShared = false;\n let error: RemoteComponentsError | undefined;\n\n const rsc = visit(fragment, {\n url: serverUrl,\n name: remoteName,\n onMetadata(attrs: RawMetadataAttrs) {\n const incoming = buildMetadata(attrs, serverUrl);\n // Skip multiple component detection for Pages Router (__next) since\n // it only supports one remote component per page\n if (\n !remoteName &&\n metadata &&\n metadata.id !== incoming.id &&\n incoming.id !== '__next' &&\n metadata.id !== '__next' &&\n !nextData\n ) {\n throw multipleRemoteComponentsError(serverUrl.href);\n }\n metadata = incoming;\n },\n onScript(attrs) {\n const clientSrc = getClientSrc(attrs.src, serverUrl.href);\n const textContent =\n typeof attrs.textContent === 'string' ? attrs.textContent : undefined;\n\n if (textContent) {\n if (!scriptTextSet.has(textContent)) {\n scriptTextSet.add(textContent);\n scripts.push({ src: '', textContent });\n }\n } else if (!scriptSrcSet.has(clientSrc)) {\n scriptSrcSet.add(clientSrc);\n scripts.push({ src: clientSrc });\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: getClientSrc(attrs.href, serverUrl.href),\n };\n const linkKey = `${relativeAttrs.href}::${attrs.rel}`;\n if (!linkKeySet.has(linkKey)) {\n linkKeySet.add(linkKey);\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n },\n onHTML(chunk) {\n if (!htmlChunks.has(chunk)) {\n htmlChunks.add(chunk);\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n if (metadata) {\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new RemoteComponentsError(\n `The Remote Component at \"${serverUrl.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new RemoteComponentsError(\n `No shared dependencies found for Remote Component at \"${serverUrl.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n }\n\n const resolvedShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared;\n\n return {\n rsc,\n metadata,\n scripts,\n links,\n hydrationData,\n nextData,\n remoteShared: resolvedShared,\n html: Array.from(htmlChunks).join(''),\n };\n}\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n options: {\n name?: string;\n rsc?: boolean;\n /** Whether this is being called from Next.js App Router. Used to enable skeleton fallback during SSG builds. */\n appRouter?: boolean;\n onRequest?: OnRequestHook;\n onResponse?: OnResponseHook;\n } = {},\n): Promise<FetchRemoteComponentResponse> {\n const ssrRelativePathBaseUrl = getSSRRelativePathBaseUrl();\n const serverUrl = new URL(src, ssrRelativePathBaseUrl);\n\n const tags = [\n '_vc_rc:fetch-remote-component',\n // the max size of a next cache tag is 256 characters\n serverUrl.host.slice(0, 256),\n // use the suffix so this tag is unique if multiple remote\n // components have the same host, but unique pathnames / query params\n (typeof src === 'string' ? src : src.href).slice(-256),\n ];\n if (options.name) {\n tags.push(options.name.slice(-256));\n }\n\n const fetchInit = {\n next: {\n tags,\n },\n };\n\n const res = await fetchWithHooks(serverUrl, fetchInit, {\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n });\n\n // If there is an error in the remote, parse and extract the remote error (except 404 and 401).\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(serverUrl.href, res);\n }\n\n if (res.status === 401) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n 'If you are using Deployment Protection, ensure the automation bypass environment variable secret in the host matches an automation bypass value in the remote. See https://remote-components-docs.vercel.sh/docs/concepts/cors-external-urls#deployment-protection for details.',\n );\n }\n\n if (res.status === 404) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n 'Check if you can open it in the browser.',\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n `Response body is empty. Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n const remoteName =\n options.name || (serverUrl.hash ? serverUrl.hash.substring(1) : undefined);\n\n const {\n rsc,\n metadata,\n scripts,\n links,\n hydrationData,\n nextData,\n remoteShared,\n html,\n } = visitFragment(fragment, serverUrl, remoteName);\n\n if (!metadata) {\n // For microfrontend builds during run time, the host and remote build\n // may be happening concurrently. In this case, the request will 404.\n // We want to allow the build to continue with a placeholder remote\n // component. Once the build completes, vercel will automatically revalidate\n // ISR and fetch the built remote component.\n const isSSGBuild = process.env.NEXT_PHASE === 'phase-production-build';\n // If the remote component is part of a microfrontend, the src provided\n // will be relative.\n const isSSRRelativePathBase =\n serverUrl.host === new URL(ssrRelativePathBaseUrl).host;\n // Only want this skeleton behaviour in previews to unblock development.\n // For production, the remote component should already be built.\n const isPreview = process.env.VERCEL_TARGET_ENV === 'preview';\n\n if (isSSGBuild && isSSRRelativePathBase && isPreview && options.appRouter) {\n let skeletonComponent: React.ReactNode | undefined;\n if (options.rsc) {\n const { createElement } = await import('react');\n skeletonComponent = createElement('div', {\n dangerouslySetInnerHTML: {\n __html: getSkeletonHtml(serverUrl.href),\n },\n });\n }\n\n return buildSkeletonResponse(\n serverUrl,\n buildMetadata({}, serverUrl),\n skeletonComponent,\n );\n }\n\n throw failedToFetchRemoteComponentError(\n serverUrl.href,\n res,\n `No Remote Component found. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n const name = remoteName || metadata.name;\n const component = options.rsc\n ? await buildRscComponent(rsc, serverUrl)\n : undefined;\n\n return {\n name,\n serverUrl,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmD;AACnD,wBAAgC;AAChC,sBAGO;AACP,8BAA+B;AAC/B,4BA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