remote-components 0.3.0 → 0.3.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 (105) hide show
  1. package/dist/config/nextjs.cjs.map +1 -1
  2. package/dist/config/nextjs.js.map +1 -1
  3. package/dist/host/html.cjs +467 -395
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +467 -395
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +507 -447
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +515 -455
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/nextjs/app.cjs +5 -6
  12. package/dist/host/nextjs/app.cjs.map +1 -1
  13. package/dist/host/nextjs/app.js +5 -6
  14. package/dist/host/nextjs/app.js.map +1 -1
  15. package/dist/host/nextjs/pages.cjs +6 -11
  16. package/dist/host/nextjs/pages.cjs.map +1 -1
  17. package/dist/host/nextjs/pages.js +9 -11
  18. package/dist/host/nextjs/pages.js.map +1 -1
  19. package/dist/host/react.cjs +435 -374
  20. package/dist/host/react.cjs.map +1 -1
  21. package/dist/host/react.js +435 -374
  22. package/dist/host/react.js.map +1 -1
  23. package/dist/internal/host/nextjs/dom-flight.cjs +16 -7
  24. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  25. package/dist/internal/host/nextjs/dom-flight.d.ts +2 -2
  26. package/dist/internal/host/nextjs/dom-flight.js +16 -7
  27. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  28. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  29. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  30. package/dist/internal/host/nextjs/image-shared.js +2 -2
  31. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  32. package/dist/internal/host/server/fetch-remote-component.cjs +183 -149
  33. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  34. package/dist/internal/host/server/fetch-remote-component.js +185 -149
  35. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  36. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  37. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  38. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  39. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  40. package/dist/internal/runtime/constants.cjs +6 -6
  41. package/dist/internal/runtime/constants.cjs.map +1 -1
  42. package/dist/internal/runtime/constants.d.ts +3 -3
  43. package/dist/internal/runtime/constants.js +4 -4
  44. package/dist/internal/runtime/constants.js.map +1 -1
  45. package/dist/internal/runtime/html/parse-remote-html.cjs +11 -15
  46. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  47. package/dist/internal/runtime/html/parse-remote-html.d.ts +2 -12
  48. package/dist/internal/runtime/html/parse-remote-html.js +17 -15
  49. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  50. package/dist/internal/runtime/loaders/script-loader.cjs +2 -2
  51. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  52. package/dist/internal/runtime/loaders/script-loader.js +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  54. package/dist/internal/runtime/metadata.cjs +42 -0
  55. package/dist/internal/runtime/metadata.cjs.map +1 -1
  56. package/dist/internal/runtime/metadata.d.ts +21 -1
  57. package/dist/internal/runtime/metadata.js +38 -0
  58. package/dist/internal/runtime/metadata.js.map +1 -1
  59. package/dist/internal/runtime/patterns.cjs +38 -0
  60. package/dist/internal/runtime/patterns.cjs.map +1 -0
  61. package/dist/internal/runtime/patterns.d.ts +5 -0
  62. package/dist/internal/runtime/patterns.js +12 -0
  63. package/dist/internal/runtime/patterns.js.map +1 -0
  64. package/dist/internal/runtime/turbopack/chunk-loader.cjs +79 -128
  65. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  66. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  67. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  68. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  69. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  70. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  71. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  72. package/dist/internal/runtime/turbopack/module.js +54 -56
  73. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  74. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  75. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  76. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  77. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  78. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  79. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  80. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  81. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  82. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  83. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  84. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +50 -31
  85. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  86. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  87. package/dist/internal/runtime/turbopack/webpack-runtime.js +52 -34
  88. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  89. package/dist/internal/runtime/types.cjs.map +1 -1
  90. package/dist/internal/runtime/types.d.ts +4 -3
  91. package/dist/internal/utils/logger.cjs.map +1 -1
  92. package/dist/internal/utils/logger.d.ts +1 -1
  93. package/dist/internal/utils/logger.js.map +1 -1
  94. package/dist/internal/utils.cjs +5 -0
  95. package/dist/internal/utils.cjs.map +1 -1
  96. package/dist/internal/utils.d.ts +15 -1
  97. package/dist/internal/utils.js +4 -0
  98. package/dist/internal/utils.js.map +1 -1
  99. package/dist/remote/html.cjs.map +1 -1
  100. package/dist/remote/html.js.map +1 -1
  101. package/dist/remote/nextjs/app.cjs +2 -1
  102. package/dist/remote/nextjs/app.cjs.map +1 -1
  103. package/dist/remote/nextjs/app.js +2 -1
  104. package/dist/remote/nextjs/app.js.map +1 -1
  105. package/package.json +1 -1
@@ -18,70 +18,50 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var chunk_loader_exports = {};
20
20
  __export(chunk_loader_exports, {
21
- createChunkLoader: () => createChunkLoader
21
+ createChunkDispatcher: () => createChunkDispatcher,
22
+ loadChunkWithScope: () => loadChunkWithScope
22
23
  });
23
24
  module.exports = __toCommonJS(chunk_loader_exports);
24
25
  var import_constants = require("#internal/runtime/constants");
26
+ var import_patterns = require("#internal/runtime/patterns");
25
27
  var import_protected_rc_fallback = require("#internal/runtime/url/protected-rc-fallback");
26
28
  var import_error = require("#internal/utils/error");
27
29
  var import_logger = require("#internal/utils/logger");
28
- var import_patterns = require("./patterns");
29
- function createChunkLoader(runtime, resolveClientUrl) {
30
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
31
- (0, import_logger.logDebug)("ChunkLoader", `Loading chunk: "${chunkId}"`);
32
- const self = globalThis;
33
- const {
34
- bundle,
35
- id: path,
36
- prefix
37
- } = import_constants.REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
38
- bundle: scriptBundle ?? "",
39
- id: chunkId
40
- };
41
- (0, import_logger.logDebug)(
42
- "ChunkLoader",
43
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
44
- );
45
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
46
- (0, import_logger.logDebug)("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
47
- if (remoteRuntime === import_constants.RUNTIME_WEBPACK) {
48
- (0, import_logger.logDebug)("ChunkLoader", "Skipping chunk load - webpack runtime detected");
49
- return Promise.resolve(void 0);
50
- }
51
- const url = new URL(
52
- path ? `${prefix ?? ""}${path}`.replace(
53
- /(?<char>[^:])(?<double>\/\/)/g,
54
- "$1/"
55
- ) : "/",
56
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
57
- ).href;
58
- if (url.endsWith(".css")) {
59
- (0, import_logger.logDebug)("ChunkLoader", `Skipping CSS file: "${url}"`);
60
- return;
61
- }
62
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
63
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
64
- }
65
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
66
- (0, import_logger.logDebug)("ChunkLoader", `Returning cached promise for: "${url}"`);
67
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
68
- }
69
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
70
- (0, import_logger.logDebug)("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
71
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
30
+ var import_patterns2 = require("./patterns");
31
+ var import_remote_scope = require("./remote-scope");
32
+ function loadChunkWithScope(scope, chunkId) {
33
+ (0, import_logger.logDebug)(
34
+ "ChunkLoader",
35
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
36
+ );
37
+ const self = globalThis;
38
+ const { bundle, path, prefix } = (0, import_remote_scope.parseRemoteId)(chunkId);
39
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
40
+ if (remoteRuntime === import_constants.RUNTIME_WEBPACK) {
41
+ return Promise.resolve(void 0);
42
+ }
43
+ const rawPath = path ? (0, import_patterns.collapseDoubleSlashes)(`${prefix}${path}`) : "/";
44
+ const url = new URL(rawPath, scope.url).href;
45
+ if (url.endsWith(".css")) {
46
+ return;
47
+ }
48
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
49
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
50
+ }
51
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
52
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
53
+ }
54
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
55
+ if (resolvedUrl !== url) {
56
+ (0, import_logger.logDebug)("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
57
+ }
58
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
59
+ (resolve, reject) => {
72
60
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
73
- const hasTurbopack = import_patterns.TURBOPACK_GLOBAL_RE.test(code);
61
+ const hasTurbopack = import_patterns2.TURBOPACK_GLOBAL_RE.test(code);
74
62
  if (hasTurbopack) {
75
- return handleTurbopackChunk(code, bundle ?? "", url);
63
+ return handleTurbopackChunk(code, scope, url);
76
64
  }
77
- (0, import_logger.logDebug)(
78
- "ChunkLoader",
79
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
80
- );
81
- (0, import_logger.logDebug)(
82
- "ChunkLoader",
83
- `First 500 chars of chunk: ${code.slice(0, 500)}`
84
- );
85
65
  }).then(resolve).catch((error) => {
86
66
  const isProxied = (0, import_protected_rc_fallback.isProxiedUrl)(resolvedUrl);
87
67
  if (isProxied) {
@@ -91,17 +71,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
91
71
  reject(error);
92
72
  }
93
73
  });
94
- });
95
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
74
+ }
75
+ );
76
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
77
+ }
78
+ function createChunkDispatcher() {
79
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
80
+ (0, import_logger.logDebug)("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
81
+ const { bundle } = (0, import_remote_scope.parseRemoteId)(chunkId);
82
+ const bundleName = bundle || scriptBundle || "default";
83
+ const scope = (0, import_remote_scope.getScope)(bundleName);
84
+ (0, import_logger.logDebug)(
85
+ "ChunkDispatcher",
86
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
87
+ );
88
+ if (!scope) {
89
+ (0, import_logger.logWarn)("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
90
+ return Promise.resolve(void 0);
91
+ }
92
+ return loadChunkWithScope(scope, chunkId);
96
93
  };
97
94
  }
98
- async function handleTurbopackChunk(code, bundle, url) {
99
- (0, import_logger.logDebug)(
100
- "ChunkLoader",
101
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
102
- );
95
+ async function handleTurbopackChunk(code, scope, url) {
103
96
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
104
- (0, import_logger.logDebug)("ChunkLoader", `Skipping worker chunk: "${url}"`);
105
97
  const preloadLinks = document.querySelectorAll(
106
98
  `link[rel="preload"][href="${new URL(url).pathname}"]`
107
99
  );
@@ -109,58 +101,41 @@ async function handleTurbopackChunk(code, bundle, url) {
109
101
  return;
110
102
  }
111
103
  const self = globalThis;
112
- const bundleKey = (0, import_constants.getBundleKey)(bundle);
113
- (0, import_logger.logDebug)("ChunkLoader", `Bundle key: "${bundleKey}"`);
104
+ const { globalKey } = scope;
114
105
  const transformedCode = code.replace(
115
106
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
116
- `globalThis["TURBOPACK_${bundleKey}"]`
107
+ `globalThis["TURBOPACK_${globalKey}"]`
117
108
  ).replace(
118
109
  /self\[\s*["']TURBOPACK["']\s*\]/g,
119
- `self["TURBOPACK_${bundleKey}"]`
120
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
110
+ `self["TURBOPACK_${globalKey}"]`
111
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
121
112
  /TURBOPACK_WORKER_LOCATION/g,
122
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
113
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
123
114
  ).replace(
124
115
  /TURBOPACK_NEXT_CHUNK_URLS/g,
125
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
116
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
126
117
  ).replace(
127
118
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
128
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
129
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
119
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
120
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
130
121
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
131
- `//# sourceMappingURL=${new URL(
132
- ".",
133
- new URL(
134
- url,
135
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
136
- )
137
- ).href}$1$2.js.map`
122
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
138
123
  );
139
- if (!self[`TURBOPACK_${bundleKey}`]) {
124
+ if (!self[`TURBOPACK_${globalKey}`]) {
140
125
  const chunkData = [];
141
126
  const turbopackObject = {
142
127
  push: (item) => {
143
- (0, import_logger.logDebug)(
144
- "ChunkLoader",
145
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
146
- );
147
128
  if (Array.isArray(item)) {
148
129
  chunkData.push(item);
149
- (0, import_logger.logDebug)(
150
- "ChunkLoader",
151
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
152
- );
153
130
  } else {
154
131
  chunkData.push([item]);
155
132
  }
156
133
  return chunkData.length;
157
134
  },
158
- // Store chunks for later access
159
135
  __chunks__: chunkData
160
136
  };
161
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
137
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
162
138
  }
163
- (0, import_logger.logDebug)("ChunkLoader", `Creating blob script for: "${url}"`);
164
139
  await new Promise((scriptResolve, scriptReject) => {
165
140
  const blob = new Blob([transformedCode], {
166
141
  type: "application/javascript; charset=UTF-8"
@@ -172,21 +147,6 @@ async function handleTurbopackChunk(code, bundle, url) {
172
147
  script.async = true;
173
148
  script.onload = () => {
174
149
  URL.revokeObjectURL(scriptUrl);
175
- (0, import_logger.logDebug)(
176
- "ChunkLoader",
177
- `Script loaded successfully for bundle "${bundle}"`
178
- );
179
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
180
- (0, import_logger.logDebug)(
181
- "ChunkLoader",
182
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
183
- );
184
- if (turbopackBundle && typeof turbopackBundle === "object") {
185
- (0, import_logger.logDebug)(
186
- "ChunkLoader",
187
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
188
- );
189
- }
190
150
  scriptResolve(void 0);
191
151
  script.remove();
192
152
  };
@@ -201,39 +161,30 @@ async function handleTurbopackChunk(code, bundle, url) {
201
161
  };
202
162
  document.head.appendChild(script);
203
163
  });
204
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
205
- (0, import_logger.logDebug)(
206
- "ChunkLoader",
207
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
208
- );
209
- const loadChunkLists = [];
164
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
165
+ const loadChunkPromises = [];
210
166
  while (chunkLists?.length) {
211
167
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
212
168
  if (chunks.length > 0) {
213
- (0, import_logger.logDebug)(
214
- "ChunkLoader",
215
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
216
- );
217
- chunks.forEach((id) => {
218
- const chunkLoadResult = self.__webpack_chunk_load__?.(
219
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
169
+ for (const id of chunks) {
170
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
171
+ const chunkLoadResult = loadChunkWithScope(
172
+ scope,
173
+ (0, import_remote_scope.formatRemoteId)(scope, `${baseUrl}/_next/${id}`)
220
174
  );
221
175
  if (chunkLoadResult) {
222
- loadChunkLists.push(chunkLoadResult);
176
+ loadChunkPromises.push(chunkLoadResult);
223
177
  }
224
- });
178
+ }
225
179
  }
226
180
  }
227
- if (loadChunkLists.length > 0) {
228
- (0, import_logger.logDebug)(
229
- "ChunkLoader",
230
- `Waiting for ${loadChunkLists.length} additional chunks to load`
231
- );
232
- await Promise.all(loadChunkLists);
181
+ if (loadChunkPromises.length > 0) {
182
+ await Promise.all(loadChunkPromises);
233
183
  }
234
184
  }
235
185
  // Annotate the CommonJS export names for ESM import in node:
236
186
  0 && (module.exports = {
237
- createChunkLoader
187
+ createChunkDispatcher,
188
+ loadChunkWithScope
238
189
  });
239
190
  //# sourceMappingURL=chunk-loader.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n getBundleKey,\n REMOTE_COMPONENT_REGEX,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logDebug, warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAKO;AAEP,mCAA6B;AAC7B,mBAGO;AACP,oBAAoD;AACpD,sBAAoC;AAO7B,SAAS,kBACd,SACA,kBAC0E;AAC1E,SAAO,SAAS,yBACd,SACA,cACA;AACA,gCAAS,eAAe,mBAAmB,UAAU;AACrD,UAAM,OAAO;AACb,UAAM;AAAA,MACJ;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,IAAI,wCAAuB,KAAK,OAAO,GAAG,UAAU;AAAA,MAClD,QAAQ,gBAAgB;AAAA,MACxB,IAAI;AAAA,IACN;AACA;AAAA,MACE;AAAA,MACA,2BAA2B,mBAAmB,mBAAmB;AAAA,IACnE;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AACJ,gCAAS,eAAe,oBAAoB,gBAAgB;AAC5D,QAAI,kBAAkB,kCAAiB;AACrC,kCAAS,eAAe,gDAAgD;AACxE,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAEA,UAAM,MAAM,IAAI;AAAA,MACd,OACI,GAAG,UAAU,KAAK,OAAO;AAAA,QACvB;AAAA,QACA;AAAA,MACF,IACA;AAAA,MACJ,KAAK,wBAAwB,UAAU,SAAS,KAC9C,IAAI,IAAI,SAAS,MAAM;AAAA,IAC3B,EAAE;AACF,QAAI,I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,IAAI,WAAW,MAAM,KAAK,EAAE,QAAQ,CAAC,EAAE;AACtD,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,QACE;AAAA,QACA,WAAW,OAAO,wCAAwC,aAAa,OAAO,KAAK,IAAI;AAAA,MACzF;AACA,aAAO,QAAQ,CAAC,OAAe;AAC7B,cAAM,kBAAkB,KAAK;AAAA,UAC3B,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC,WAAW;AAAA,QAC9D;AACA,YAAI,iBAAiB;AACnB,yBAAe,KAAK,eAAe;AAAA,QACrC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,eAAe,SAAS,GAAG;AAC7B;AAAA,MACE;AAAA,MACA,eAAe,eAAe;AAAA,IAChC;AACA,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import { RUNTIME_WEBPACK } from '#internal/runtime/constants';\nimport { collapseDoubleSlashes } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport {\n logDebug,\n logWarn,\n warnCrossOriginFetchError,\n} from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\nimport {\n formatRemoteId,\n getScope,\n parseRemoteId,\n type RemoteScope,\n} from './remote-scope';\n\n/**\n * Loads a chunk using a specific scope. All state (base URL, proxy callback,\n * TURBOPACK global key) comes from the scope — no global lookups needed.\n *\n * This is the primary chunk loader called directly from:\n * - setupWebpackRuntime (initial chunks)\n * - TurbopackContext.l (module-level chunk loading)\n * - handleTurbopackChunk (CHUNK_LIST additional chunks)\n *\n * The global chunk dedup cache is keyed by absolute URL, so different origins\n * naturally get separate cache entries even when sharing a bundle name.\n */\nexport function loadChunkWithScope(\n scope: RemoteScope,\n chunkId: string,\n): Promise<unknown> | undefined {\n logDebug(\n 'ChunkLoader',\n `loadChunkWithScope: \"${chunkId}\" (scope: \"${scope.scopedName}\")`,\n );\n const self = globalThis as GlobalScope;\n\n const { bundle, path, prefix } = parseRemoteId(chunkId);\n\n // Skip webpack runtime chunks\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : scope.runtime;\n if (remoteRuntime === RUNTIME_WEBPACK) {\n return Promise.resolve(undefined);\n }\n\n const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : '/';\n const url = new URL(rawPath, scope.url).href;\n\n if (url.endsWith('.css')) {\n return;\n }\n\n // Global dedup cache keyed by absolute URL\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;\n if (resolvedUrl !== url) {\n logDebug('ChunkLoader', `Proxied chunk URL: \"${url}\" → \"${resolvedUrl}\"`);\n }\n\n self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(\n (resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, scope, url);\n }\n // Chunk doesn't contain Turbopack globals — nothing to process\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n },\n );\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n}\n\n/**\n * Creates the global `__webpack_chunk_load__` dispatcher.\n * This is a thin wrapper called only by external code (React's RSC runtime).\n * It parses the chunkId, resolves the correct scope, and delegates to\n * `loadChunkWithScope`.\n */\nexport function createChunkDispatcher(): (\n chunkId: string,\n scriptBundle?: string,\n) => Promise<unknown> | undefined {\n return function __chunk_dispatcher__(chunkId: string, scriptBundle?: string) {\n logDebug('ChunkDispatcher', `Dispatching chunk: \"${chunkId}\"`);\n\n const { bundle } = parseRemoteId(chunkId);\n const bundleName = bundle || scriptBundle || 'default';\n\n // Works with both the scoped name (Next.js hosts with server-side\n // rewriting) and the plain bundle name (static/HTML hosts).\n const scope = getScope(bundleName);\n\n logDebug(\n 'ChunkDispatcher',\n `Scope resolution: bundle=\"${bundleName}\", scope=${scope?.scopedName ?? 'null'}`,\n );\n\n if (!scope) {\n logWarn('ChunkDispatcher', `No scope found for bundle \"${bundleName}\"`);\n return Promise.resolve(undefined);\n }\n\n return loadChunkWithScope(scope, chunkId);\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n * Receives scope directly — no global state lookups needed.\n */\nasync function handleTurbopackChunk(\n code: string,\n scope: RemoteScope,\n url: string,\n): Promise<void> {\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const { globalKey } = scope;\n\n // replace global variables with scope-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${globalKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`,\n )\n .replace(/__next_require__/g, `__${globalKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${new URL('.', new URL(url, scope.url)).href}$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor\n if (!self[`TURBOPACK_${globalKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n if (Array.isArray(item)) {\n chunkData.push(item);\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${globalKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n // These CHUNK_LIST chunks load directly via scope — no global dispatch needed.\n const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n const loadChunkPromises: (Promise<unknown> | undefined)[] = [];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n for (const id of chunks) {\n const baseUrl = url.slice(0, url.indexOf('/_next'));\n const chunkLoadResult = loadChunkWithScope(\n scope,\n formatRemoteId(scope, `${baseUrl}/_next/${id}`),\n );\n if (chunkLoadResult) {\n loadChunkPromises.push(chunkLoadResult);\n }\n }\n }\n }\n if (loadChunkPromises.length > 0) {\n await Promise.all(loadChunkPromises);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAgC;AAChC,sBAAsC;AAEtC,mCAA6B;AAC7B,mBAGO;AACP,oBAIO;AACP,IAAAA,mBAAoC;AACpC,0BAKO;AAcA,SAAS,mBACd,OACA,SAC8B;AAC9B;AAAA,IACE;AAAA,IACA,wBAAwB,qBAAqB,MAAM;AAAA,EACrD;AACA,QAAM,OAAO;AAEb,QAAM,EAAE,QAAQ,MAAM,OAAO,QAAI,mCAAc,OAAO;AAGtD,QAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D,MAAM;AACV,MAAI,kBAAkB,kCAAiB;AACrC,WAAO,QAAQ,QAAQ,MAAS;AAAA,EAClC;AAEA,QAAM,UAAU,WAAO,uCAAsB,GAAG,SAAS,MAAM,IAAI;AACnE,QAAM,MAAM,IAAI,IAAI,SAAS,MAAM,GAAG,EAAE;AAExC,MAAI,IAAI,SAAS,MAAM,GAAG;AACxB;AAAA,EACF;AAGA,MAAI,CAAC,KAAK,sDAAsD;AAC9D,SAAK,uDAAuD,CAAC;AAAA,EAC/D;AACA,MAAI,KAAK,qDAAqD,GAAG,GAAG;AAClE,WAAO,KAAK,qDAAqD,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sBAAsB,GAAG;AAC7C,WAAO,MAAM;AACb,WAAO,QAAQ;AACf,WAAO,SAAS,MAAM;AACpB,UAAI,gBAAgB,SAAS;AAC7B,oBAAc,MAAS;AACvB,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,UAAU,MAAM;AACrB,UAAI,gBAAgB,SAAS;AAC7B;AAAA,QACE,IAAI;AAAA,UACF,+BAA+B,OAAO;AAAA,QACxC;AAAA,MACF;AACA,aAAO,OAAO;AAAA,IAChB;AACA,aAAS,KAAK,YAAY,MAAM;AAAA,EAClC,CAAC;AAID,QAAM,aAAa,KAAK,aAAa,uBAAuB;AAG5D,QAAM,oBAAsD,CAAC;AAC7D,SAAO,YAAY,QAAQ;AACzB,UAAM,EAAE,OAAO,IAAI,WAAW,MAAM,KAAK,EAAE,QAAQ,CAAC,EAAE;AACtD,QAAI,OAAO,SAAS,GAAG;AACrB,iBAAW,MAAM,QAAQ;AACvB,cAAM,UAAU,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC;AAClD,cAAM,kBAAkB;AAAA,UACtB;AAAA,cACA,oCAAe,OAAO,GAAG,iBAAiB,IAAI;AAAA,QAChD;AACA,YAAI,iBAAiB;AACnB,4BAAkB,KAAK,eAAe;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,kBAAkB,SAAS,GAAG;AAChC,UAAM,QAAQ,IAAI,iBAAiB;AAAA,EACrC;AACF;","names":["import_patterns"]}
@@ -1,11 +1,26 @@
1
- import { InternalResolveClientUrl } from '../url/resolve-client-url.js';
2
- import { Runtime } from '../constants.js';
1
+ import { RemoteScope } from './remote-scope.js';
2
+ import '../url/resolve-client-url.js';
3
+ import '../constants.js';
3
4
 
4
5
  /**
5
- * Creates chunk loader function for webpack runtime.
6
- * This function is responsible for loading JavaScript chunks from remote applications
7
- * and transforming Turbopack-specific code to work in the host environment.
6
+ * Loads a chunk using a specific scope. All state (base URL, proxy callback,
7
+ * TURBOPACK global key) comes from the scope no global lookups needed.
8
+ *
9
+ * This is the primary chunk loader called directly from:
10
+ * - setupWebpackRuntime (initial chunks)
11
+ * - TurbopackContext.l (module-level chunk loading)
12
+ * - handleTurbopackChunk (CHUNK_LIST additional chunks)
13
+ *
14
+ * The global chunk dedup cache is keyed by absolute URL, so different origins
15
+ * naturally get separate cache entries even when sharing a bundle name.
8
16
  */
9
- declare function createChunkLoader(runtime: Runtime, resolveClientUrl?: InternalResolveClientUrl): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined;
17
+ declare function loadChunkWithScope(scope: RemoteScope, chunkId: string): Promise<unknown> | undefined;
18
+ /**
19
+ * Creates the global `__webpack_chunk_load__` dispatcher.
20
+ * This is a thin wrapper called only by external code (React's RSC runtime).
21
+ * It parses the chunkId, resolves the correct scope, and delegates to
22
+ * `loadChunkWithScope`.
23
+ */
24
+ declare function createChunkDispatcher(): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined;
10
25
 
11
- export { createChunkLoader };
26
+ export { createChunkDispatcher, loadChunkWithScope };