remote-components 0.0.51 → 0.1.2

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 (135) hide show
  1. package/dist/{component-loader-1838f572.d.ts → component-loader-21865da3.d.ts} +142 -16
  2. package/dist/host-config-58cdccea.d.ts +87 -0
  3. package/dist/html/host.cjs +589 -377
  4. package/dist/html/host.cjs.map +1 -1
  5. package/dist/html/host.d.ts +2 -0
  6. package/dist/html/host.js +588 -377
  7. package/dist/html/host.js.map +1 -1
  8. package/dist/html/remote.cjs +65 -57
  9. package/dist/html/remote.cjs.map +1 -1
  10. package/dist/html/remote.js +65 -57
  11. package/dist/html/remote.js.map +1 -1
  12. package/dist/internal/next/host/app-router-client.cjs +21 -10
  13. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  14. package/dist/internal/next/host/app-router-client.d.ts +36 -14
  15. package/dist/internal/next/host/app-router-client.js +21 -10
  16. package/dist/internal/next/host/app-router-client.js.map +1 -1
  17. package/dist/internal/next/remote/render-server.cjs.map +1 -1
  18. package/dist/internal/next/remote/render-server.d.ts +13 -14
  19. package/dist/internal/next/remote/render-server.js.map +1 -1
  20. package/dist/internal/react/context.cjs +43 -0
  21. package/dist/internal/react/context.cjs.map +1 -0
  22. package/dist/internal/react/context.d.ts +20 -0
  23. package/dist/internal/react/context.js +18 -0
  24. package/dist/internal/react/context.js.map +1 -0
  25. package/dist/internal/react/hooks/use-resolve-client-url.cjs +39 -0
  26. package/dist/internal/react/hooks/use-resolve-client-url.cjs.map +1 -0
  27. package/dist/internal/react/hooks/use-resolve-client-url.d.ts +5 -0
  28. package/dist/internal/react/hooks/use-resolve-client-url.js +15 -0
  29. package/dist/internal/react/hooks/use-resolve-client-url.js.map +1 -0
  30. package/dist/internal/shared/client/apply-origin.cjs +10 -5
  31. package/dist/internal/shared/client/apply-origin.cjs.map +1 -1
  32. package/dist/internal/shared/client/apply-origin.d.ts +3 -1
  33. package/dist/internal/shared/client/apply-origin.js +10 -5
  34. package/dist/internal/shared/client/apply-origin.js.map +1 -1
  35. package/dist/internal/shared/client/default-resolve-client-url.cjs +32 -0
  36. package/dist/internal/shared/client/default-resolve-client-url.cjs.map +1 -0
  37. package/dist/internal/shared/client/default-resolve-client-url.d.ts +5 -0
  38. package/dist/internal/shared/client/default-resolve-client-url.js +10 -0
  39. package/dist/internal/shared/client/default-resolve-client-url.js.map +1 -0
  40. package/dist/internal/shared/client/protected-rc-fallback.cjs +11 -2
  41. package/dist/internal/shared/client/protected-rc-fallback.cjs.map +1 -1
  42. package/dist/internal/shared/client/protected-rc-fallback.d.ts +2 -1
  43. package/dist/internal/shared/client/protected-rc-fallback.js +9 -1
  44. package/dist/internal/shared/client/protected-rc-fallback.js.map +1 -1
  45. package/dist/internal/shared/client/proxy-through-host.cjs +65 -0
  46. package/dist/internal/shared/client/proxy-through-host.cjs.map +1 -0
  47. package/dist/internal/shared/client/proxy-through-host.d.ts +62 -0
  48. package/dist/internal/shared/client/proxy-through-host.js +40 -0
  49. package/dist/internal/shared/client/proxy-through-host.js.map +1 -0
  50. package/dist/internal/shared/client/remote-component.cjs +121 -137
  51. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  52. package/dist/internal/shared/client/remote-component.d.ts +7 -5
  53. package/dist/internal/shared/client/remote-component.js +120 -137
  54. package/dist/internal/shared/client/remote-component.js.map +1 -1
  55. package/dist/internal/shared/constants.cjs +3 -0
  56. package/dist/internal/shared/constants.cjs.map +1 -1
  57. package/dist/internal/shared/constants.d.ts +2 -1
  58. package/dist/internal/shared/constants.js +2 -0
  59. package/dist/internal/shared/constants.js.map +1 -1
  60. package/dist/internal/shared/contract/host-state.cjs +38 -0
  61. package/dist/internal/shared/contract/host-state.cjs.map +1 -0
  62. package/dist/internal/shared/contract/host-state.d.ts +53 -0
  63. package/dist/internal/shared/contract/host-state.js +14 -0
  64. package/dist/internal/shared/contract/host-state.js.map +1 -0
  65. package/dist/internal/shared/contract/resolve-name-from-src.cjs +40 -0
  66. package/dist/internal/shared/contract/resolve-name-from-src.cjs.map +1 -0
  67. package/dist/internal/shared/contract/resolve-name-from-src.d.ts +13 -0
  68. package/dist/internal/shared/contract/resolve-name-from-src.js +16 -0
  69. package/dist/internal/shared/contract/resolve-name-from-src.js.map +1 -0
  70. package/dist/internal/shared/error.cjs +70 -0
  71. package/dist/internal/shared/error.cjs.map +1 -1
  72. package/dist/internal/shared/error.d.ts +3 -1
  73. package/dist/internal/shared/error.js +71 -0
  74. package/dist/internal/shared/error.js.map +1 -1
  75. package/dist/internal/shared/ssr/dom-flight.d.ts +1 -1
  76. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  77. package/dist/internal/shared/ssr/fetch-remote-component.d.ts +1 -1
  78. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  79. package/dist/internal/shared/ssr/fetch-with-hooks.cjs +7 -2
  80. package/dist/internal/shared/ssr/fetch-with-hooks.cjs.map +1 -1
  81. package/dist/internal/shared/ssr/fetch-with-hooks.d.ts +1 -1
  82. package/dist/internal/shared/ssr/fetch-with-hooks.js +7 -2
  83. package/dist/internal/shared/ssr/fetch-with-hooks.js.map +1 -1
  84. package/dist/internal/shared/utils/logger.cjs +26 -10
  85. package/dist/internal/shared/utils/logger.cjs.map +1 -1
  86. package/dist/internal/shared/utils/logger.d.ts +6 -1
  87. package/dist/internal/shared/utils/logger.js +24 -9
  88. package/dist/internal/shared/utils/logger.js.map +1 -1
  89. package/dist/next/config.cjs +2 -2
  90. package/dist/next/config.cjs.map +1 -1
  91. package/dist/next/config.js +2 -2
  92. package/dist/next/config.js.map +1 -1
  93. package/dist/next/host/app-router-server.cjs.map +1 -1
  94. package/dist/next/host/app-router-server.d.ts +11 -41
  95. package/dist/next/host/app-router-server.js.map +1 -1
  96. package/dist/next/host/client/index.cjs +467 -298
  97. package/dist/next/host/client/index.cjs.map +1 -1
  98. package/dist/next/host/client/index.d.ts +3 -1
  99. package/dist/next/host/client/index.js +445 -277
  100. package/dist/next/host/client/index.js.map +1 -1
  101. package/dist/next/host/pages-router-client.cjs +15 -2
  102. package/dist/next/host/pages-router-client.cjs.map +1 -1
  103. package/dist/next/host/pages-router-client.d.ts +14 -26
  104. package/dist/next/host/pages-router-client.js +15 -2
  105. package/dist/next/host/pages-router-client.js.map +1 -1
  106. package/dist/next/host/pages-router-server.cjs +2 -0
  107. package/dist/next/host/pages-router-server.cjs.map +1 -1
  108. package/dist/next/host/pages-router-server.d.ts +17 -31
  109. package/dist/next/host/pages-router-server.js +2 -0
  110. package/dist/next/host/pages-router-server.js.map +1 -1
  111. package/dist/next/index.cjs.map +1 -1
  112. package/dist/next/index.d.ts +13 -39
  113. package/dist/next/index.js.map +1 -1
  114. package/dist/next/proxy.cjs +33 -6
  115. package/dist/next/proxy.cjs.map +1 -1
  116. package/dist/next/proxy.js +33 -6
  117. package/dist/next/proxy.js.map +1 -1
  118. package/dist/next/remote/server.d.ts +4 -0
  119. package/dist/proxy-through-host-a676a522.d.ts +52 -0
  120. package/dist/react/index.cjs +486 -298
  121. package/dist/react/index.cjs.map +1 -1
  122. package/dist/react/index.d.ts +27 -40
  123. package/dist/react/index.js +463 -277
  124. package/dist/react/index.js.map +1 -1
  125. package/dist/shared/host/proxy.cjs +32 -6
  126. package/dist/shared/host/proxy.cjs.map +1 -1
  127. package/dist/shared/host/proxy.js +36 -7
  128. package/dist/shared/host/proxy.js.map +1 -1
  129. package/dist/{types-cbe44b51.d.ts → types-2b26a246.d.ts} +23 -6
  130. package/package.json +1 -1
  131. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.cjs +0 -65
  132. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.cjs.map +0 -1
  133. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.d.ts +0 -13
  134. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.js +0 -41
  135. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.js.map +0 -1
@@ -9,11 +9,38 @@ var __export = (target, all) => {
9
9
  __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
11
 
12
+ // src/shared/constants.ts
13
+ var CORS_DOCS_URL;
14
+ var init_constants = __esm({
15
+ "src/shared/constants.ts"() {
16
+ "use strict";
17
+ CORS_DOCS_URL = "https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components";
18
+ }
19
+ });
20
+
21
+ // src/shared/client/protected-rc-fallback.ts
22
+ var init_protected_rc_fallback = __esm({
23
+ "src/shared/client/protected-rc-fallback.ts"() {
24
+ "use strict";
25
+ init_constants();
26
+ }
27
+ });
28
+
29
+ // src/shared/utils/abort.ts
30
+ var init_abort = __esm({
31
+ "src/shared/utils/abort.ts"() {
32
+ "use strict";
33
+ }
34
+ });
35
+
12
36
  // src/shared/error.ts
13
37
  var RemoteComponentsError;
14
38
  var init_error = __esm({
15
39
  "src/shared/error.ts"() {
16
40
  "use strict";
41
+ init_protected_rc_fallback();
42
+ init_constants();
43
+ init_abort();
17
44
  RemoteComponentsError = class extends Error {
18
45
  code = "REMOTE_COMPONENTS_ERROR";
19
46
  constructor(message, options) {
@@ -25,9 +52,6 @@ var init_error = __esm({
25
52
  });
26
53
 
27
54
  // src/shared/utils/logger.ts
28
- function logInfo(location2, message) {
29
- console.info(`[${PREFIX}:${location2}]: ${message}`);
30
- }
31
55
  function logWarn(location2, message) {
32
56
  console.warn(`[${PREFIX}:${location2}]: ${message}`);
33
57
  }
@@ -38,62 +62,50 @@ function logError(location2, message, cause) {
38
62
  })
39
63
  );
40
64
  }
65
+ function warnCrossOriginFetchError(logLocation, url) {
66
+ try {
67
+ const parsed = typeof url === "string" ? new URL(url) : url;
68
+ if (typeof location === "undefined" || parsed.origin === location.origin) {
69
+ return;
70
+ }
71
+ logWarn(
72
+ logLocation,
73
+ `Failed to fetch cross-origin resource "${parsed.href}". If this is a protected deployment, ensure withRemoteComponentsHost middleware is configured in your host and that the remote URL is included in allowedProxyUrls. See: ${CORS_DOCS_URL}`
74
+ );
75
+ } catch {
76
+ }
77
+ }
41
78
  var PREFIX, DEBUG;
42
79
  var init_logger = __esm({
43
80
  "src/shared/utils/logger.ts"() {
44
81
  "use strict";
82
+ init_constants();
45
83
  init_error();
46
84
  PREFIX = "remote-components";
47
85
  DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
48
86
  }
49
87
  });
50
88
 
51
- // src/shared/constants.ts
52
- var RC_PROTECTED_REMOTE_FETCH_PATHNAME;
53
- var init_constants = __esm({
54
- "src/shared/constants.ts"() {
55
- "use strict";
56
- RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
57
- }
58
- });
59
-
60
- // src/shared/client/protected-rc-fallback.ts
61
- function generateProtectedRcFallbackSrc(url) {
62
- return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;
63
- }
64
- var init_protected_rc_fallback = __esm({
65
- "src/shared/client/protected-rc-fallback.ts"() {
66
- "use strict";
67
- init_constants();
68
- }
69
- });
70
-
71
89
  // src/shared/client/static-loader.ts
72
90
  var static_loader_exports = {};
73
91
  __export(static_loader_exports, {
74
92
  loadStaticRemoteComponent: () => loadStaticRemoteComponent
75
93
  });
76
- async function importViaProxy(absoluteSrc) {
77
- const proxyUrl = new URL(
78
- generateProtectedRcFallbackSrc(absoluteSrc),
79
- location.href
80
- ).href;
81
- const response = await fetch(proxyUrl);
94
+ async function importViaCallback(absoluteSrc, resolveClientUrl) {
95
+ const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;
96
+ const fetchUrl = new URL(resolvedUrl, location.href).href;
97
+ const response = await fetch(fetchUrl);
82
98
  if (!response.ok)
83
- throw new Error(`Proxy fetch failed: ${response.status}`);
84
- logInfo(
85
- "StaticLoader",
86
- `Successfully loaded ${absoluteSrc} via protected RC proxy fallback.`
87
- );
99
+ throw new Error(`Proxied fetch failed: ${response.status}`);
88
100
  const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
89
101
  /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
90
102
  (_, keyword, quote, relativePath) => {
91
103
  const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
92
- const absoluteProxyUrl = new URL(
93
- generateProtectedRcFallbackSrc(absoluteImportUrl),
104
+ const resolvedImportUrl = new URL(
105
+ resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,
94
106
  location.href
95
107
  ).href;
96
- return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;
108
+ return `${keyword} ${quote}${resolvedImportUrl}${quote}`;
97
109
  }
98
110
  );
99
111
  const moduleBlobUrl = URL.createObjectURL(
@@ -127,6 +139,20 @@ async function importViaProxy(absoluteSrc) {
127
139
  delete registry[absoluteSrc];
128
140
  return mod;
129
141
  }
142
+ async function importDirectly(absoluteSrc) {
143
+ try {
144
+ return await import(
145
+ /* @vite-ignore */
146
+ /* webpackIgnore: true */
147
+ absoluteSrc
148
+ );
149
+ } catch (importError) {
150
+ if (!absoluteSrc.startsWith("blob:")) {
151
+ warnCrossOriginFetchError("StaticLoader", absoluteSrc);
152
+ }
153
+ throw importError;
154
+ }
155
+ }
130
156
  function resolveScriptSrc(script, url) {
131
157
  const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
132
158
  if (!rawSrc && script.textContent) {
@@ -139,24 +165,7 @@ function resolveScriptSrc(script, url) {
139
165
  }
140
166
  return rawSrc;
141
167
  }
142
- async function importScriptMod(absoluteSrc) {
143
- try {
144
- return await import(
145
- /* @vite-ignore */
146
- /* webpackIgnore: true */
147
- absoluteSrc
148
- );
149
- } catch (importError) {
150
- if (absoluteSrc.startsWith("blob:"))
151
- throw importError;
152
- logWarn(
153
- "StaticLoader",
154
- `Direct import of ${absoluteSrc} failed, attempting via protected RC proxy fallback.`
155
- );
156
- return importViaProxy(absoluteSrc);
157
- }
158
- }
159
- async function loadStaticRemoteComponent(scripts, url) {
168
+ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
160
169
  const self = globalThis;
161
170
  if (self.__remote_script_entrypoint_mount__?.[url.href]) {
162
171
  self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
@@ -169,7 +178,7 @@ async function loadStaticRemoteComponent(scripts, url) {
169
178
  try {
170
179
  const src = resolveScriptSrc(script, url);
171
180
  const absoluteSrc = new URL(src, url).href;
172
- const mod = await importScriptMod(absoluteSrc);
181
+ const mod = resolveClientUrl ? await importViaCallback(absoluteSrc, resolveClientUrl) : await importDirectly(absoluteSrc);
173
182
  if (src.startsWith("blob:")) {
174
183
  URL.revokeObjectURL(src);
175
184
  }
@@ -234,7 +243,6 @@ var init_static_loader = __esm({
234
243
  "src/shared/client/static-loader.ts"() {
235
244
  "use strict";
236
245
  init_logger();
237
- init_protected_rc_fallback();
238
246
  }
239
247
  });
240
248
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shared/error.ts","../../src/shared/utils/logger.ts","../../src/shared/constants.ts","../../src/shared/client/protected-rc-fallback.ts","../../src/shared/client/static-loader.ts","../../src/html/remote/index.tsx"],"sourcesContent":["export class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n","import { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n","export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n","import { logError, logInfo, logWarn } from '../utils/logger';\nimport { generateProtectedRcFallbackSrc } from './protected-rc-fallback';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the same-origin protected RC proxy, rewrites its\n * relative imports to also go through the proxy, then loads it by injecting a\n * wrapper <script type=\"module\"> tag (same pattern as loadScriptWithProtectedRcFallback\n * in script-loader.ts). The module's namespace is captured via a temporary\n * global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth — the proxy runs\n * server-side where credentials are available.\n */\nasync function importViaProxy<T>(absoluteSrc: string): Promise<T> {\n const proxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteSrc),\n location.href,\n ).href;\n const response = await fetch(proxyUrl);\n if (!response.ok) throw new Error(`Proxy fetch failed: ${response.status}`);\n logInfo(\n 'StaticLoader',\n `Successfully loaded ${absoluteSrc} via protected RC proxy fallback.`,\n );\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute proxy URLs so that transitive\n // dependencies (e.g. shared React chunks) also bypass CORS/auth, and so\n // that the paths resolve correctly from within a Blob URL context.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const absoluteProxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteImportUrl),\n location.href,\n ).href;\n return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n // A wrapper module imports everything from the module blob and writes the\n // namespace into a temporary global. We inject it as a <script> tag rather\n // than calling import() again, since import() is equally subject to CORS.\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nasync function importScriptMod(absoluteSrc: string): Promise<ScriptMod> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as ScriptMod;\n } catch (importError) {\n // Direct import failed (likely CORS or auth for cross-origin modules).\n // Blob URLs are same-origin, so they should never fail here — re-throw.\n if (absoluteSrc.startsWith('blob:')) throw importError;\n logWarn(\n 'StaticLoader',\n `Direct import of ${absoluteSrc} failed, attempting via protected RC proxy fallback.`,\n );\n return importViaProxy<ScriptMod>(absoluteSrc);\n }\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod = await importScriptMod(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","import type { MountOrUnmountFunction } from '../../shared/client/types';\nimport { logError } from '../../shared/utils/logger';\n\nif (typeof HTMLElement !== 'undefined') {\n class RemoteComponent extends HTMLElement {\n name?: string;\n root?: ShadowRoot | null = null;\n unmount?: Set<MountOrUnmountFunction> | null = null;\n\n constructor() {\n super();\n\n const html = this.innerHTML;\n this.root = this.attachShadow({\n mode: this.getAttribute('mode') === 'closed' ? 'closed' : 'open',\n });\n this.root.innerHTML = html;\n // Clear light DOM — content was copied into the shadow root above.\n // Without this the original children render twice (once in light DOM,\n // once in shadow DOM).\n this.replaceChildren();\n\n // run the mount functions for any scripts inside the shadow root asynchronously\n (async () => {\n const { loadStaticRemoteComponent } = await import(\n '../../shared/client/static-loader'\n );\n loadStaticRemoteComponent(\n Array.from(this.root?.querySelectorAll('script') ?? []),\n new URL(location.href),\n )\n .then(({ mount, unmount }) => {\n this.unmount = unmount;\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(this.root)),\n );\n })\n .catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n })().catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n }\n\n disconnectedCallback() {\n // run the unmount functions for any scripts inside the shadow root asynchronously\n (async () => {\n if (this.unmount) {\n await Promise.all(\n Array.from(this.unmount).map(async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n }\n }),\n );\n }\n })().catch((e) => {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n });\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAa;AAAb;AAAA;AAAA;AAAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,MAC/C,OAAO;AAAA,MAEP,YAAY,SAAiB,SAA+B;AAC1D,cAAM,SAAS,OAAO;AACtB,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA;AAAA;;;ACsBO,SAAS,QAAQA,WAAuB,SAAiB;AAE9D,UAAQ,KAAK,IAAI,UAAUA,eAAc,SAAS;AACpD;AAEO,SAAS,QAAQA,WAAuB,SAAiB;AAE9D,UAAQ,KAAK,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5C,QAAAA;AAAA,UACE,MAAM,KAAK,KAAK,MAAM,iBAAiB,QAAQ,KAAK,CAAC,CAAC;AAAA,UACtD,IAAI,IAAI,SAAS,IAAI;AAAA,QACvB,EACG,KAAK,CAAC,EAAE,OAAO,QAAQ,MAAM;AAC5B,eAAK,UAAU;AACf,iBAAO,QAAQ;AAAA,YACb,MAAM,KAAK,KAAK,EAAE,IAAI,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AAAA,UACvD;AAAA,QACF,CAAC,EACA,MAAM,CAAC,MAAM;AACZ,mBAAS,cAAc,oCAAoC,CAAC;AAAA,QAC9D,CAAC;AAAA,MACL,GAAG,EAAE,MAAM,CAAC,MAAM;AAChB,iBAAS,cAAc,oCAAoC,CAAC;AAAA,MAC9D,CAAC;AAAA,IACH;AAAA,IAEA,uBAAuB;AAErB,OAAC,YAAY;AACX,YAAI,KAAK,SAAS;AAChB,gBAAM,QAAQ;AAAA,YACZ,MAAM,KAAK,KAAK,OAAO,EAAE,IAAI,OAAO,YAAY;AAC9C,kBAAI;AACF,sBAAM,QAAQ,KAAK,IAAI;AAAA,cACzB,SAAS,GAAP;AACA,yBAAS,cAAc,sCAAsC,CAAC;AAAA,cAChE;AAAA,YACF,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF,GAAG,EAAE,MAAM,CAAC,MAAM;AAChB,iBAAS,cAAc,sCAAsC,CAAC;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;","names":["location","loadStaticRemoteComponent"]}
1
+ {"version":3,"sources":["../../src/shared/constants.ts","../../src/shared/client/protected-rc-fallback.ts","../../src/shared/utils/abort.ts","../../src/shared/error.ts","../../src/shared/utils/logger.ts","../../src/shared/client/static-loader.ts","../../src/html/remote/index.tsx"],"sourcesContent":["export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n\nexport const CORS_DOCS_URL =\n 'https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n\nexport function isProxiedUrl(url: string): boolean {\n try {\n return (\n new URL(url, location.href).pathname ===\n RC_PROTECTED_REMOTE_FETCH_PATHNAME\n );\n } catch {\n return false;\n }\n}\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { isProxiedUrl } from '#internal/shared/client/protected-rc-fallback';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/shared/constants';\nimport { isAbortError } from '#internal/shared/utils/abort';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={proxyClientRequestsThroughHost} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/shared/constants';\nimport { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the withRemoteComponentsHost middleware on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'If this is a protected deployment, ensure withRemoteComponentsHost middleware ' +\n 'is configured in your host and that the remote URL is included in allowedProxyUrls. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { logError, warnCrossOriginFetchError } from '../utils/logger';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the resolveClientUrl callback, rewrites its\n * relative imports to also go through the callback, then loads it by injecting a\n * wrapper <script type=\"module\"> tag. The module's namespace is captured via\n * a temporary global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth. A simple URL rewrite\n * doesn't work for import() because relative imports inside the module would\n * resolve against the rewritten URL instead of the original remote origin.\n */\nasync function importViaCallback<T>(\n absoluteSrc: string,\n resolveClientUrl: InternalResolveClientUrl,\n): Promise<T> {\n const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;\n const fetchUrl = new URL(resolvedUrl, location.href).href;\n const response = await fetch(fetchUrl);\n if (!response.ok) throw new Error(`Proxied fetch failed: ${response.status}`);\n\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute URLs resolved through the callback so\n // that transitive dependencies also bypass CORS/auth.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const resolvedImportUrl = new URL(\n resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,\n location.href,\n ).href;\n return `${keyword} ${quote}${resolvedImportUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nasync function importDirectly<T>(absoluteSrc: string): Promise<T> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as T;\n } catch (importError) {\n if (!absoluteSrc.startsWith('blob:')) {\n warnCrossOriginFetchError('StaticLoader', absoluteSrc);\n }\n throw importError;\n }\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod: ScriptMod = resolveClientUrl\n ? await importViaCallback<ScriptMod>(absoluteSrc, resolveClientUrl)\n : await importDirectly<ScriptMod>(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","import type { MountOrUnmountFunction } from '../../shared/client/types';\nimport { logError } from '../../shared/utils/logger';\n\nif (typeof HTMLElement !== 'undefined') {\n class RemoteComponent extends HTMLElement {\n name?: string;\n root?: ShadowRoot | null = null;\n unmount?: Set<MountOrUnmountFunction> | null = null;\n\n constructor() {\n super();\n\n const html = this.innerHTML;\n this.root = this.attachShadow({\n mode: this.getAttribute('mode') === 'closed' ? 'closed' : 'open',\n });\n this.root.innerHTML = html;\n // Clear light DOM — content was copied into the shadow root above.\n // Without this the original children render twice (once in light DOM,\n // once in shadow DOM).\n this.replaceChildren();\n\n // run the mount functions for any scripts inside the shadow root asynchronously\n (async () => {\n const { loadStaticRemoteComponent } = await import(\n '../../shared/client/static-loader'\n );\n loadStaticRemoteComponent(\n Array.from(this.root?.querySelectorAll('script') ?? []),\n new URL(location.href),\n )\n .then(({ mount, unmount }) => {\n this.unmount = unmount;\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(this.root)),\n );\n })\n .catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n })().catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n }\n\n disconnectedCallback() {\n // run the unmount functions for any scripts inside the shadow root asynchronously\n (async () => {\n if (this.unmount) {\n await Promise.all(\n Array.from(this.unmount).map(async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n }\n }),\n );\n }\n })().catch((e) => {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n });\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n"],"mappings":";;;;;;;;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,YACF,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF,GAAG,EAAE,MAAM,CAAC,MAAM;AAChB,iBAAS,cAAc,sCAAsC,CAAC;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;","names":["location","loadStaticRemoteComponent"]}
@@ -8,11 +8,38 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // src/shared/constants.ts
12
+ var CORS_DOCS_URL;
13
+ var init_constants = __esm({
14
+ "src/shared/constants.ts"() {
15
+ "use strict";
16
+ CORS_DOCS_URL = "https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components";
17
+ }
18
+ });
19
+
20
+ // src/shared/client/protected-rc-fallback.ts
21
+ var init_protected_rc_fallback = __esm({
22
+ "src/shared/client/protected-rc-fallback.ts"() {
23
+ "use strict";
24
+ init_constants();
25
+ }
26
+ });
27
+
28
+ // src/shared/utils/abort.ts
29
+ var init_abort = __esm({
30
+ "src/shared/utils/abort.ts"() {
31
+ "use strict";
32
+ }
33
+ });
34
+
11
35
  // src/shared/error.ts
12
36
  var RemoteComponentsError;
13
37
  var init_error = __esm({
14
38
  "src/shared/error.ts"() {
15
39
  "use strict";
40
+ init_protected_rc_fallback();
41
+ init_constants();
42
+ init_abort();
16
43
  RemoteComponentsError = class extends Error {
17
44
  code = "REMOTE_COMPONENTS_ERROR";
18
45
  constructor(message, options) {
@@ -24,9 +51,6 @@ var init_error = __esm({
24
51
  });
25
52
 
26
53
  // src/shared/utils/logger.ts
27
- function logInfo(location2, message) {
28
- console.info(`[${PREFIX}:${location2}]: ${message}`);
29
- }
30
54
  function logWarn(location2, message) {
31
55
  console.warn(`[${PREFIX}:${location2}]: ${message}`);
32
56
  }
@@ -37,62 +61,50 @@ function logError(location2, message, cause) {
37
61
  })
38
62
  );
39
63
  }
64
+ function warnCrossOriginFetchError(logLocation, url) {
65
+ try {
66
+ const parsed = typeof url === "string" ? new URL(url) : url;
67
+ if (typeof location === "undefined" || parsed.origin === location.origin) {
68
+ return;
69
+ }
70
+ logWarn(
71
+ logLocation,
72
+ `Failed to fetch cross-origin resource "${parsed.href}". If this is a protected deployment, ensure withRemoteComponentsHost middleware is configured in your host and that the remote URL is included in allowedProxyUrls. See: ${CORS_DOCS_URL}`
73
+ );
74
+ } catch {
75
+ }
76
+ }
40
77
  var PREFIX, DEBUG;
41
78
  var init_logger = __esm({
42
79
  "src/shared/utils/logger.ts"() {
43
80
  "use strict";
81
+ init_constants();
44
82
  init_error();
45
83
  PREFIX = "remote-components";
46
84
  DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
47
85
  }
48
86
  });
49
87
 
50
- // src/shared/constants.ts
51
- var RC_PROTECTED_REMOTE_FETCH_PATHNAME;
52
- var init_constants = __esm({
53
- "src/shared/constants.ts"() {
54
- "use strict";
55
- RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
56
- }
57
- });
58
-
59
- // src/shared/client/protected-rc-fallback.ts
60
- function generateProtectedRcFallbackSrc(url) {
61
- return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;
62
- }
63
- var init_protected_rc_fallback = __esm({
64
- "src/shared/client/protected-rc-fallback.ts"() {
65
- "use strict";
66
- init_constants();
67
- }
68
- });
69
-
70
88
  // src/shared/client/static-loader.ts
71
89
  var static_loader_exports = {};
72
90
  __export(static_loader_exports, {
73
91
  loadStaticRemoteComponent: () => loadStaticRemoteComponent
74
92
  });
75
- async function importViaProxy(absoluteSrc) {
76
- const proxyUrl = new URL(
77
- generateProtectedRcFallbackSrc(absoluteSrc),
78
- location.href
79
- ).href;
80
- const response = await fetch(proxyUrl);
93
+ async function importViaCallback(absoluteSrc, resolveClientUrl) {
94
+ const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;
95
+ const fetchUrl = new URL(resolvedUrl, location.href).href;
96
+ const response = await fetch(fetchUrl);
81
97
  if (!response.ok)
82
- throw new Error(`Proxy fetch failed: ${response.status}`);
83
- logInfo(
84
- "StaticLoader",
85
- `Successfully loaded ${absoluteSrc} via protected RC proxy fallback.`
86
- );
98
+ throw new Error(`Proxied fetch failed: ${response.status}`);
87
99
  const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
88
100
  /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
89
101
  (_, keyword, quote, relativePath) => {
90
102
  const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
91
- const absoluteProxyUrl = new URL(
92
- generateProtectedRcFallbackSrc(absoluteImportUrl),
103
+ const resolvedImportUrl = new URL(
104
+ resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,
93
105
  location.href
94
106
  ).href;
95
- return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;
107
+ return `${keyword} ${quote}${resolvedImportUrl}${quote}`;
96
108
  }
97
109
  );
98
110
  const moduleBlobUrl = URL.createObjectURL(
@@ -126,6 +138,20 @@ async function importViaProxy(absoluteSrc) {
126
138
  delete registry[absoluteSrc];
127
139
  return mod;
128
140
  }
141
+ async function importDirectly(absoluteSrc) {
142
+ try {
143
+ return await import(
144
+ /* @vite-ignore */
145
+ /* webpackIgnore: true */
146
+ absoluteSrc
147
+ );
148
+ } catch (importError) {
149
+ if (!absoluteSrc.startsWith("blob:")) {
150
+ warnCrossOriginFetchError("StaticLoader", absoluteSrc);
151
+ }
152
+ throw importError;
153
+ }
154
+ }
129
155
  function resolveScriptSrc(script, url) {
130
156
  const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
131
157
  if (!rawSrc && script.textContent) {
@@ -138,24 +164,7 @@ function resolveScriptSrc(script, url) {
138
164
  }
139
165
  return rawSrc;
140
166
  }
141
- async function importScriptMod(absoluteSrc) {
142
- try {
143
- return await import(
144
- /* @vite-ignore */
145
- /* webpackIgnore: true */
146
- absoluteSrc
147
- );
148
- } catch (importError) {
149
- if (absoluteSrc.startsWith("blob:"))
150
- throw importError;
151
- logWarn(
152
- "StaticLoader",
153
- `Direct import of ${absoluteSrc} failed, attempting via protected RC proxy fallback.`
154
- );
155
- return importViaProxy(absoluteSrc);
156
- }
157
- }
158
- async function loadStaticRemoteComponent(scripts, url) {
167
+ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
159
168
  const self = globalThis;
160
169
  if (self.__remote_script_entrypoint_mount__?.[url.href]) {
161
170
  self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
@@ -168,7 +177,7 @@ async function loadStaticRemoteComponent(scripts, url) {
168
177
  try {
169
178
  const src = resolveScriptSrc(script, url);
170
179
  const absoluteSrc = new URL(src, url).href;
171
- const mod = await importScriptMod(absoluteSrc);
180
+ const mod = resolveClientUrl ? await importViaCallback(absoluteSrc, resolveClientUrl) : await importDirectly(absoluteSrc);
172
181
  if (src.startsWith("blob:")) {
173
182
  URL.revokeObjectURL(src);
174
183
  }
@@ -233,7 +242,6 @@ var init_static_loader = __esm({
233
242
  "src/shared/client/static-loader.ts"() {
234
243
  "use strict";
235
244
  init_logger();
236
- init_protected_rc_fallback();
237
245
  }
238
246
  });
239
247
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shared/error.ts","../../src/shared/utils/logger.ts","../../src/shared/constants.ts","../../src/shared/client/protected-rc-fallback.ts","../../src/shared/client/static-loader.ts","../../src/html/remote/index.tsx"],"sourcesContent":["export class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n","import { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n","export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n","import { logError, logInfo, logWarn } from '../utils/logger';\nimport { generateProtectedRcFallbackSrc } from './protected-rc-fallback';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the same-origin protected RC proxy, rewrites its\n * relative imports to also go through the proxy, then loads it by injecting a\n * wrapper <script type=\"module\"> tag (same pattern as loadScriptWithProtectedRcFallback\n * in script-loader.ts). The module's namespace is captured via a temporary\n * global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth — the proxy runs\n * server-side where credentials are available.\n */\nasync function importViaProxy<T>(absoluteSrc: string): Promise<T> {\n const proxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteSrc),\n location.href,\n ).href;\n const response = await fetch(proxyUrl);\n if (!response.ok) throw new Error(`Proxy fetch failed: ${response.status}`);\n logInfo(\n 'StaticLoader',\n `Successfully loaded ${absoluteSrc} via protected RC proxy fallback.`,\n );\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute proxy URLs so that transitive\n // dependencies (e.g. shared React chunks) also bypass CORS/auth, and so\n // that the paths resolve correctly from within a Blob URL context.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const absoluteProxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteImportUrl),\n location.href,\n ).href;\n return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n // A wrapper module imports everything from the module blob and writes the\n // namespace into a temporary global. We inject it as a <script> tag rather\n // than calling import() again, since import() is equally subject to CORS.\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nasync function importScriptMod(absoluteSrc: string): Promise<ScriptMod> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as ScriptMod;\n } catch (importError) {\n // Direct import failed (likely CORS or auth for cross-origin modules).\n // Blob URLs are same-origin, so they should never fail here — re-throw.\n if (absoluteSrc.startsWith('blob:')) throw importError;\n logWarn(\n 'StaticLoader',\n `Direct import of ${absoluteSrc} failed, attempting via protected RC proxy fallback.`,\n );\n return importViaProxy<ScriptMod>(absoluteSrc);\n }\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod = await importScriptMod(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","import type { MountOrUnmountFunction } from '../../shared/client/types';\nimport { logError } from '../../shared/utils/logger';\n\nif (typeof HTMLElement !== 'undefined') {\n class RemoteComponent extends HTMLElement {\n name?: string;\n root?: ShadowRoot | null = null;\n unmount?: Set<MountOrUnmountFunction> | null = null;\n\n constructor() {\n super();\n\n const html = this.innerHTML;\n this.root = this.attachShadow({\n mode: this.getAttribute('mode') === 'closed' ? 'closed' : 'open',\n });\n this.root.innerHTML = html;\n // Clear light DOM — content was copied into the shadow root above.\n // Without this the original children render twice (once in light DOM,\n // once in shadow DOM).\n this.replaceChildren();\n\n // run the mount functions for any scripts inside the shadow root asynchronously\n (async () => {\n const { loadStaticRemoteComponent } = await import(\n '../../shared/client/static-loader'\n );\n loadStaticRemoteComponent(\n Array.from(this.root?.querySelectorAll('script') ?? []),\n new URL(location.href),\n )\n .then(({ mount, unmount }) => {\n this.unmount = unmount;\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(this.root)),\n );\n })\n .catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n })().catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n }\n\n disconnectedCallback() {\n // run the unmount functions for any scripts inside the shadow root asynchronously\n (async () => {\n if (this.unmount) {\n await Promise.all(\n Array.from(this.unmount).map(async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n }\n }),\n );\n }\n })().catch((e) => {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n });\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAAa;AAAb;AAAA;AAAA;AAAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,MAC/C,OAA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{"version":3,"sources":["../../src/shared/constants.ts","../../src/shared/client/protected-rc-fallback.ts","../../src/shared/utils/abort.ts","../../src/shared/error.ts","../../src/shared/utils/logger.ts","../../src/shared/client/static-loader.ts","../../src/html/remote/index.tsx"],"sourcesContent":["export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n\nexport const CORS_DOCS_URL =\n 'https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n\nexport function isProxiedUrl(url: string): boolean {\n try {\n return (\n new URL(url, location.href).pathname ===\n RC_PROTECTED_REMOTE_FETCH_PATHNAME\n );\n } catch {\n return false;\n }\n}\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { isProxiedUrl } from '#internal/shared/client/protected-rc-fallback';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/shared/constants';\nimport { isAbortError } from '#internal/shared/utils/abort';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={proxyClientRequestsThroughHost} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/shared/constants';\nimport { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the withRemoteComponentsHost middleware on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'If this is a protected deployment, ensure withRemoteComponentsHost middleware ' +\n 'is configured in your host and that the remote URL is included in allowedProxyUrls. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { logError, warnCrossOriginFetchError } from '../utils/logger';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the resolveClientUrl callback, rewrites its\n * relative imports to also go through the callback, then loads it by injecting a\n * wrapper <script type=\"module\"> tag. The module's namespace is captured via\n * a temporary global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth. A simple URL rewrite\n * doesn't work for import() because relative imports inside the module would\n * resolve against the rewritten URL instead of the original remote origin.\n */\nasync function importViaCallback<T>(\n absoluteSrc: string,\n resolveClientUrl: InternalResolveClientUrl,\n): Promise<T> {\n const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;\n const fetchUrl = new URL(resolvedUrl, location.href).href;\n const response = await fetch(fetchUrl);\n if (!response.ok) throw new Error(`Proxied fetch failed: ${response.status}`);\n\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute URLs resolved through the callback so\n // that transitive dependencies also bypass CORS/auth.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const resolvedImportUrl = new URL(\n resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,\n location.href,\n ).href;\n return `${keyword} ${quote}${resolvedImportUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nasync function importDirectly<T>(absoluteSrc: string): Promise<T> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as T;\n } catch (importError) {\n if (!absoluteSrc.startsWith('blob:')) {\n warnCrossOriginFetchError('StaticLoader', absoluteSrc);\n }\n throw importError;\n }\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod: ScriptMod = resolveClientUrl\n ? await importViaCallback<ScriptMod>(absoluteSrc, resolveClientUrl)\n : await importDirectly<ScriptMod>(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","import type { MountOrUnmountFunction } from '../../shared/client/types';\nimport { logError } from '../../shared/utils/logger';\n\nif (typeof HTMLElement !== 'undefined') {\n class RemoteComponent extends HTMLElement {\n name?: string;\n root?: ShadowRoot | null = null;\n unmount?: Set<MountOrUnmountFunction> | null = null;\n\n constructor() {\n super();\n\n const html = this.innerHTML;\n this.root = this.attachShadow({\n mode: this.getAttribute('mode') === 'closed' ? 'closed' : 'open',\n });\n this.root.innerHTML = html;\n // Clear light DOM — content was copied into the shadow root above.\n // Without this the original children render twice (once in light DOM,\n // once in shadow DOM).\n this.replaceChildren();\n\n // run the mount functions for any scripts inside the shadow root asynchronously\n (async () => {\n const { loadStaticRemoteComponent } = await import(\n '../../shared/client/static-loader'\n );\n loadStaticRemoteComponent(\n Array.from(this.root?.querySelectorAll('script') ?? []),\n new URL(location.href),\n )\n .then(({ mount, unmount }) => {\n this.unmount = unmount;\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(this.root)),\n );\n })\n .catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n })().catch((e) => {\n logError('HtmlRemote', 'Error mounting remote component.', e);\n });\n }\n\n disconnectedCallback() {\n // run the unmount functions for any scripts inside the shadow root asynchronously\n (async () => {\n if (this.unmount) {\n await Promise.all(\n Array.from(this.unmount).map(async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n }\n }),\n );\n }\n })().catch((e) => {\n logError('HtmlRemote', 'Error unmounting remote component.', e);\n });\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAEa;AAFb;AAAA;AAAA;AAEO,IAAM,gBACX;AAAA;AAAA;;;ACHF;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAOa;AAPb;AAAA;AAAA;AAAA;AACA;AAIA;AAEO,IAAM,wBAAN,cAAoC,MAAM;AAAA,MAC/C,OAAO;AAAA,MAEP,YAAY,SAAiB,SAA+B;AAC1D,cAAM,SAAS,OAAO;AACtB,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA;AAAA;;;ACqBO,SAAS,QAAQA,WAAuB,SAAiB;AAE9D,UAAQ,KAAK,IAAI,UAAUA,eAAc,SAAS;AACpD;AAEO,SAAS,SACdA,WACA,SACA,OACA;AAEA,UAAQ;AAAA,IACN,IAAI,sBAAsB,IAAI,UAAUA,eAAc,WAAW;AAAA,MAC/D;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAMO,SAAS,0BACd,aACA,KACM;AACN,MAAI;AACF,UAAM,SAAS,OAAO,QAAQ,WAAW,IAAI,IAAI,GAAG,IAAI;AACxD,QAAI,OAAO,aAAa,eAAe,OAAO,WAAW,SAAS,QAAQ;AACxE;AAAA,IACF;AACA;AAAA,MACE;AAAA,MACA,0CAA0C,OAAO,iLAGvC;AAAA,IACZ;AAAA,EACF,QAAE;AAAA,EAEF;AACF;AA5EA,IAmBM,QACA;AApBN;AAAA;AAAA;AAAA;AACA;AAkBA,IAAM,SAAS;AACf,IAAM,QACJ,OAAO,WAAW,eAAe,aAAa,QAAQ,UAAU,MAAM;AAAA;A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