remote-components 0.0.28 → 0.0.29

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 (41) hide show
  1. package/dist/html/host.cjs +93 -5
  2. package/dist/html/host.cjs.map +1 -1
  3. package/dist/html/host.js +93 -5
  4. package/dist/html/host.js.map +1 -1
  5. package/dist/internal/next/host/app-router-client.cjs +4 -4
  6. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  7. package/dist/internal/next/host/app-router-client.js +5 -5
  8. package/dist/internal/next/host/app-router-client.js.map +1 -1
  9. package/dist/internal/shared/client/apply-origin.cjs +21 -1
  10. package/dist/internal/shared/client/apply-origin.cjs.map +1 -1
  11. package/dist/internal/shared/client/apply-origin.js +21 -1
  12. package/dist/internal/shared/client/apply-origin.js.map +1 -1
  13. package/dist/internal/shared/client/polyfill.cjs +69 -3
  14. package/dist/internal/shared/client/polyfill.cjs.map +1 -1
  15. package/dist/internal/shared/client/polyfill.js +69 -3
  16. package/dist/internal/shared/client/polyfill.js.map +1 -1
  17. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  18. package/dist/internal/shared/client/remote-component.js.map +1 -1
  19. package/dist/internal/shared/ssr/dom-flight.cjs +20 -0
  20. package/dist/internal/shared/ssr/dom-flight.cjs.map +1 -1
  21. package/dist/internal/shared/ssr/dom-flight.js +20 -0
  22. package/dist/internal/shared/ssr/dom-flight.js.map +1 -1
  23. package/dist/internal/shared/ssr/fetch-headers.cjs +3 -1
  24. package/dist/internal/shared/ssr/fetch-headers.cjs.map +1 -1
  25. package/dist/internal/shared/ssr/fetch-headers.d.ts +1 -6
  26. package/dist/internal/shared/ssr/fetch-headers.js +3 -1
  27. package/dist/internal/shared/ssr/fetch-headers.js.map +1 -1
  28. package/dist/internal/shared/utils.cjs +9 -0
  29. package/dist/internal/shared/utils.cjs.map +1 -1
  30. package/dist/internal/shared/utils.d.ts +2 -1
  31. package/dist/internal/shared/utils.js +8 -0
  32. package/dist/internal/shared/utils.js.map +1 -1
  33. package/dist/next/middleware.cjs +15 -22
  34. package/dist/next/middleware.cjs.map +1 -1
  35. package/dist/next/middleware.js +15 -22
  36. package/dist/next/middleware.js.map +1 -1
  37. package/dist/react/index.cjs +7 -5
  38. package/dist/react/index.cjs.map +1 -1
  39. package/dist/react/index.js +7 -5
  40. package/dist/react/index.js.map +1 -1
  41. package/package.json +1 -1
@@ -18,14 +18,23 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var utils_exports = {};
20
20
  __export(utils_exports, {
21
+ attrToProp: () => attrToProp,
21
22
  escapeString: () => escapeString
22
23
  });
23
24
  module.exports = __toCommonJS(utils_exports);
24
25
  function escapeString(str) {
25
26
  return str.replace(/[^a-z0-9]/g, "_");
26
27
  }
28
+ const attrToProp = {
29
+ fetchpriority: "fetchPriority",
30
+ crossorigin: "crossOrigin",
31
+ imagesrcset: "imageSrcSet",
32
+ imagesizes: "imageSizes",
33
+ srcset: "srcSet"
34
+ };
27
35
  // Annotate the CommonJS export names for ESM import in node:
28
36
  0 && (module.exports = {
37
+ attrToProp,
29
38
  escapeString
30
39
  });
31
40
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/shared/utils/index.ts"],"sourcesContent":["export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;","names":[]}
1
+ {"version":3,"sources":["../../../src/shared/utils/index.ts"],"sourcesContent":["export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;AAEO,MAAM,aAAa;AAAA,EACxB,eAAe;AAAA,EACf,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,QAAQ;AACV;","names":[]}
@@ -1,3 +1,4 @@
1
1
  declare function escapeString(str: string): string;
2
+ declare const attrToProp: Record<string, string>;
2
3
 
3
- export { escapeString };
4
+ export { attrToProp, escapeString };
@@ -1,7 +1,15 @@
1
1
  function escapeString(str) {
2
2
  return str.replace(/[^a-z0-9]/g, "_");
3
3
  }
4
+ const attrToProp = {
5
+ fetchpriority: "fetchPriority",
6
+ crossorigin: "crossOrigin",
7
+ imagesrcset: "imageSrcSet",
8
+ imagesizes: "imageSizes",
9
+ srcset: "srcSet"
10
+ };
4
11
  export {
12
+ attrToProp,
5
13
  escapeString
6
14
  };
7
15
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/shared/utils/index.ts"],"sourcesContent":["export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n"],"mappings":"AAAO,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;","names":[]}
1
+ {"version":3,"sources":["../../../src/shared/utils/index.ts"],"sourcesContent":["export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n"],"mappings":"AAAO,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;AAEO,MAAM,aAAa;AAAA,EACxB,eAAe;AAAA,EACf,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,QAAQ;AACV;","names":[]}
@@ -25,41 +25,34 @@ __export(middleware_exports, {
25
25
  });
26
26
  module.exports = __toCommonJS(middleware_exports);
27
27
  var import_server = require("next/server");
28
- function corsFromOptions(options) {
29
- const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((origin) => origin.trim());
30
- const CORS_HEADERS = {
28
+ function corsHeadersFromOptions(options, headers) {
29
+ const origin = headers?.get("origin") ?? (headers?.has("referer") ? new URL(headers.get("referer") ?? "*").origin : "*");
30
+ const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((allowedOrigin) => allowedOrigin.trim());
31
+ const isAllowed = ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin);
32
+ const allowedHeaders = process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || headers?.get("access-control-request-headers");
33
+ const CORS_HEADERS = isAllowed ? {
34
+ "Access-Control-Allow-Origin": origin,
31
35
  "Access-Control-Allow-Methods": process.env.REMOTE_COMPONENTS_ALLOW_METHODS || (Array.isArray(options?.method) ? options.method.map((m) => m.trim()).join(",") : options?.method) || "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
32
- "Access-Control-Allow-Headers": process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization",
36
+ ...allowedHeaders ? { "Access-Control-Allow-Headers": allowedHeaders } : {},
33
37
  ...process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials ? {
34
38
  "Access-Control-Allow-Credentials": process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || "true"
35
39
  } : {},
36
- "Access-Control-Max-Age": options?.maxAge || "600"
37
- };
38
- return { ALLOWED_ORIGINS, CORS_HEADERS };
40
+ "Access-Control-Max-Age": options?.maxAge || "600",
41
+ Vary: "Origin"
42
+ } : {};
43
+ return CORS_HEADERS;
39
44
  }
40
45
  function withRemoteComponents(middleware, options) {
41
46
  return async (request) => {
42
- const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);
43
- const origin = request.headers.get("origin") ?? (request.headers.has("referer") ? new URL(request.headers.get("referer") ?? "*").origin : "*");
44
- const isAllowed = ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin);
47
+ const corsHeaders = corsHeadersFromOptions(options?.cors, request.headers);
45
48
  if (request.method === "OPTIONS") {
46
49
  return new Response(null, {
47
50
  status: 200,
48
- headers: isAllowed ? {
49
- "Access-Control-Allow-Origin": origin,
50
- Vary: "Origin",
51
- ...CORS_HEADERS
52
- } : {}
51
+ headers: corsHeaders
53
52
  });
54
53
  }
55
54
  const response = typeof middleware === "function" ? await middleware(request) : import_server.NextResponse.next();
56
- if (isAllowed) {
57
- response.headers.set("Access-Control-Allow-Origin", origin);
58
- response.headers.set("Vary", "Origin");
59
- }
60
- Object.entries(CORS_HEADERS).forEach(
61
- ([k, v]) => response.headers.set(k, v)
62
- );
55
+ Object.entries(corsHeaders).forEach(([k, v]) => response.headers.set(k, v));
63
56
  return response;
64
57
  };
65
58
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n maxAge?: string;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers':\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization',\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n 'Access-Control-Max-Age': options?.maxAge || '600',\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin =\n request.headers.get('origin') ??\n (request.headers.has('referer')\n ? new URL(request.headers.get('referer') ?? '*').origin\n : '*');\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n Vary: 'Origin',\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n response.headers.set('Vary', 'Origin');\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAY/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,WAAW,OAAO,KAAK,CAAC;AAEhC,QAAM,eAAe;AAAA,IACnB,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb;AAAA,IACF,GAAI,QAAQ,IAAI,uCAAuC,SAAS,cAC5D;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,IACL,0BAA0B,SAAS,UAAU;AAAA,EAC/C;AAEA,SAAO,EAAE,iBAAiB,aAAa;AACzC;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,EAAE,iBAAiB,aAAa,IAAI,gBAAgB,SAAS,IAAI;AAEvE,UAAM,SACJ,QAAQ,QAAQ,IAAI,QAAQ,MAC3B,QAAQ,QAAQ,IAAI,SAAS,IAC1B,IAAI,IAAI,QAAQ,QAAQ,IAAI,SAAS,KAAK,GAAG,EAAE,SAC/C;AACN,UAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAGlE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS,YACL;AAAA,UACE,+BAA+B;AAAA,UAC/B,MAAM;AAAA,UACN,GAAG;AAAA,QACL,IACA,CAAC;AAAA,MACP,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,2BAAa,KAAK;AAExB,QAAI,WAAW;AACb,eAAS,QAAQ,IAAI,+BAA+B,MAAM;AAC1D,eAAS,QAAQ,IAAI,QAAQ,QAAQ;AAAA,IACvC;AAEA,WAAO,QAAQ,YAAY,EAAE;AAAA,MAAQ,CAAC,CAAC,GAAG,CAAC,MACzC,SAAS,QAAQ,IAAI,GAAG,CAAC;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
1
+ {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n maxAge?: string;\n };\n}\n\nfunction corsHeadersFromOptions(\n options?: RemoteComponentMiddlewareOptions['cors'],\n headers?: Headers,\n) {\n const origin =\n headers?.get('origin') ??\n (headers?.has('referer')\n ? new URL(headers.get('referer') ?? '*').origin\n : '*');\n\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((allowedOrigin) => allowedOrigin.trim());\n\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n const allowedHeaders =\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n headers?.get('access-control-request-headers');\n\n const CORS_HEADERS = (\n isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n ...(allowedHeaders\n ? { 'Access-Control-Allow-Headers': allowedHeaders }\n : {}),\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS ||\n options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n 'Access-Control-Max-Age': options?.maxAge || '600',\n Vary: 'Origin',\n }\n : {}\n ) as Record<string, string>;\n\n return CORS_HEADERS;\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const corsHeaders = corsHeadersFromOptions(options?.cors, request.headers);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: corsHeaders,\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n Object.entries(corsHeaders).forEach(([k, v]) => response.headers.set(k, v));\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAY/C,SAAS,uBACP,SACA,SACA;AACA,QAAM,SACJ,SAAS,IAAI,QAAQ,MACpB,SAAS,IAAI,SAAS,IACnB,IAAI,IAAI,QAAQ,IAAI,SAAS,KAAK,GAAG,EAAE,SACvC;AAEN,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,kBAAkB,cAAc,KAAK,CAAC;AAE9C,QAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAElE,QAAM,iBACJ,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb,SAAS,IAAI,gCAAgC;AAE/C,QAAM,eACJ,YACI;AAAA,IACE,+BAA+B;AAAA,IAC/B,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,GAAI,iBACA,EAAE,gCAAgC,eAAe,IACjD,CAAC;AAAA,IACL,GAAI,QAAQ,IAAI,uCAChB,SAAS,cACL;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,IACL,0BAA0B,SAAS,UAAU;AAAA,IAC7C,MAAM;AAAA,EACR,IACA,CAAC;AAGP,SAAO;AACT;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,cAAc,uBAAuB,SAAS,MAAM,QAAQ,OAAO;AAGzE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,2BAAa,KAAK;AAExB,WAAO,QAAQ,WAAW,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,SAAS,QAAQ,IAAI,GAAG,CAAC,CAAC;AAE1E,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
@@ -1,40 +1,33 @@
1
1
  // src/next/middleware/index.ts
2
2
  import { NextResponse } from "next/server";
3
- function corsFromOptions(options) {
4
- const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((origin) => origin.trim());
5
- const CORS_HEADERS = {
3
+ function corsHeadersFromOptions(options, headers) {
4
+ const origin = headers?.get("origin") ?? (headers?.has("referer") ? new URL(headers.get("referer") ?? "*").origin : "*");
5
+ const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((allowedOrigin) => allowedOrigin.trim());
6
+ const isAllowed = ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin);
7
+ const allowedHeaders = process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || headers?.get("access-control-request-headers");
8
+ const CORS_HEADERS = isAllowed ? {
9
+ "Access-Control-Allow-Origin": origin,
6
10
  "Access-Control-Allow-Methods": process.env.REMOTE_COMPONENTS_ALLOW_METHODS || (Array.isArray(options?.method) ? options.method.map((m) => m.trim()).join(",") : options?.method) || "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
7
- "Access-Control-Allow-Headers": process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization",
11
+ ...allowedHeaders ? { "Access-Control-Allow-Headers": allowedHeaders } : {},
8
12
  ...process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials ? {
9
13
  "Access-Control-Allow-Credentials": process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || "true"
10
14
  } : {},
11
- "Access-Control-Max-Age": options?.maxAge || "600"
12
- };
13
- return { ALLOWED_ORIGINS, CORS_HEADERS };
15
+ "Access-Control-Max-Age": options?.maxAge || "600",
16
+ Vary: "Origin"
17
+ } : {};
18
+ return CORS_HEADERS;
14
19
  }
15
20
  function withRemoteComponents(middleware, options) {
16
21
  return async (request) => {
17
- const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);
18
- const origin = request.headers.get("origin") ?? (request.headers.has("referer") ? new URL(request.headers.get("referer") ?? "*").origin : "*");
19
- const isAllowed = ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin);
22
+ const corsHeaders = corsHeadersFromOptions(options?.cors, request.headers);
20
23
  if (request.method === "OPTIONS") {
21
24
  return new Response(null, {
22
25
  status: 200,
23
- headers: isAllowed ? {
24
- "Access-Control-Allow-Origin": origin,
25
- Vary: "Origin",
26
- ...CORS_HEADERS
27
- } : {}
26
+ headers: corsHeaders
28
27
  });
29
28
  }
30
29
  const response = typeof middleware === "function" ? await middleware(request) : NextResponse.next();
31
- if (isAllowed) {
32
- response.headers.set("Access-Control-Allow-Origin", origin);
33
- response.headers.set("Vary", "Origin");
34
- }
35
- Object.entries(CORS_HEADERS).forEach(
36
- ([k, v]) => response.headers.set(k, v)
37
- );
30
+ Object.entries(corsHeaders).forEach(([k, v]) => response.headers.set(k, v));
38
31
  return response;
39
32
  };
40
33
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n maxAge?: string;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers':\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization',\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n 'Access-Control-Max-Age': options?.maxAge || '600',\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin =\n request.headers.get('origin') ??\n (request.headers.has('referer')\n ? new URL(request.headers.get('referer') ?? '*').origin\n : '*');\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n Vary: 'Origin',\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n response.headers.set('Vary', 'Origin');\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";AAAA,SAA2B,oBAAoB;AAY/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,WAAW,OAAO,KAAK,CAAC;AAEhC,QAAM,eAAe;AAAA,IACnB,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAA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Response } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n maxAge?: string;\n };\n}\n\nfunction corsHeadersFromOptions(\n options?: RemoteComponentMiddlewareOptions['cors'],\n headers?: Headers,\n) {\n const origin =\n headers?.get('origin') ??\n (headers?.has('referer')\n ? new URL(headers.get('referer') ?? '*').origin\n : '*');\n\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((allowedOrigin) => allowedOrigin.trim());\n\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n const allowedHeaders =\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n headers?.get('access-control-request-headers');\n\n const CORS_HEADERS = (\n isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n ...(allowedHeaders\n ? { 'Access-Control-Allow-Headers': allowedHeaders }\n : {}),\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS ||\n options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n 'Access-Control-Max-Age': options?.maxAge || '600',\n Vary: 'Origin',\n }\n : {}\n ) as Record<string, string>;\n\n return CORS_HEADERS;\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const corsHeaders = corsHeadersFromOptions(options?.cors, request.headers);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: corsHeaders,\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n Object.entries(corsHeaders).forEach(([k, v]) => response.headers.set(k, v));\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";AAAA,SAA2B,oBAAoB;AAY/C,SAAS,uBACP,SACA,SACA;AACA,QAAM,SACJ,SAAS,IAAI,QAAQ,MACpB,SAAS,IAAI,SAAS,IACnB,IAAI,IAAI,QAAQ,IAAI,SAAS,KAAK,GAAG,EAAE,SACvC;AAEN,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,kBAAkB,cAAc,KAAK,CAAC;AAE9C,QAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAElE,QAAM,iBACJ,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb,SAAS,IAAI,gCAAgC;AAE/C,QAAM,eACJ,YACI;AAAA,IACE,+BAA+B;AAAA,IAC/B,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,GAAI,iBACA,EAAE,gCAAgC,eAAe,IACjD,CAAC;AAAA,IACL,GAAI,QAAQ,IAAI,uCAChB,SAAS,cACL;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,IACL,0BAA0B,SAAS,UAAU;AAAA,IAC7C,MAAM;AAAA,EACR,IACA,CAAC;AAGP,SAAO;AACT;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,cAAc,uBAAuB,SAAS,MAAM,QAAQ,OAAO;AAGzE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,aAAa,KAAK;AAExB,WAAO,QAAQ,WAAW,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,SAAS,QAAQ,IAAI,GAAG,CAAC,CAAC;AAE1E,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
@@ -49,10 +49,6 @@ function getRemoteComponentHtml(html) {
49
49
  }
50
50
  return "";
51
51
  }
52
- const attrToProp = {
53
- fetchpriority: "fetchPriority",
54
- crossorigin: "crossOrigin"
55
- };
56
52
  function RemoteComponent({
57
53
  src,
58
54
  isolate,
@@ -110,6 +106,7 @@ function RemoteComponent({
110
106
  })() : []
111
107
  );
112
108
  const prevSrcRef = (0, import_react2.useRef)(null);
109
+ const componentHydrationHtml = (0, import_react2.useRef)(null);
113
110
  (0, import_react2.useLayoutEffect)(() => {
114
111
  if (childrenRef.current.length > 0 && remoteComponent) {
115
112
  childrenRef.current.forEach((el) => {
@@ -233,7 +230,7 @@ function RemoteComponent({
233
230
  href: new URL(link.getAttribute("href") ?? link.href, url).href,
234
231
  ...link.getAttributeNames().reduce((acc, key) => {
235
232
  if (key !== "href") {
236
- acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
233
+ acc[import_utils.attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
237
234
  }
238
235
  return acc;
239
236
  }, {})
@@ -312,6 +309,7 @@ function RemoteComponent({
312
309
  url: url.href,
313
310
  data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
314
311
  };
312
+ componentHydrationHtml.current = Array.from(doc.querySelectorAll("link,style")).map((link) => link.outerHTML).join("") + component.innerHTML;
315
313
  const userShared = await shared;
316
314
  const result = await (0, import_remote_component.loadRemoteComponent)({
317
315
  url: new URL(url, location.origin),
@@ -399,6 +397,10 @@ function RemoteComponent({
399
397
  linksToRender,
400
398
  remoteComponent ?? children
401
399
  ] });
400
+ if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {
401
+ shadowRoot.innerHTML = componentHydrationHtml.current;
402
+ componentHydrationHtml.current = null;
403
+ }
402
404
  if (isolate !== false) {
403
405
  const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");
404
406
  if (shadowRemoteComponentHtml) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString } from '#internal/shared/utils';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The shadow DOM mode to use when isolating the remote component. */\n mode?: 'open' | 'closed';\n /** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */\n reset?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** Additional headers to use when fetching the remote component. */\n additionalHeaders?: Headers | Record<string, string>;\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n // parse the HTML string to extract the relevant parts\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // remote component content\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n\nconst attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n} as Record<string, string>;\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n additionalHeaders,\n children,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const prevSrcRef = useRef<string | URL | null>(null);\n\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // create a shadow root if it doesn't exist\n // this is a fallback for browsers that don't support declarative shadow DOM\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [name, isolate, shadowRoot, remoteComponent, mode, src, data]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (index > 0) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n const url = useMemo(() => {\n if (typeof src !== 'string')\n return new URL(\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n try {\n return typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src);\n } catch {\n return new URL(src, 'http://localhost');\n }\n }, [src]);\n\n useEffect(() => {\n let mounted = true;\n\n if (src && src !== prevSrcRef.current) {\n prevSrcRef.current = src;\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n method: 'GET',\n headers: remoteFetchHeaders(additionalHeaders),\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack';\n shared?: Record<string, string>;\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(\n `#${remoteName}_shared[data-remote-components-shared]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n\n if (!component || !(rsc || nextData)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url);\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n )\n .filter((link) => {\n return !component.contains(link);\n })\n .map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(url.href)}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n url: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n const userShared = await shared;\n const result = await loadRemoteComponent({\n url: new URL(url, location.origin),\n name: remoteName,\n rscName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8mBI;AAcE;AA5nBN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAEP,sBAAgC;AAChC,0BAAmC;AACnC,mBAA6B;AAC7B,2BAAmC;AAwCnC,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAG5C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AAA,gBACF,IACE;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,sBACX;AAAA,cACE,4EACE;AAAA,4DAAC,cAAS,IAAI,GAAG,cAAc;AAAA,gBAC9B;AAAA,gBACA;AAAA,gBACA;AAAA,gBACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,iBACpD;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AACA,UAAQ,UAAU;AAGlB,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["import_react","url"]}
1
+ {"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString, attrToProp } from '#internal/shared/utils';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The shadow DOM mode to use when isolating the remote component. */\n mode?: 'open' | 'closed';\n /** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */\n reset?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** Additional headers to use when fetching the remote component. */\n additionalHeaders?: Headers | Record<string, string>;\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n // parse the HTML string to extract the relevant parts\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // remote component content\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n additionalHeaders,\n children,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const prevSrcRef = useRef<string | URL | null>(null);\n const componentHydrationHtml = useRef<string | null>(null);\n\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // create a shadow root if it doesn't exist\n // this is a fallback for browsers that don't support declarative shadow DOM\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [name, isolate, shadowRoot, remoteComponent, mode, src, data]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (index > 0) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n const url = useMemo(() => {\n if (typeof src !== 'string')\n return new URL(\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n try {\n return typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src);\n } catch {\n return new URL(src, 'http://localhost');\n }\n }, [src]);\n\n useEffect(() => {\n let mounted = true;\n\n if (src && src !== prevSrcRef.current) {\n prevSrcRef.current = src;\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n method: 'GET',\n headers: remoteFetchHeaders(additionalHeaders),\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack';\n shared?: Record<string, string>;\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(\n `#${remoteName}_shared[data-remote-components-shared]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n\n if (!component || !(rsc || nextData)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url);\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n )\n .filter((link) => {\n return !component.contains(link);\n })\n .map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(url.href)}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n url: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current =\n Array.from(doc.querySelectorAll('link,style'))\n .map((link) => link.outerHTML)\n .join('') + component.innerHTML;\n\n const userShared = await shared;\n const result = await loadRemoteComponent({\n url: new URL(url, location.origin),\n name: remoteName,\n rscName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+mBI;AAcE;AA7nBN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAEP,sBAAgC;AAChC,0BAAmC;AACnC,mBAAyC;AACzC,2BAAmC;AAwCnC,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAG5C,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,OAAO,gBAAgB,MAAM,WAAW;AAGrD,QAAM,8BAA8B,KAAK;AAAA,IACvC;AAAA,EACF;AACA,MAAI,6BAA6B;AAC/B,WAAO,4BAA4B;AAAA,EACrC;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AI;AAAA;AAAA;AAAA;AAAA,oBAIvL;AAAA;AAAA,gBACF,IACE;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,sBACX;AAAA,cACE,4EACE;AAAA,4DAAC,cAAS,IAAI,GAAG,cAAc;AAAA,gBAC9B;AAAA,gBACA;AAAA,gBACA;AAAA,gBACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,iBACpD;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AACA,UAAQ,UAAU;AAGlB,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["import_react","url"]}
@@ -18,7 +18,7 @@ import {
18
18
  } from "#internal/shared/client/remote-component";
19
19
  import { sharedPolyfills } from "#internal/shared/client/polyfill";
20
20
  import { applyOriginToNodes } from "#internal/shared/client/apply-origin";
21
- import { escapeString } from "#internal/shared/utils";
21
+ import { escapeString, attrToProp } from "#internal/shared/utils";
22
22
  import { remoteFetchHeaders } from "#internal/shared/ssr/fetch-headers";
23
23
  function getRemoteComponentHtml(html) {
24
24
  if (typeof document === "undefined")
@@ -39,10 +39,6 @@ function getRemoteComponentHtml(html) {
39
39
  }
40
40
  return "";
41
41
  }
42
- const attrToProp = {
43
- fetchpriority: "fetchPriority",
44
- crossorigin: "crossOrigin"
45
- };
46
42
  function RemoteComponent({
47
43
  src,
48
44
  isolate,
@@ -100,6 +96,7 @@ function RemoteComponent({
100
96
  })() : []
101
97
  );
102
98
  const prevSrcRef = useRef(null);
99
+ const componentHydrationHtml = useRef(null);
103
100
  useLayoutEffect(() => {
104
101
  if (childrenRef.current.length > 0 && remoteComponent) {
105
102
  childrenRef.current.forEach((el) => {
@@ -302,6 +299,7 @@ function RemoteComponent({
302
299
  url: url.href,
303
300
  data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
304
301
  };
302
+ componentHydrationHtml.current = Array.from(doc.querySelectorAll("link,style")).map((link) => link.outerHTML).join("") + component.innerHTML;
305
303
  const userShared = await shared;
306
304
  const result = await loadRemoteComponent({
307
305
  url: new URL(url, location.origin),
@@ -389,6 +387,10 @@ function RemoteComponent({
389
387
  linksToRender,
390
388
  remoteComponent ?? children
391
389
  ] });
390
+ if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {
391
+ shadowRoot.innerHTML = componentHydrationHtml.current;
392
+ componentHydrationHtml.current = null;
393
+ }
392
394
  if (isolate !== false) {
393
395
  const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");
394
396
  if (shadowRemoteComponentHtml) {