remote-components 0.0.50 → 0.0.51

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 (71) hide show
  1. package/dist/html/host.cjs +330 -166
  2. package/dist/html/host.cjs.map +1 -1
  3. package/dist/html/host.js +330 -166
  4. package/dist/html/host.js.map +1 -1
  5. package/dist/html/remote.cjs +114 -20
  6. package/dist/html/remote.cjs.map +1 -1
  7. package/dist/html/remote.js +114 -20
  8. package/dist/html/remote.js.map +1 -1
  9. package/dist/internal/shared/{ssr → client}/fetch-with-protected-rc-fallback.cjs +9 -6
  10. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.cjs.map +1 -0
  11. package/dist/internal/shared/{ssr → client}/fetch-with-protected-rc-fallback.d.ts +1 -2
  12. package/dist/internal/shared/{ssr → client}/fetch-with-protected-rc-fallback.js +10 -6
  13. package/dist/internal/shared/client/fetch-with-protected-rc-fallback.js.map +1 -0
  14. package/dist/internal/shared/client/protected-rc-fallback.cjs +32 -0
  15. package/dist/internal/shared/client/protected-rc-fallback.cjs.map +1 -0
  16. package/dist/internal/shared/client/protected-rc-fallback.d.ts +6 -0
  17. package/dist/internal/shared/client/protected-rc-fallback.js +8 -0
  18. package/dist/internal/shared/client/protected-rc-fallback.js.map +1 -0
  19. package/dist/internal/shared/client/remote-component.cjs +190 -100
  20. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  21. package/dist/internal/shared/client/remote-component.js +190 -100
  22. package/dist/internal/shared/client/remote-component.js.map +1 -1
  23. package/dist/internal/shared/constants.cjs +29 -0
  24. package/dist/internal/shared/constants.cjs.map +1 -0
  25. package/dist/internal/shared/constants.d.ts +3 -0
  26. package/dist/internal/shared/constants.js +5 -0
  27. package/dist/internal/shared/constants.js.map +1 -0
  28. package/dist/internal/shared/ssr/fetch-remote-component.cjs +1 -2
  29. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  30. package/dist/internal/shared/ssr/fetch-remote-component.js +1 -2
  31. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  32. package/dist/internal/shared/ssr/fetch-with-hooks.cjs +1 -1
  33. package/dist/internal/shared/ssr/fetch-with-hooks.cjs.map +1 -1
  34. package/dist/internal/shared/ssr/fetch-with-hooks.js +1 -1
  35. package/dist/internal/shared/ssr/fetch-with-hooks.js.map +1 -1
  36. package/dist/internal/shared/utils/logger.cjs.map +1 -1
  37. package/dist/internal/shared/utils/logger.d.ts +1 -1
  38. package/dist/internal/shared/utils/logger.js.map +1 -1
  39. package/dist/next/config.cjs.map +1 -1
  40. package/dist/next/config.js.map +1 -1
  41. package/dist/next/host/client/index.cjs +202 -107
  42. package/dist/next/host/client/index.cjs.map +1 -1
  43. package/dist/next/host/client/index.js +202 -107
  44. package/dist/next/host/client/index.js.map +1 -1
  45. package/dist/next/host/pages-router-server.cjs +1 -2
  46. package/dist/next/host/pages-router-server.cjs.map +1 -1
  47. package/dist/next/host/pages-router-server.d.ts +5 -0
  48. package/dist/next/host/pages-router-server.js +1 -2
  49. package/dist/next/host/pages-router-server.js.map +1 -1
  50. package/dist/next/proxy.cjs +36 -24
  51. package/dist/next/proxy.cjs.map +1 -1
  52. package/dist/next/proxy.d.ts +0 -1
  53. package/dist/next/proxy.js +36 -24
  54. package/dist/next/proxy.js.map +1 -1
  55. package/dist/react/index.cjs +202 -107
  56. package/dist/react/index.cjs.map +1 -1
  57. package/dist/react/index.js +202 -107
  58. package/dist/react/index.js.map +1 -1
  59. package/dist/shared/host/proxy.cjs +23 -20
  60. package/dist/shared/host/proxy.cjs.map +1 -1
  61. package/dist/shared/host/proxy.d.ts +0 -3
  62. package/dist/shared/host/proxy.js +23 -19
  63. package/dist/shared/host/proxy.js.map +1 -1
  64. package/dist/shared/remote/proxy.cjs +9 -1
  65. package/dist/shared/remote/proxy.cjs.map +1 -1
  66. package/dist/shared/remote/proxy.d.ts +7 -1
  67. package/dist/shared/remote/proxy.js +8 -1
  68. package/dist/shared/remote/proxy.js.map +1 -1
  69. package/package.json +1 -1
  70. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.cjs.map +0 -1
  71. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.js.map +0 -1
@@ -25,6 +25,12 @@ var init_error = __esm({
25
25
  });
26
26
 
27
27
  // src/shared/utils/logger.ts
28
+ function logInfo(location2, message) {
29
+ console.info(`[${PREFIX}:${location2}]: ${message}`);
30
+ }
31
+ function logWarn(location2, message) {
32
+ console.warn(`[${PREFIX}:${location2}]: ${message}`);
33
+ }
28
34
  function logError(location2, message, cause) {
29
35
  console.error(
30
36
  new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
@@ -42,11 +48,114 @@ var init_logger = __esm({
42
48
  }
43
49
  });
44
50
 
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
+
45
71
  // src/shared/client/static-loader.ts
46
72
  var static_loader_exports = {};
47
73
  __export(static_loader_exports, {
48
74
  loadStaticRemoteComponent: () => loadStaticRemoteComponent
49
75
  });
76
+ async function importViaProxy(absoluteSrc) {
77
+ const proxyUrl = new URL(
78
+ generateProtectedRcFallbackSrc(absoluteSrc),
79
+ location.href
80
+ ).href;
81
+ const response = await fetch(proxyUrl);
82
+ 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
+ );
88
+ const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
89
+ /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
90
+ (_, keyword, quote, relativePath) => {
91
+ const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
92
+ const absoluteProxyUrl = new URL(
93
+ generateProtectedRcFallbackSrc(absoluteImportUrl),
94
+ location.href
95
+ ).href;
96
+ return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;
97
+ }
98
+ );
99
+ const moduleBlobUrl = URL.createObjectURL(
100
+ new Blob([content], { type: "text/javascript" })
101
+ );
102
+ const wrapperContent = [
103
+ `import*as m from${JSON.stringify(moduleBlobUrl)};`,
104
+ `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,
105
+ `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`
106
+ ].join("");
107
+ const wrapperBlobUrl = URL.createObjectURL(
108
+ new Blob([wrapperContent], { type: "text/javascript" })
109
+ );
110
+ const scriptEl = document.createElement("script");
111
+ scriptEl.type = "module";
112
+ scriptEl.src = wrapperBlobUrl;
113
+ try {
114
+ await new Promise((resolve, reject) => {
115
+ scriptEl.onload = () => resolve();
116
+ scriptEl.onerror = () => reject(new Error(`Failed to load module for ${absoluteSrc}`));
117
+ document.head.appendChild(scriptEl);
118
+ });
119
+ } finally {
120
+ scriptEl.remove();
121
+ URL.revokeObjectURL(moduleBlobUrl);
122
+ URL.revokeObjectURL(wrapperBlobUrl);
123
+ }
124
+ const registry = globalThis.__rc_module_registry__;
125
+ const mod = registry?.[absoluteSrc] ?? {};
126
+ if (registry)
127
+ delete registry[absoluteSrc];
128
+ return mod;
129
+ }
130
+ function resolveScriptSrc(script, url) {
131
+ const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
132
+ if (!rawSrc && script.textContent) {
133
+ return URL.createObjectURL(
134
+ new Blob(
135
+ [script.textContent.replace(/import\.meta\.url/g, JSON.stringify(url))],
136
+ { type: "text/javascript" }
137
+ )
138
+ );
139
+ }
140
+ return rawSrc;
141
+ }
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
+ }
50
159
  async function loadStaticRemoteComponent(scripts, url) {
51
160
  const self = globalThis;
52
161
  if (self.__remote_script_entrypoint_mount__?.[url.href]) {
@@ -58,26 +167,9 @@ async function loadStaticRemoteComponent(scripts, url) {
58
167
  const mountUnmountSets = await Promise.all(
59
168
  scripts.map(async (script) => {
60
169
  try {
61
- let src = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
62
- if (!src && script.textContent) {
63
- const blob = new Blob(
64
- [
65
- script.textContent.replace(
66
- /import\.meta\.url/g,
67
- JSON.stringify(url)
68
- )
69
- ],
70
- {
71
- type: "text/javascript"
72
- }
73
- );
74
- src = URL.createObjectURL(blob);
75
- }
76
- const mod = await import(
77
- /* @vite-ignore */
78
- /* webpackIgnore: true */
79
- new URL(src, url).href
80
- );
170
+ const src = resolveScriptSrc(script, url);
171
+ const absoluteSrc = new URL(src, url).href;
172
+ const mod = await importScriptMod(absoluteSrc);
81
173
  if (src.startsWith("blob:")) {
82
174
  URL.revokeObjectURL(src);
83
175
  }
@@ -142,6 +234,7 @@ var init_static_loader = __esm({
142
234
  "src/shared/client/static-loader.ts"() {
143
235
  "use strict";
144
236
  init_logger();
237
+ init_protected_rc_fallback();
145
238
  }
146
239
  });
147
240
 
@@ -159,6 +252,7 @@ if (typeof HTMLElement !== "undefined") {
159
252
  mode: this.getAttribute("mode") === "closed" ? "closed" : "open"
160
253
  });
161
254
  this.root.innerHTML = html;
255
+ this.replaceChildren();
162
256
  (async () => {
163
257
  const { loadStaticRemoteComponent: loadStaticRemoteComponent2 } = await Promise.resolve().then(() => (init_static_loader(), static_loader_exports));
164
258
  loadStaticRemoteComponent2(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shared/error.ts","../../src/shared/utils/logger.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 | '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","import { logError } from '../utils/logger';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\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 let src =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n // if there's no src attribute but there is inline script content, create a blob URL for it\n if (!src && script.textContent) {\n const blob = new Blob(\n [\n script.textContent.replace(\n /import\\.meta\\.url/g,\n JSON.stringify(url),\n ),\n ],\n {\n type: 'text/javascript',\n },\n );\n src = URL.createObjectURL(blob);\n }\n const mod = (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ new URL(src, url).href\n )) as {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n };\n // revoke the object URL if we created one\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\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;;;AC+BO,SAAS,SACdA,WACA,SACA,OACA;AAEA,UAAQ;AAAA,IACN,IAAI,sBAAsB,IAAI,UAAUA,eAAc,WAAW;AAAA,MAC/D;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAjDA,IAiBM,QACA;AAlBN;AAAA;AAAA;AAAA;AAiBA,IAAM,SAAS;AACf,IAAM,QACJ,OAAO,WAAW,eAAe,aAAa,QAAQ,UAAU,MAAM;AAAA;AAAA;;;ACnBxE;AAAA;AAAA;AAAA;AAMA,eAAsB,0BACpB,SACA,KACA;AACA,QAAM,OAAO;AACb,MAAI,KAAK,qCAAqC,IAAI,IAAI,GAAG;AACvD,SAAK,mCAAmC,IAAI,IAAI,IAAI,oBAAI,IAAI;AAAA,EAC9D;AACA,MAAI,KAAK,uCAAuC,IAAI,IAAI,GAAG;AACzD,SAAK,qCAAqC,IAAI,IAAI,IAAI,oB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AAC,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/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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E,CAAC;AAAA,IACH;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;","names":["location","loadStaticRemoteComponent"]}
@@ -24,6 +24,12 @@ var init_error = __esm({
24
24
  });
25
25
 
26
26
  // src/shared/utils/logger.ts
27
+ function logInfo(location2, message) {
28
+ console.info(`[${PREFIX}:${location2}]: ${message}`);
29
+ }
30
+ function logWarn(location2, message) {
31
+ console.warn(`[${PREFIX}:${location2}]: ${message}`);
32
+ }
27
33
  function logError(location2, message, cause) {
28
34
  console.error(
29
35
  new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
@@ -41,11 +47,114 @@ var init_logger = __esm({
41
47
  }
42
48
  });
43
49
 
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
+
44
70
  // src/shared/client/static-loader.ts
45
71
  var static_loader_exports = {};
46
72
  __export(static_loader_exports, {
47
73
  loadStaticRemoteComponent: () => loadStaticRemoteComponent
48
74
  });
75
+ async function importViaProxy(absoluteSrc) {
76
+ const proxyUrl = new URL(
77
+ generateProtectedRcFallbackSrc(absoluteSrc),
78
+ location.href
79
+ ).href;
80
+ const response = await fetch(proxyUrl);
81
+ 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
+ );
87
+ const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
88
+ /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
89
+ (_, keyword, quote, relativePath) => {
90
+ const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
91
+ const absoluteProxyUrl = new URL(
92
+ generateProtectedRcFallbackSrc(absoluteImportUrl),
93
+ location.href
94
+ ).href;
95
+ return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;
96
+ }
97
+ );
98
+ const moduleBlobUrl = URL.createObjectURL(
99
+ new Blob([content], { type: "text/javascript" })
100
+ );
101
+ const wrapperContent = [
102
+ `import*as m from${JSON.stringify(moduleBlobUrl)};`,
103
+ `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,
104
+ `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`
105
+ ].join("");
106
+ const wrapperBlobUrl = URL.createObjectURL(
107
+ new Blob([wrapperContent], { type: "text/javascript" })
108
+ );
109
+ const scriptEl = document.createElement("script");
110
+ scriptEl.type = "module";
111
+ scriptEl.src = wrapperBlobUrl;
112
+ try {
113
+ await new Promise((resolve, reject) => {
114
+ scriptEl.onload = () => resolve();
115
+ scriptEl.onerror = () => reject(new Error(`Failed to load module for ${absoluteSrc}`));
116
+ document.head.appendChild(scriptEl);
117
+ });
118
+ } finally {
119
+ scriptEl.remove();
120
+ URL.revokeObjectURL(moduleBlobUrl);
121
+ URL.revokeObjectURL(wrapperBlobUrl);
122
+ }
123
+ const registry = globalThis.__rc_module_registry__;
124
+ const mod = registry?.[absoluteSrc] ?? {};
125
+ if (registry)
126
+ delete registry[absoluteSrc];
127
+ return mod;
128
+ }
129
+ function resolveScriptSrc(script, url) {
130
+ const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
131
+ if (!rawSrc && script.textContent) {
132
+ return URL.createObjectURL(
133
+ new Blob(
134
+ [script.textContent.replace(/import\.meta\.url/g, JSON.stringify(url))],
135
+ { type: "text/javascript" }
136
+ )
137
+ );
138
+ }
139
+ return rawSrc;
140
+ }
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
+ }
49
158
  async function loadStaticRemoteComponent(scripts, url) {
50
159
  const self = globalThis;
51
160
  if (self.__remote_script_entrypoint_mount__?.[url.href]) {
@@ -57,26 +166,9 @@ async function loadStaticRemoteComponent(scripts, url) {
57
166
  const mountUnmountSets = await Promise.all(
58
167
  scripts.map(async (script) => {
59
168
  try {
60
- let src = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
61
- if (!src && script.textContent) {
62
- const blob = new Blob(
63
- [
64
- script.textContent.replace(
65
- /import\.meta\.url/g,
66
- JSON.stringify(url)
67
- )
68
- ],
69
- {
70
- type: "text/javascript"
71
- }
72
- );
73
- src = URL.createObjectURL(blob);
74
- }
75
- const mod = await import(
76
- /* @vite-ignore */
77
- /* webpackIgnore: true */
78
- new URL(src, url).href
79
- );
169
+ const src = resolveScriptSrc(script, url);
170
+ const absoluteSrc = new URL(src, url).href;
171
+ const mod = await importScriptMod(absoluteSrc);
80
172
  if (src.startsWith("blob:")) {
81
173
  URL.revokeObjectURL(src);
82
174
  }
@@ -141,6 +233,7 @@ var init_static_loader = __esm({
141
233
  "src/shared/client/static-loader.ts"() {
142
234
  "use strict";
143
235
  init_logger();
236
+ init_protected_rc_fallback();
144
237
  }
145
238
  });
146
239
 
@@ -158,6 +251,7 @@ if (typeof HTMLElement !== "undefined") {
158
251
  mode: this.getAttribute("mode") === "closed" ? "closed" : "open"
159
252
  });
160
253
  this.root.innerHTML = html;
254
+ this.replaceChildren();
161
255
  (async () => {
162
256
  const { loadStaticRemoteComponent: loadStaticRemoteComponent2 } = await Promise.resolve().then(() => (init_static_loader(), static_loader_exports));
163
257
  loadStaticRemoteComponent2(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shared/error.ts","../../src/shared/utils/logger.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 | '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","import { logError } from '../utils/logger';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\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 let src =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n // if there's no src attribute but there is inline script content, create a blob URL for it\n if (!src && script.textContent) {\n const blob = new Blob(\n [\n script.textContent.replace(\n /import\\.meta\\.url/g,\n JSON.stringify(url),\n ),\n ],\n {\n type: 'text/javascript',\n },\n );\n src = URL.createObjectURL(blob);\n }\n const mod = (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ new URL(src, url).href\n )) as {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n };\n // revoke the object URL if we created one\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\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;;;AC+BO,SAAS,SACdA,WACA,SACA,OACA;AAEA,UAAQ;AAAA,IACN,IAAI,sBAAsB,IAAI,UAAUA,eAAc,WAAW;AAAA,MAC/D;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAjDA,IAiBM,QACA;AAlBN;AAAA;AAAA;AAAA;AAiBA,IAAM,SAAS;AACf,IAAM,QACJ,OAAO,WAAW,eAAe,aAAa,QAAQ,UAAU,MAAM;AAAA;AAAA;;;ACnBxE;AAAA;AAAA;AAAA;AAMA,eAAsB,0BACpB,SACA,KACA;AACA,QAAM,OAAO;AACb,MAAI,KAAK,qCAAqC,IAAI,IAAI,GAAG;AACvD,SAAK,mCAAmC,IAAI,IAAI,IAAI,oBAAI,IAAI;AAAA,EAC9D;AACA,MAAI,KAAK,uCAAuC,IAAI,IAAI,GAAG;AACzD,SAAK,qCAAqC,IAAI,IAAI,IAAI,oBAAI,IAAI;AAAA,EAChE;AACA,QAAM,mB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AAS,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/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;AA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BAAe,OAAO,oBAAoB,eAAe;AAC3D;","names":["location","loadStaticRemoteComponent"]}
@@ -18,13 +18,12 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var fetch_with_protected_rc_fallback_exports = {};
20
20
  __export(fetch_with_protected_rc_fallback_exports, {
21
- RC_PROTECTED_REMOTE_FETCH_PATHNAME: () => RC_PROTECTED_REMOTE_FETCH_PATHNAME,
22
21
  fetchWithProtectedRcFallback: () => fetchWithProtectedRcFallback
23
22
  });
24
23
  module.exports = __toCommonJS(fetch_with_protected_rc_fallback_exports);
24
+ var import_protected_rc_fallback = require("#internal/shared/client/protected-rc-fallback");
25
25
  var import_abort = require("#internal/shared/utils/abort");
26
26
  var import_logger = require("#internal/shared/utils/logger");
27
- const RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
28
27
  async function fetchWithProtectedRcFallback(url, init) {
29
28
  try {
30
29
  const res = await fetch(url, init);
@@ -33,16 +32,21 @@ async function fetchWithProtectedRcFallback(url, init) {
33
32
  if ((0, import_abort.isAbortError)(error)) {
34
33
  throw error;
35
34
  }
36
- if (typeof document === "object" && typeof document.location === "object" && document.location.origin !== new URL(url).origin) {
37
- (0, import_logger.logInfo)(
35
+ const parsedUrl = new URL(url);
36
+ if (typeof document === "object" && typeof document.location === "object" && document.location.origin !== parsedUrl.origin) {
37
+ (0, import_logger.logWarn)(
38
38
  "FetchRemoteComponent",
39
39
  "Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy."
40
40
  );
41
41
  const proxiedRes = await fetch(
42
- `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${url}`,
42
+ (0, import_protected_rc_fallback.generateProtectedRcFallbackSrc)(parsedUrl.href),
43
43
  init?.signal ? { signal: init.signal } : void 0
44
44
  );
45
45
  if (proxiedRes.status === 200) {
46
+ (0, import_logger.logInfo)(
47
+ "FetchRemoteComponent",
48
+ `Successfully fetched ${parsedUrl.href} with fallback withRemoteComponentsHost proxy`
49
+ );
46
50
  return proxiedRes;
47
51
  } else {
48
52
  (0, import_logger.logError)(
@@ -56,7 +60,6 @@ async function fetchWithProtectedRcFallback(url, init) {
56
60
  }
57
61
  // Annotate the CommonJS export names for ESM import in node:
58
62
  0 && (module.exports = {
59
- RC_PROTECTED_REMOTE_FETCH_PATHNAME,
60
63
  fetchWithProtectedRcFallback
61
64
  });
62
65
  //# sourceMappingURL=fetch-with-protected-rc-fallback.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/shared/client/fetch-with-protected-rc-fallback.ts"],"sourcesContent":["import { generateProtectedRcFallbackSrc } from '#internal/shared/client/protected-rc-fallback';\nimport { isAbortError } from '#internal/shared/utils/abort';\nimport { logError, logInfo, logWarn } from '#internal/shared/utils/logger';\n\n/**\n * When a vercel host preview fetches a vercel protected remote preview on the\n * client, the request will reject as it's not possible to authenticate for the\n * protected deployment in a client side fetch - cookies cannot be shared across\n * domains. To enable previews, this request is proxied via the host where the\n * process.env.VERCEL_AUTOMATION_BYPASS_SECRET will be added.\n *\n * @param url - The URL to fetch\n * @param init - Fetch init options (should include signal for abort support)\n */\nexport async function fetchWithProtectedRcFallback(\n url: URL | string,\n init?: RequestInit,\n): Promise<Response> {\n try {\n const res = await fetch(url, init);\n return res;\n } catch (error) {\n // Re-throw AbortError immediately - don't try fallback for cancelled requests\n if (isAbortError(error)) {\n throw error;\n }\n\n const parsedUrl = new URL(url);\n if (\n typeof document === 'object' &&\n typeof document.location === 'object' &&\n document.location.origin !== parsedUrl.origin\n ) {\n logWarn(\n 'FetchRemoteComponent',\n 'Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy.',\n );\n // Pass signal to proxy fetch as well so it can be cancelled\n const proxiedRes = await fetch(\n generateProtectedRcFallbackSrc(parsedUrl.href),\n init?.signal ? { signal: init.signal } : undefined,\n );\n if (proxiedRes.status === 200) {\n logInfo(\n 'FetchRemoteComponent',\n `Successfully fetched ${parsedUrl.href} with fallback withRemoteComponentsHost proxy`,\n );\n return proxiedRes;\n } else {\n logError(\n 'FetchRemoteComponent',\n `Could not proxy remote: [response status ${\n proxiedRes.status\n }] ${await proxiedRes.text()}`,\n );\n }\n }\n\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mCAA+C;AAC/C,mBAA6B;AAC7B,oBAA2C;AAY3C,eAAsB,6BACpB,KACA,MACmB;AACnB,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,KAAK,IAAI;AACjC,WAAO;AAAA,EACT,SAAS,OAAP;AAEA,YAAI,2BAAa,KAAK,GAAG;AACvB,YAAM;AAAA,IACR;AAEA,UAAM,YAAY,IAAI,IAAI,GAAG;AAC7B,QACE,OAAO,aAAa,YACpB,OAAO,SAAS,aAAa,YAC7B,SAAS,SAAS,WAAW,UAAU,QACvC;AACA;AAAA,QACE;AAAA,QACA;AAAA,MACF;AAEA,YAAM,aAAa,MAAM;AAAA,YACvB,6DAA+B,UAAU,IAAI;AAAA,QAC7C,MAAM,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI;AAAA,MAC3C;AACA,UAAI,WAAW,WAAW,KAAK;AAC7B;AAAA,UACE;AAAA,UACA,wBAAwB,UAAU;AAAA,QACpC;AACA,eAAO;AAAA,MACT,OAAO;AACL;AAAA,UACE;AAAA,UACA,4CACE,WAAW,WACR,MAAM,WAAW,KAAK;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -1,4 +1,3 @@
1
- declare const RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
2
1
  /**
3
2
  * When a vercel host preview fetches a vercel protected remote preview on the
4
3
  * client, the request will reject as it's not possible to authenticate for the
@@ -11,4 +10,4 @@ declare const RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
11
10
  */
12
11
  declare function fetchWithProtectedRcFallback(url: URL | string, init?: RequestInit): Promise<Response>;
13
12
 
14
- export { RC_PROTECTED_REMOTE_FETCH_PATHNAME, fetchWithProtectedRcFallback };
13
+ export { fetchWithProtectedRcFallback };
@@ -1,6 +1,6 @@
1
+ import { generateProtectedRcFallbackSrc } from "#internal/shared/client/protected-rc-fallback";
1
2
  import { isAbortError } from "#internal/shared/utils/abort";
2
- import { logError, logInfo } from "#internal/shared/utils/logger";
3
- const RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
3
+ import { logError, logInfo, logWarn } from "#internal/shared/utils/logger";
4
4
  async function fetchWithProtectedRcFallback(url, init) {
5
5
  try {
6
6
  const res = await fetch(url, init);
@@ -9,16 +9,21 @@ async function fetchWithProtectedRcFallback(url, init) {
9
9
  if (isAbortError(error)) {
10
10
  throw error;
11
11
  }
12
- if (typeof document === "object" && typeof document.location === "object" && document.location.origin !== new URL(url).origin) {
13
- logInfo(
12
+ const parsedUrl = new URL(url);
13
+ if (typeof document === "object" && typeof document.location === "object" && document.location.origin !== parsedUrl.origin) {
14
+ logWarn(
14
15
  "FetchRemoteComponent",
15
16
  "Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy."
16
17
  );
17
18
  const proxiedRes = await fetch(
18
- `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${url}`,
19
+ generateProtectedRcFallbackSrc(parsedUrl.href),
19
20
  init?.signal ? { signal: init.signal } : void 0
20
21
  );
21
22
  if (proxiedRes.status === 200) {
23
+ logInfo(
24
+ "FetchRemoteComponent",
25
+ `Successfully fetched ${parsedUrl.href} with fallback withRemoteComponentsHost proxy`
26
+ );
22
27
  return proxiedRes;
23
28
  } else {
24
29
  logError(
@@ -31,7 +36,6 @@ async function fetchWithProtectedRcFallback(url, init) {
31
36
  }
32
37
  }
33
38
  export {
34
- RC_PROTECTED_REMOTE_FETCH_PATHNAME,
35
39
  fetchWithProtectedRcFallback
36
40
  };
37
41
  //# sourceMappingURL=fetch-with-protected-rc-fallback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/shared/client/fetch-with-protected-rc-fallback.ts"],"sourcesContent":["import { generateProtectedRcFallbackSrc } from '#internal/shared/client/protected-rc-fallback';\nimport { isAbortError } from '#internal/shared/utils/abort';\nimport { logError, logInfo, logWarn } from '#internal/shared/utils/logger';\n\n/**\n * When a vercel host preview fetches a vercel protected remote preview on the\n * client, the request will reject as it's not possible to authenticate for the\n * protected deployment in a client side fetch - cookies cannot be shared across\n * domains. To enable previews, this request is proxied via the host where the\n * process.env.VERCEL_AUTOMATION_BYPASS_SECRET will be added.\n *\n * @param url - The URL to fetch\n * @param init - Fetch init options (should include signal for abort support)\n */\nexport async function fetchWithProtectedRcFallback(\n url: URL | string,\n init?: RequestInit,\n): Promise<Response> {\n try {\n const res = await fetch(url, init);\n return res;\n } catch (error) {\n // Re-throw AbortError immediately - don't try fallback for cancelled requests\n if (isAbortError(error)) {\n throw error;\n }\n\n const parsedUrl = new URL(url);\n if (\n typeof document === 'object' &&\n typeof document.location === 'object' &&\n document.location.origin !== parsedUrl.origin\n ) {\n logWarn(\n 'FetchRemoteComponent',\n 'Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy.',\n );\n // Pass signal to proxy fetch as well so it can be cancelled\n const proxiedRes = await fetch(\n generateProtectedRcFallbackSrc(parsedUrl.href),\n init?.signal ? { signal: init.signal } : undefined,\n );\n if (proxiedRes.status === 200) {\n logInfo(\n 'FetchRemoteComponent',\n `Successfully fetched ${parsedUrl.href} with fallback withRemoteComponentsHost proxy`,\n );\n return proxiedRes;\n } else {\n logError(\n 'FetchRemoteComponent',\n `Could not proxy remote: [response status ${\n proxiedRes.status\n }] ${await proxiedRes.text()}`,\n );\n }\n }\n\n throw error;\n }\n}\n"],"mappings":"AAAA,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,UAAU,SAAS,eAAe;AAY3C,eAAsB,6BACpB,KACA,MACmB;AACnB,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,KAAK,IAAI;AACjC,WAAO;AAAA,EACT,SAAS,OAAP;AAEA,QAAI,aAAa,KAAK,GAAG;AACvB,YAAM;AAAA,IACR;AAEA,UAAM,YAAY,IAAI,IAAI,GAAG;AAC7B,QACE,OAAO,aAAa,YACpB,OAAO,SAAS,aAAa,YAC7B,SAAS,SAAS,WAAW,UAAU,QACvC;AACA;AAAA,QACE;AAAA,QACA;AAAA,MACF;AAEA,YAAM,aAAa,MAAM;AAAA,QACvB,+BAA+B,UAAU,IAAI;AAAA,QAC7C,MAAM,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI;AAAA,MAC3C;AACA,UAAI,WAAW,WAAW,KAAK;AAC7B;AAAA,UACE;AAAA,UACA,wBAAwB,UAAU;AAAA,QACpC;AACA,eAAO;AAAA,MACT,OAAO;AACL;AAAA,UACE;AAAA,UACA,4CACE,WAAW,WACR,MAAM,WAAW,KAAK;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,UAAM;AAAA,EACR;AACF;","names":[]}