react-server-dom-webpack 18.3.0-next-fa4314841-20230502 → 19.0.0-canary-2b036d3f1-20240327

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 (42) hide show
  1. package/cjs/react-server-dom-webpack-client.browser.development.js +1768 -1188
  2. package/cjs/react-server-dom-webpack-client.browser.production.js +1739 -0
  3. package/cjs/react-server-dom-webpack-client.browser.production.min.js +40 -34
  4. package/cjs/react-server-dom-webpack-client.browser.production.min.js.map +1 -0
  5. package/cjs/react-server-dom-webpack-client.edge.development.js +1755 -221
  6. package/cjs/react-server-dom-webpack-client.edge.production.js +1986 -0
  7. package/cjs/react-server-dom-webpack-client.edge.production.min.js +45 -28
  8. package/cjs/react-server-dom-webpack-client.edge.production.min.js.map +1 -0
  9. package/cjs/react-server-dom-webpack-client.node.development.js +1743 -239
  10. package/cjs/react-server-dom-webpack-client.node.production.js +1942 -0
  11. package/cjs/react-server-dom-webpack-client.node.production.min.js +44 -28
  12. package/cjs/react-server-dom-webpack-client.node.production.min.js.map +1 -0
  13. package/cjs/react-server-dom-webpack-client.node.unbundled.development.js +1702 -194
  14. package/cjs/react-server-dom-webpack-client.node.unbundled.production.js +1895 -0
  15. package/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js +43 -26
  16. package/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js.map +1 -0
  17. package/cjs/react-server-dom-webpack-node-register.js +12 -18
  18. package/cjs/react-server-dom-webpack-node-register.js.map +1 -0
  19. package/cjs/react-server-dom-webpack-plugin.js +22 -19
  20. package/cjs/react-server-dom-webpack-plugin.js.map +1 -0
  21. package/cjs/react-server-dom-webpack-server.browser.development.js +1588 -808
  22. package/cjs/react-server-dom-webpack-server.browser.production.js +3257 -0
  23. package/cjs/react-server-dom-webpack-server.browser.production.min.js +80 -62
  24. package/cjs/react-server-dom-webpack-server.browser.production.min.js.map +1 -0
  25. package/cjs/react-server-dom-webpack-server.edge.development.js +1583 -811
  26. package/cjs/react-server-dom-webpack-server.edge.production.js +3261 -0
  27. package/cjs/react-server-dom-webpack-server.edge.production.min.js +82 -62
  28. package/cjs/react-server-dom-webpack-server.edge.production.min.js.map +1 -0
  29. package/cjs/react-server-dom-webpack-server.node.development.js +1575 -805
  30. package/cjs/react-server-dom-webpack-server.node.production.js +3464 -0
  31. package/cjs/react-server-dom-webpack-server.node.production.min.js +85 -67
  32. package/cjs/react-server-dom-webpack-server.node.production.min.js.map +1 -0
  33. package/cjs/react-server-dom-webpack-server.node.unbundled.development.js +1526 -761
  34. package/cjs/react-server-dom-webpack-server.node.unbundled.production.js +3391 -0
  35. package/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js +82 -65
  36. package/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js.map +1 -0
  37. package/esm/react-server-dom-webpack-node-loader.production.min.js +19 -12
  38. package/package.json +7 -13
  39. package/umd/react-server-dom-webpack-client.browser.development.js +1770 -1189
  40. package/umd/react-server-dom-webpack-client.browser.production.min.js +26 -20
  41. package/umd/react-server-dom-webpack-server.browser.development.js +1589 -808
  42. package/umd/react-server-dom-webpack-server.browser.production.min.js +55 -42
@@ -56,10 +56,13 @@ function printWarning(level, format, args) {
56
56
  }
57
57
  }
58
58
 
59
+ // -----------------------------------------------------------------------------
60
+ var enablePostpone = false;
61
+
59
62
  function scheduleWork(callback) {
60
63
  setTimeout(callback, 0);
61
64
  }
62
- var VIEW_SIZE = 512;
65
+ var VIEW_SIZE = 2048;
63
66
  var currentView = null;
64
67
  var writtenBytes = 0;
65
68
  function beginWriting(destination) {
@@ -67,20 +70,14 @@ function beginWriting(destination) {
67
70
  writtenBytes = 0;
68
71
  }
69
72
  function writeChunk(destination, chunk) {
70
- if (chunk.length === 0) {
73
+ if (chunk.byteLength === 0) {
71
74
  return;
72
75
  }
73
76
 
74
- if (chunk.length > VIEW_SIZE) {
75
- {
76
- if (precomputedChunkSet.has(chunk)) {
77
- error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.');
78
- }
79
- } // this chunk may overflow a single view which implies it was not
77
+ if (chunk.byteLength > VIEW_SIZE) {
78
+ // this chunk may overflow a single view which implies it was not
80
79
  // one that is cached by the streaming renderer. We will enqueu
81
80
  // it directly and expect it is not re-used
82
-
83
-
84
81
  if (writtenBytes > 0) {
85
82
  destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
86
83
  currentView = new Uint8Array(VIEW_SIZE);
@@ -94,7 +91,7 @@ function writeChunk(destination, chunk) {
94
91
  var bytesToWrite = chunk;
95
92
  var allowableBytes = currentView.length - writtenBytes;
96
93
 
97
- if (allowableBytes < bytesToWrite.length) {
94
+ if (allowableBytes < bytesToWrite.byteLength) {
98
95
  // this chunk would overflow the current view. We enqueue a full view
99
96
  // and start a new view with the remaining chunk
100
97
  if (allowableBytes === 0) {
@@ -114,7 +111,7 @@ function writeChunk(destination, chunk) {
114
111
  }
115
112
 
116
113
  currentView.set(bytesToWrite, writtenBytes);
117
- writtenBytes += bytesToWrite.length;
114
+ writtenBytes += bytesToWrite.byteLength;
118
115
  }
119
116
  function writeChunkAndReturn(destination, chunk) {
120
117
  writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more
@@ -135,7 +132,9 @@ var textEncoder = new TextEncoder();
135
132
  function stringToChunk(content) {
136
133
  return textEncoder.encode(content);
137
134
  }
138
- var precomputedChunkSet = new Set() ;
135
+ function byteLengthOfChunk(chunk) {
136
+ return chunk.byteLength;
137
+ }
139
138
  function closeWithError(destination, error) {
140
139
  // $FlowFixMe[method-unbinding]
141
140
  if (typeof destination.error === 'function') {
@@ -152,65 +151,270 @@ function closeWithError(destination, error) {
152
151
  }
153
152
  }
154
153
 
155
- // This file is an intermediate layer to translate between Flight
156
- var stringify = JSON.stringify;
157
-
158
- function serializeRowHeader(tag, id) {
159
- return id.toString(16) + ':' + tag;
154
+ // eslint-disable-next-line no-unused-vars
155
+ var CLIENT_REFERENCE_TAG$1 = Symbol.for('react.client.reference');
156
+ var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
157
+ function isClientReference(reference) {
158
+ return reference.$$typeof === CLIENT_REFERENCE_TAG$1;
159
+ }
160
+ function isServerReference(reference) {
161
+ return reference.$$typeof === SERVER_REFERENCE_TAG;
162
+ }
163
+ function registerClientReference(proxyImplementation, id, exportName) {
164
+ return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false);
160
165
  }
161
166
 
162
- function processErrorChunkProd(request, id, digest) {
163
- {
164
- // These errors should never make it into a build so we don't need to encode them in codes.json
165
- // eslint-disable-next-line react-internal/prod-error-codes
166
- throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.');
167
+ function registerClientReferenceImpl(proxyImplementation, id, async) {
168
+ return Object.defineProperties(proxyImplementation, {
169
+ $$typeof: {
170
+ value: CLIENT_REFERENCE_TAG$1
171
+ },
172
+ $$id: {
173
+ value: id
174
+ },
175
+ $$async: {
176
+ value: async
177
+ }
178
+ });
179
+ } // $FlowFixMe[method-unbinding]
180
+
181
+
182
+ var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding]
183
+
184
+ var ArraySlice = Array.prototype.slice;
185
+
186
+ function bind() {
187
+ // $FlowFixMe[unsupported-syntax]
188
+ var newFn = FunctionBind.apply(this, arguments);
189
+
190
+ if (this.$$typeof === SERVER_REFERENCE_TAG) {
191
+ {
192
+ var thisBind = arguments[0];
193
+
194
+ if (thisBind != null) {
195
+ error('Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().');
196
+ }
197
+ }
198
+
199
+ var args = ArraySlice.call(arguments, 1);
200
+ return Object.defineProperties(newFn, {
201
+ $$typeof: {
202
+ value: SERVER_REFERENCE_TAG
203
+ },
204
+ $$id: {
205
+ value: this.$$id
206
+ },
207
+ $$bound: {
208
+ value: this.$$bound ? this.$$bound.concat(args) : args
209
+ },
210
+ bind: {
211
+ value: bind
212
+ }
213
+ });
167
214
  }
168
- }
169
- function processErrorChunkDev(request, id, digest, message, stack) {
170
215
 
171
- var errorInfo = {
172
- digest: digest,
173
- message: message,
174
- stack: stack
175
- };
176
- var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
177
- return stringToChunk(row);
178
- }
179
- function processModelChunk(request, id, model) {
180
- // $FlowFixMe[incompatible-type] stringify can return null
181
- var json = stringify(model, request.toJSON);
182
- var row = id.toString(16) + ':' + json + '\n';
183
- return stringToChunk(row);
216
+ return newFn;
184
217
  }
185
- function processReferenceChunk(request, id, reference) {
186
- var json = stringify(reference);
187
- var row = id.toString(16) + ':' + json + '\n';
188
- return stringToChunk(row);
218
+
219
+ function registerServerReference(reference, id, exportName) {
220
+ return Object.defineProperties(reference, {
221
+ $$typeof: {
222
+ value: SERVER_REFERENCE_TAG
223
+ },
224
+ $$id: {
225
+ value: exportName === null ? id : id + '#' + exportName,
226
+ configurable: true
227
+ },
228
+ $$bound: {
229
+ value: null,
230
+ configurable: true
231
+ },
232
+ bind: {
233
+ value: bind,
234
+ configurable: true
235
+ }
236
+ });
189
237
  }
190
- function processImportChunk(request, id, clientReferenceMetadata) {
191
- // $FlowFixMe[incompatible-type] stringify can return null
192
- var json = stringify(clientReferenceMetadata);
193
- var row = serializeRowHeader('I', id) + json + '\n';
194
- return stringToChunk(row);
238
+ var PROMISE_PROTOTYPE = Promise.prototype;
239
+ var deepProxyHandlers = {
240
+ get: function (target, name, receiver) {
241
+ switch (name) {
242
+ // These names are read by the Flight runtime if you end up using the exports object.
243
+ case '$$typeof':
244
+ // These names are a little too common. We should probably have a way to
245
+ // have the Flight runtime extract the inner target instead.
246
+ return target.$$typeof;
247
+
248
+ case '$$id':
249
+ return target.$$id;
250
+
251
+ case '$$async':
252
+ return target.$$async;
253
+
254
+ case 'name':
255
+ return target.name;
256
+
257
+ case 'displayName':
258
+ return undefined;
259
+ // We need to special case this because createElement reads it if we pass this
260
+ // reference.
261
+
262
+ case 'defaultProps':
263
+ return undefined;
264
+ // Avoid this attempting to be serialized.
265
+
266
+ case 'toJSON':
267
+ return undefined;
268
+
269
+ case Symbol.toPrimitive:
270
+ // $FlowFixMe[prop-missing]
271
+ return Object.prototype[Symbol.toPrimitive];
272
+
273
+ case Symbol.toStringTag:
274
+ // $FlowFixMe[prop-missing]
275
+ return Object.prototype[Symbol.toStringTag];
276
+
277
+ case 'Provider':
278
+ throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider.");
279
+ } // eslint-disable-next-line react-internal/safe-string-coercion
280
+
281
+
282
+ var expression = String(target.name) + '.' + String(name);
283
+ throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.');
284
+ },
285
+ set: function () {
286
+ throw new Error('Cannot assign to a client module from a server module.');
287
+ }
288
+ };
289
+
290
+ function getReference(target, name) {
291
+ switch (name) {
292
+ // These names are read by the Flight runtime if you end up using the exports object.
293
+ case '$$typeof':
294
+ return target.$$typeof;
295
+
296
+ case '$$id':
297
+ return target.$$id;
298
+
299
+ case '$$async':
300
+ return target.$$async;
301
+
302
+ case 'name':
303
+ return target.name;
304
+ // We need to special case this because createElement reads it if we pass this
305
+ // reference.
306
+
307
+ case 'defaultProps':
308
+ return undefined;
309
+ // Avoid this attempting to be serialized.
310
+
311
+ case 'toJSON':
312
+ return undefined;
313
+
314
+ case Symbol.toPrimitive:
315
+ // $FlowFixMe[prop-missing]
316
+ return Object.prototype[Symbol.toPrimitive];
317
+
318
+ case Symbol.toStringTag:
319
+ // $FlowFixMe[prop-missing]
320
+ return Object.prototype[Symbol.toStringTag];
321
+
322
+ case '__esModule':
323
+ // Something is conditionally checking which export to use. We'll pretend to be
324
+ // an ESM compat module but then we'll check again on the client.
325
+ var moduleId = target.$$id;
326
+ target.default = registerClientReferenceImpl(function () {
327
+ throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component.");
328
+ }, target.$$id + '#', target.$$async);
329
+ return true;
330
+
331
+ case 'then':
332
+ if (target.then) {
333
+ // Use a cached value
334
+ return target.then;
335
+ }
336
+
337
+ if (!target.$$async) {
338
+ // If this module is expected to return a Promise (such as an AsyncModule) then
339
+ // we should resolve that with a client reference that unwraps the Promise on
340
+ // the client.
341
+ var clientReference = registerClientReferenceImpl({}, target.$$id, true);
342
+ var proxy = new Proxy(clientReference, proxyHandlers$1); // Treat this as a resolved Promise for React's use()
343
+
344
+ target.status = 'fulfilled';
345
+ target.value = proxy;
346
+ var then = target.then = registerClientReferenceImpl(function then(resolve, reject) {
347
+ // Expose to React.
348
+ return Promise.resolve(resolve(proxy));
349
+ }, // If this is not used as a Promise but is treated as a reference to a `.then`
350
+ // export then we should treat it as a reference to that name.
351
+ target.$$id + '#then', false);
352
+ return then;
353
+ } else {
354
+ // Since typeof .then === 'function' is a feature test we'd continue recursing
355
+ // indefinitely if we return a function. Instead, we return an object reference
356
+ // if we check further.
357
+ return undefined;
358
+ }
359
+
360
+ }
361
+
362
+ if (typeof name === 'symbol') {
363
+ throw new Error('Cannot read Symbol exports. Only named exports are supported on a client module ' + 'imported on the server.');
364
+ }
365
+
366
+ var cachedReference = target[name];
367
+
368
+ if (!cachedReference) {
369
+ var reference = registerClientReferenceImpl(function () {
370
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
371
+ "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component.");
372
+ }, target.$$id + '#' + name, target.$$async);
373
+ Object.defineProperty(reference, 'name', {
374
+ value: name
375
+ });
376
+ cachedReference = target[name] = new Proxy(reference, deepProxyHandlers);
377
+ }
378
+
379
+ return cachedReference;
195
380
  }
196
- function processHintChunk(request, id, code, model) {
197
- var json = stringify(model);
198
- var row = serializeRowHeader('H' + code, id) + json + '\n';
199
- return stringToChunk(row);
381
+
382
+ var proxyHandlers$1 = {
383
+ get: function (target, name, receiver) {
384
+ return getReference(target, name);
385
+ },
386
+ getOwnPropertyDescriptor: function (target, name) {
387
+ var descriptor = Object.getOwnPropertyDescriptor(target, name);
388
+
389
+ if (!descriptor) {
390
+ descriptor = {
391
+ value: getReference(target, name),
392
+ writable: false,
393
+ configurable: false,
394
+ enumerable: false
395
+ };
396
+ Object.defineProperty(target, name, descriptor);
397
+ }
398
+
399
+ return descriptor;
400
+ },
401
+ getPrototypeOf: function (target) {
402
+ // Pretend to be a Promise in case anyone asks.
403
+ return PROMISE_PROTOTYPE;
404
+ },
405
+ set: function () {
406
+ throw new Error('Cannot assign to a client module from a server module.');
407
+ }
408
+ };
409
+ function createClientModuleProxy(moduleId) {
410
+ var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import.
411
+ moduleId, false);
412
+ return new Proxy(clientReference, proxyHandlers$1);
200
413
  }
201
414
 
202
- // eslint-disable-next-line no-unused-vars
203
- var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
204
- var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
205
415
  function getClientReferenceKey(reference) {
206
416
  return reference.$$async ? reference.$$id + '#async' : reference.$$id;
207
417
  }
208
- function isClientReference(reference) {
209
- return reference.$$typeof === CLIENT_REFERENCE_TAG;
210
- }
211
- function isServerReference(reference) {
212
- return reference.$$typeof === SERVER_REFERENCE_TAG;
213
- }
214
418
  function resolveClientReferenceMetadata(config, clientReference) {
215
419
  var modulePath = clientReference.$$id;
216
420
  var name = '';
@@ -236,12 +440,11 @@ function resolveClientReferenceMetadata(config, clientReference) {
236
440
  }
237
441
  }
238
442
 
239
- return {
240
- id: resolvedModuleData.id,
241
- chunks: resolvedModuleData.chunks,
242
- name: name,
243
- async: !!clientReference.$$async
244
- };
443
+ if (clientReference.$$async === true) {
444
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1];
445
+ } else {
446
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
447
+ }
245
448
  }
246
449
  function getServerReferenceId(config, serverReference) {
247
450
  return serverReference.$$id;
@@ -252,340 +455,365 @@ function getServerReferenceBoundArguments(config, serverReference) {
252
455
 
253
456
  var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
254
457
 
255
- var ReactDOMFlightServerDispatcher = {
458
+ var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.ReactDOMCurrentDispatcher;
459
+ var previousDispatcher = ReactDOMCurrentDispatcher.current;
460
+ ReactDOMCurrentDispatcher.current = {
256
461
  prefetchDNS: prefetchDNS,
257
462
  preconnect: preconnect,
258
463
  preload: preload,
259
- preinit: preinit
464
+ preloadModule: preloadModule$1,
465
+ preinitStyle: preinitStyle,
466
+ preinitScript: preinitScript,
467
+ preinitModuleScript: preinitModuleScript
260
468
  };
261
469
 
262
- function prefetchDNS(href, options) {
263
- {
264
- if (typeof href === 'string') {
265
- var request = resolveRequest();
470
+ function prefetchDNS(href) {
471
+ if (typeof href === 'string' && href) {
472
+ var request = resolveRequest();
266
473
 
267
- if (request) {
268
- var hints = getHints(request);
269
- var key = 'D' + href;
474
+ if (request) {
475
+ var hints = getHints(request);
476
+ var key = 'D|' + href;
270
477
 
271
- if (hints.has(key)) {
272
- // duplicate hint
273
- return;
274
- }
275
-
276
- hints.add(key);
277
-
278
- if (options) {
279
- emitHint(request, 'D', [href, options]);
280
- } else {
281
- emitHint(request, 'D', href);
282
- }
478
+ if (hints.has(key)) {
479
+ // duplicate hint
480
+ return;
283
481
  }
482
+
483
+ hints.add(key);
484
+ emitHint(request, 'D', href);
485
+ } else {
486
+ previousDispatcher.prefetchDNS(href);
284
487
  }
285
488
  }
286
489
  }
287
490
 
288
- function preconnect(href, options) {
289
- {
290
- if (typeof href === 'string') {
291
- var request = resolveRequest();
491
+ function preconnect(href, crossOrigin) {
492
+ if (typeof href === 'string') {
493
+ var request = resolveRequest();
292
494
 
293
- if (request) {
294
- var hints = getHints(request);
295
- var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : '';
296
- var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href;
495
+ if (request) {
496
+ var hints = getHints(request);
497
+ var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href;
297
498
 
298
- if (hints.has(key)) {
299
- // duplicate hint
300
- return;
301
- }
499
+ if (hints.has(key)) {
500
+ // duplicate hint
501
+ return;
502
+ }
302
503
 
303
- hints.add(key);
504
+ hints.add(key);
304
505
 
305
- if (options) {
306
- emitHint(request, 'C', [href, options]);
307
- } else {
308
- emitHint(request, 'C', href);
309
- }
506
+ if (typeof crossOrigin === 'string') {
507
+ emitHint(request, 'C', [href, crossOrigin]);
508
+ } else {
509
+ emitHint(request, 'C', href);
310
510
  }
511
+ } else {
512
+ previousDispatcher.preconnect(href, crossOrigin);
311
513
  }
312
514
  }
313
515
  }
314
516
 
315
- function preload(href, options) {
316
- {
317
- if (typeof href === 'string') {
318
- var request = resolveRequest();
517
+ function preload(href, as, options) {
518
+ if (typeof href === 'string') {
519
+ var request = resolveRequest();
319
520
 
320
- if (request) {
321
- var hints = getHints(request);
322
- var key = 'L' + href;
521
+ if (request) {
522
+ var hints = getHints(request);
523
+ var key = 'L';
323
524
 
324
- if (hints.has(key)) {
325
- // duplicate hint
326
- return;
327
- }
525
+ if (as === 'image' && options) {
526
+ key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes);
527
+ } else {
528
+ key += "[" + as + "]" + href;
529
+ }
530
+
531
+ if (hints.has(key)) {
532
+ // duplicate hint
533
+ return;
534
+ }
328
535
 
329
- hints.add(key);
330
- emitHint(request, 'L', [href, options]);
536
+ hints.add(key);
537
+ var trimmed = trimOptions(options);
538
+
539
+ if (trimmed) {
540
+ emitHint(request, 'L', [href, as, trimmed]);
541
+ } else {
542
+ emitHint(request, 'L', [href, as]);
331
543
  }
544
+ } else {
545
+ previousDispatcher.preload(href, as, options);
332
546
  }
333
547
  }
334
548
  }
335
549
 
336
- function preinit(href, options) {
337
- {
338
- if (typeof href === 'string') {
339
- var request = resolveRequest();
550
+ function preloadModule$1(href, options) {
551
+ if (typeof href === 'string') {
552
+ var request = resolveRequest();
340
553
 
341
- if (request) {
342
- var hints = getHints(request);
343
- var key = 'I' + href;
554
+ if (request) {
555
+ var hints = getHints(request);
556
+ var key = 'm|' + href;
344
557
 
345
- if (hints.has(key)) {
346
- // duplicate hint
347
- return;
348
- }
558
+ if (hints.has(key)) {
559
+ // duplicate hint
560
+ return;
561
+ }
562
+
563
+ hints.add(key);
564
+ var trimmed = trimOptions(options);
349
565
 
350
- hints.add(key);
351
- emitHint(request, 'I', [href, options]);
566
+ if (trimmed) {
567
+ return emitHint(request, 'm', [href, trimmed]);
568
+ } else {
569
+ return emitHint(request, 'm', href);
352
570
  }
571
+ } else {
572
+ previousDispatcher.preloadModule(href, options);
353
573
  }
354
574
  }
355
575
  }
356
576
 
357
- var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher;
358
- function prepareHostDispatcher() {
359
- ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher;
360
- } // Used to distinguish these contexts from ones used in other renderers.
361
- function createHints() {
362
- return new Set();
363
- }
577
+ function preinitStyle(href, precedence, options) {
578
+ if (typeof href === 'string') {
579
+ var request = resolveRequest();
364
580
 
365
- var supportsRequestStorage = typeof AsyncLocalStorage === 'function';
366
- var requestStorage = supportsRequestStorage ? new AsyncLocalStorage() : null;
581
+ if (request) {
582
+ var hints = getHints(request);
583
+ var key = 'S|' + href;
367
584
 
368
- // ATTENTION
369
- // When adding new symbols to this file,
370
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
371
- // The Symbol used to tag the ReactElement-like types.
372
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
373
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
374
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
375
- var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
376
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
377
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
378
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
379
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
380
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
381
- var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
382
- var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
383
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
384
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
385
- function getIteratorFn(maybeIterable) {
386
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
387
- return null;
388
- }
585
+ if (hints.has(key)) {
586
+ // duplicate hint
587
+ return;
588
+ }
389
589
 
390
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
590
+ hints.add(key);
591
+ var trimmed = trimOptions(options);
391
592
 
392
- if (typeof maybeIterator === 'function') {
393
- return maybeIterator;
593
+ if (trimmed) {
594
+ return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]);
595
+ } else if (typeof precedence === 'string') {
596
+ return emitHint(request, 'S', [href, precedence]);
597
+ } else {
598
+ return emitHint(request, 'S', href);
599
+ }
600
+ } else {
601
+ previousDispatcher.preinitStyle(href, precedence, options);
602
+ }
394
603
  }
395
-
396
- return null;
397
604
  }
398
605
 
399
- var rendererSigil;
400
-
401
- {
402
- // Use this to detect multiple renderers using the same context
403
- rendererSigil = {};
404
- } // Used to store the parent path of all context overrides in a shared linked list.
405
- // Forming a reverse tree.
406
- // The structure of a context snapshot is an implementation of this file.
407
- // Currently, it's implemented as tracking the current active node.
606
+ function preinitScript(src, options) {
607
+ if (typeof src === 'string') {
608
+ var request = resolveRequest();
408
609
 
610
+ if (request) {
611
+ var hints = getHints(request);
612
+ var key = 'X|' + src;
409
613
 
410
- var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
411
- // This global (actually thread local) state represents what state all those "current",
412
- // fields are currently in.
614
+ if (hints.has(key)) {
615
+ // duplicate hint
616
+ return;
617
+ }
413
618
 
414
- var currentActiveSnapshot = null;
619
+ hints.add(key);
620
+ var trimmed = trimOptions(options);
415
621
 
416
- function popNode(prev) {
417
- {
418
- prev.context._currentValue = prev.parentValue;
622
+ if (trimmed) {
623
+ return emitHint(request, 'X', [src, trimmed]);
624
+ } else {
625
+ return emitHint(request, 'X', src);
626
+ }
627
+ } else {
628
+ previousDispatcher.preinitScript(src, options);
629
+ }
419
630
  }
420
631
  }
421
632
 
422
- function pushNode(next) {
423
- {
424
- next.context._currentValue = next.value;
425
- }
426
- }
633
+ function preinitModuleScript(src, options) {
634
+ if (typeof src === 'string') {
635
+ var request = resolveRequest();
427
636
 
428
- function popToNearestCommonAncestor(prev, next) {
429
- if (prev === next) ; else {
430
- popNode(prev);
431
- var parentPrev = prev.parent;
432
- var parentNext = next.parent;
637
+ if (request) {
638
+ var hints = getHints(request);
639
+ var key = 'M|' + src;
433
640
 
434
- if (parentPrev === null) {
435
- if (parentNext !== null) {
436
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
437
- }
438
- } else {
439
- if (parentNext === null) {
440
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
641
+ if (hints.has(key)) {
642
+ // duplicate hint
643
+ return;
441
644
  }
442
645
 
443
- popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common.
646
+ hints.add(key);
647
+ var trimmed = trimOptions(options);
444
648
 
445
- pushNode(next);
649
+ if (trimmed) {
650
+ return emitHint(request, 'M', [src, trimmed]);
651
+ } else {
652
+ return emitHint(request, 'M', src);
653
+ }
654
+ } else {
655
+ previousDispatcher.preinitModuleScript(src, options);
446
656
  }
447
657
  }
448
- }
658
+ } // Flight normally encodes undefined as a special character however for directive option
659
+ // arguments we don't want to send unnecessary keys and bloat the payload so we create a
660
+ // trimmed object which omits any keys with null or undefined values.
661
+ // This is only typesafe because these option objects have entirely optional fields where
662
+ // null and undefined represent the same thing as no property.
449
663
 
450
- function popAllPrevious(prev) {
451
- popNode(prev);
452
- var parentPrev = prev.parent;
453
-
454
- if (parentPrev !== null) {
455
- popAllPrevious(parentPrev);
456
- }
457
- }
458
664
 
459
- function pushAllNext(next) {
460
- var parentNext = next.parent;
665
+ function trimOptions(options) {
666
+ if (options == null) return null;
667
+ var hasProperties = false;
668
+ var trimmed = {};
461
669
 
462
- if (parentNext !== null) {
463
- pushAllNext(parentNext);
670
+ for (var key in options) {
671
+ if (options[key] != null) {
672
+ hasProperties = true;
673
+ trimmed[key] = options[key];
674
+ }
464
675
  }
465
676
 
466
- pushNode(next);
677
+ return hasProperties ? trimmed : null;
467
678
  }
468
679
 
469
- function popPreviousToCommonLevel(prev, next) {
470
- popNode(prev);
471
- var parentPrev = prev.parent;
680
+ function getImagePreloadKey(href, imageSrcSet, imageSizes) {
681
+ var uniquePart = '';
472
682
 
473
- if (parentPrev === null) {
474
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
475
- }
683
+ if (typeof imageSrcSet === 'string' && imageSrcSet !== '') {
684
+ uniquePart += '[' + imageSrcSet + ']';
476
685
 
477
- if (parentPrev.depth === next.depth) {
478
- // We found the same level. Now we just need to find a shared ancestor.
479
- popToNearestCommonAncestor(parentPrev, next);
686
+ if (typeof imageSizes === 'string') {
687
+ uniquePart += '[' + imageSizes + ']';
688
+ }
480
689
  } else {
481
- // We must still be deeper.
482
- popPreviousToCommonLevel(parentPrev, next);
690
+ uniquePart += '[][]' + href;
483
691
  }
692
+
693
+ return "[image]" + uniquePart;
484
694
  }
485
695
 
486
- function popNextToCommonLevel(prev, next) {
487
- var parentNext = next.parent;
696
+ // This module registers the host dispatcher so it needs to be imported
697
+ // small, smaller than how we encode undefined, and is unambiguous. We could use
698
+ // a different tuple structure to encode this instead but this makes the runtime
699
+ // cost cheaper by eliminating a type checks in more positions.
700
+ // prettier-ignore
488
701
 
489
- if (parentNext === null) {
490
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
491
- }
702
+ function createHints() {
703
+ return new Set();
704
+ }
492
705
 
493
- if (prev.depth === parentNext.depth) {
494
- // We found the same level. Now we just need to find a shared ancestor.
495
- popToNearestCommonAncestor(prev, parentNext);
496
- } else {
497
- // We must still be deeper.
498
- popNextToCommonLevel(prev, parentNext);
499
- }
500
-
501
- pushNode(next);
502
- } // Perform context switching to the new snapshot.
503
- // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
504
- // updating all the context's current values. That way reads, always just read the current value.
505
- // At the cost of updating contexts even if they're never read by this subtree.
506
-
507
-
508
- function switchContext(newSnapshot) {
509
- // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
510
- // We also need to update any new contexts that are now on the stack with the deepest value.
511
- // The easiest way to update new contexts is to just reapply them in reverse order from the
512
- // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
513
- // for that. Therefore this algorithm is recursive.
514
- // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
515
- // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
516
- // 3) Then we reapply new contexts on the way back up the stack.
517
- var prev = currentActiveSnapshot;
518
- var next = newSnapshot;
519
-
520
- if (prev !== next) {
521
- if (prev === null) {
522
- // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev.
523
- pushAllNext(next);
524
- } else if (next === null) {
525
- popAllPrevious(prev);
526
- } else if (prev.depth === next.depth) {
527
- popToNearestCommonAncestor(prev, next);
528
- } else if (prev.depth > next.depth) {
529
- popPreviousToCommonLevel(prev, next);
530
- } else {
531
- popNextToCommonLevel(prev, next);
532
- }
706
+ var supportsRequestStorage = typeof AsyncLocalStorage === 'function';
707
+ var requestStorage = supportsRequestStorage ? new AsyncLocalStorage() : null; // We use the Node version but get access to async_hooks from a global.
533
708
 
534
- currentActiveSnapshot = next;
535
- }
709
+ typeof async_hooks === 'object' ? async_hooks.createHook : function () {
710
+ return {
711
+ enable: function () {},
712
+ disable: function () {}
713
+ };
714
+ };
715
+ typeof async_hooks === 'object' ? async_hooks.executionAsyncId : null;
716
+
717
+ var TEMPORARY_REFERENCE_TAG = Symbol.for('react.temporary.reference'); // eslint-disable-next-line no-unused-vars
718
+
719
+ function isTemporaryReference(reference) {
720
+ return reference.$$typeof === TEMPORARY_REFERENCE_TAG;
721
+ }
722
+ function resolveTemporaryReferenceID(temporaryReference) {
723
+ return temporaryReference.$$id;
536
724
  }
537
- function pushProvider(context, nextValue) {
538
- var prevValue;
725
+ var proxyHandlers = {
726
+ get: function (target, name, receiver) {
727
+ switch (name) {
728
+ // These names are read by the Flight runtime if you end up using the exports object.
729
+ case '$$typeof':
730
+ // These names are a little too common. We should probably have a way to
731
+ // have the Flight runtime extract the inner target instead.
732
+ return target.$$typeof;
539
733
 
540
- {
541
- prevValue = context._currentValue;
542
- context._currentValue = nextValue;
734
+ case '$$id':
735
+ return target.$$id;
543
736
 
544
- {
545
- if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
546
- error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
547
- }
737
+ case '$$async':
738
+ return target.$$async;
739
+
740
+ case 'name':
741
+ return undefined;
548
742
 
549
- context._currentRenderer = rendererSigil;
743
+ case 'displayName':
744
+ return undefined;
745
+ // We need to special case this because createElement reads it if we pass this
746
+ // reference.
747
+
748
+ case 'defaultProps':
749
+ return undefined;
750
+ // Avoid this attempting to be serialized.
751
+
752
+ case 'toJSON':
753
+ return undefined;
754
+
755
+ case Symbol.toPrimitive:
756
+ // $FlowFixMe[prop-missing]
757
+ return Object.prototype[Symbol.toPrimitive];
758
+
759
+ case Symbol.toStringTag:
760
+ // $FlowFixMe[prop-missing]
761
+ return Object.prototype[Symbol.toStringTag];
762
+
763
+ case 'Provider':
764
+ throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider.");
550
765
  }
551
- }
552
766
 
553
- var prevNode = currentActiveSnapshot;
554
- var newNode = {
555
- parent: prevNode,
556
- depth: prevNode === null ? 0 : prevNode.depth + 1,
557
- context: context,
558
- parentValue: prevValue,
559
- value: nextValue
560
- };
561
- currentActiveSnapshot = newNode;
562
- return newNode;
767
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
768
+ "Cannot access " + String(name) + " on the server. " + 'You cannot dot into a temporary client reference from a server component. ' + 'You can only pass the value through to the client.');
769
+ },
770
+ set: function () {
771
+ throw new Error('Cannot assign to a temporary client reference from a server module.');
772
+ }
773
+ };
774
+ function createTemporaryReference(id) {
775
+ var reference = Object.defineProperties(function () {
776
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
777
+ "Attempted to call a temporary Client Reference from the server but it is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component.");
778
+ }, {
779
+ $$typeof: {
780
+ value: TEMPORARY_REFERENCE_TAG
781
+ },
782
+ $$id: {
783
+ value: id
784
+ }
785
+ });
786
+ return new Proxy(reference, proxyHandlers);
563
787
  }
564
- function popProvider() {
565
- var prevSnapshot = currentActiveSnapshot;
566
788
 
567
- if (prevSnapshot === null) {
568
- throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
789
+ // ATTENTION
790
+ // When adding new symbols to this file,
791
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
792
+ // The Symbol used to tag the ReactElement-like types.
793
+ var REACT_ELEMENT_TYPE = Symbol.for('react.element');
794
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
795
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
796
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
797
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
798
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
799
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
800
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
801
+ var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
802
+ var REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
803
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
804
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
805
+ function getIteratorFn(maybeIterable) {
806
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
807
+ return null;
569
808
  }
570
809
 
571
- {
572
- var value = prevSnapshot.parentValue;
810
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
573
811
 
574
- if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
575
- prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
576
- } else {
577
- prevSnapshot.context._currentValue = value;
578
- }
812
+ if (typeof maybeIterator === 'function') {
813
+ return maybeIterator;
579
814
  }
580
815
 
581
- return currentActiveSnapshot = prevSnapshot.parent;
582
- }
583
- function getActiveContext() {
584
- return currentActiveSnapshot;
585
- }
586
- function readContext$1(context) {
587
- var value = context._currentValue ;
588
- return value;
816
+ return null;
589
817
  }
590
818
 
591
819
  // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
@@ -716,29 +944,13 @@ function prepareToUseHooksForComponent(prevThenableState) {
716
944
  thenableState = prevThenableState;
717
945
  }
718
946
  function getThenableStateAfterSuspending() {
719
- var state = thenableState;
947
+ // If you use() to Suspend this should always exist but if you throw a Promise instead,
948
+ // which is not really supported anymore, it will be empty. We use the empty set as a
949
+ // marker to know if this was a replay of the same component or first attempt.
950
+ var state = thenableState || createThenableState();
720
951
  thenableState = null;
721
952
  return state;
722
953
  }
723
-
724
- function readContext(context) {
725
- {
726
- if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) {
727
- if (isClientReference(context)) {
728
- error('Cannot read a Client Context from a Server Component.');
729
- } else {
730
- error('Only createServerContext is supported in Server Components.');
731
- }
732
- }
733
-
734
- if (currentRequest$1 === null) {
735
- error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
736
- }
737
- }
738
-
739
- return readContext$1(context);
740
- }
741
-
742
954
  var HooksDispatcher = {
743
955
  useMemo: function (nextCreate) {
744
956
  return nextCreate();
@@ -749,8 +961,8 @@ var HooksDispatcher = {
749
961
  useDebugValue: function () {},
750
962
  useDeferredValue: unsupportedHook,
751
963
  useTransition: unsupportedHook,
752
- readContext: readContext,
753
- useContext: readContext,
964
+ readContext: unsupportedContext,
965
+ useContext: unsupportedContext,
754
966
  useReducer: unsupportedHook,
755
967
  useRef: unsupportedHook,
756
968
  useState: unsupportedHook,
@@ -759,7 +971,6 @@ var HooksDispatcher = {
759
971
  useImperativeHandle: unsupportedHook,
760
972
  useEffect: unsupportedHook,
761
973
  useId: useId,
762
- useMutableSource: unsupportedHook,
763
974
  useSyncExternalStore: unsupportedHook,
764
975
  useCacheRefresh: function () {
765
976
  return unsupportedRefresh;
@@ -784,6 +995,10 @@ function unsupportedRefresh() {
784
995
  throw new Error('Refreshing the cache is not supported in Server Components.');
785
996
  }
786
997
 
998
+ function unsupportedContext() {
999
+ throw new Error('Cannot read a Client Context from a Server Component.');
1000
+ }
1001
+
787
1002
  function useId() {
788
1003
  if (currentRequest$1 === null) {
789
1004
  throw new Error('useId can only be used while React is rendering');
@@ -809,20 +1024,22 @@ function use(usable) {
809
1024
  }
810
1025
 
811
1026
  return trackUsedThenable(thenableState, thenable, index);
812
- } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
813
- var context = usable;
814
- return readContext(context);
1027
+ } else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
1028
+ unsupportedContext();
815
1029
  }
816
1030
  }
817
1031
 
818
- {
819
- if (isClientReference(usable)) {
820
- error('Cannot use() an already resolved Client Reference.');
1032
+ if (isClientReference(usable)) {
1033
+ if (usable.value != null && usable.value.$$typeof === REACT_CONTEXT_TYPE) {
1034
+ // Show a more specific message since it's a common mistake.
1035
+ throw new Error('Cannot read a Client Context from a Server Component.');
1036
+ } else {
1037
+ throw new Error('Cannot use() an already resolved Client Reference.');
821
1038
  }
822
- } // eslint-disable-next-line react-internal/safe-string-coercion
823
-
824
-
825
- throw new Error('An unsupported type was passed to use(): ' + String(usable));
1039
+ } else {
1040
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
1041
+ 'An unsupported type was passed to use(): ' + String(usable));
1042
+ }
826
1043
  }
827
1044
 
828
1045
  function createSignal() {
@@ -871,6 +1088,8 @@ function isArray(a) {
871
1088
  return isArrayImpl(a);
872
1089
  }
873
1090
 
1091
+ var getPrototypeOf = Object.getPrototypeOf;
1092
+
874
1093
  // in case they error.
875
1094
 
876
1095
  var jsxPropsParents = new WeakMap();
@@ -889,7 +1108,7 @@ function isObjectPrototype(object) {
889
1108
  // still just a plain simple object.
890
1109
 
891
1110
 
892
- if (Object.getPrototypeOf(object)) {
1111
+ if (getPrototypeOf(object)) {
893
1112
  return false;
894
1113
  }
895
1114
 
@@ -905,7 +1124,7 @@ function isObjectPrototype(object) {
905
1124
  }
906
1125
 
907
1126
  function isSimpleObject(object) {
908
- if (!isObjectPrototype(Object.getPrototypeOf(object))) {
1127
+ if (!isObjectPrototype(getPrototypeOf(object))) {
909
1128
  return false;
910
1129
  }
911
1130
 
@@ -958,6 +1177,10 @@ function describeValueForErrorMessage(value) {
958
1177
  return '[...]';
959
1178
  }
960
1179
 
1180
+ if (value !== null && value.$$typeof === CLIENT_REFERENCE_TAG) {
1181
+ return describeClientReference();
1182
+ }
1183
+
961
1184
  var name = objectName(value);
962
1185
 
963
1186
  if (name === 'Object') {
@@ -968,7 +1191,15 @@ function describeValueForErrorMessage(value) {
968
1191
  }
969
1192
 
970
1193
  case 'function':
971
- return 'function';
1194
+ {
1195
+ if (value.$$typeof === CLIENT_REFERENCE_TAG) {
1196
+ return describeClientReference();
1197
+ }
1198
+
1199
+ var _name = value.displayName || value.name;
1200
+
1201
+ return _name ? 'function ' + _name : 'function';
1202
+ }
972
1203
 
973
1204
  default:
974
1205
  // eslint-disable-next-line react-internal/safe-string-coercion
@@ -1014,6 +1245,12 @@ function describeElementType(type) {
1014
1245
  return '';
1015
1246
  }
1016
1247
 
1248
+ var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
1249
+
1250
+ function describeClientReference(ref) {
1251
+ return 'client';
1252
+ }
1253
+
1017
1254
  function describeObjectForErrorMessage(objectOrArray, expandedName) {
1018
1255
  var objKind = objectName(objectOrArray);
1019
1256
 
@@ -1039,7 +1276,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1039
1276
  if (typeof value === 'string') {
1040
1277
  substr = value;
1041
1278
  } else if (typeof value === 'object' && value !== null) {
1042
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1043
1279
  substr = '{' + describeObjectForErrorMessage(value) + '}';
1044
1280
  } else {
1045
1281
  substr = '{' + describeValueForErrorMessage(value) + '}';
@@ -1072,7 +1308,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1072
1308
  var _substr = void 0;
1073
1309
 
1074
1310
  if (typeof _value === 'object' && _value !== null) {
1075
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1076
1311
  _substr = describeObjectForErrorMessage(_value);
1077
1312
  } else {
1078
1313
  _substr = describeValueForErrorMessage(_value);
@@ -1094,6 +1329,8 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1094
1329
  } else {
1095
1330
  if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) {
1096
1331
  str = '<' + describeElementType(objectOrArray.type) + '/>';
1332
+ } else if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) {
1333
+ return describeClientReference();
1097
1334
  } else if (jsxPropsParents.has(objectOrArray)) {
1098
1335
  // Print JSX
1099
1336
  var _type = jsxPropsParents.get(objectOrArray);
@@ -1111,7 +1348,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1111
1348
  var _substr2 = void 0;
1112
1349
 
1113
1350
  if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) {
1114
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1115
1351
  _substr2 = describeObjectForErrorMessage(_value2);
1116
1352
  } else {
1117
1353
  _substr2 = describeValueForErrorMessage(_value2);
@@ -1145,20 +1381,19 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1145
1381
  str += ', ';
1146
1382
  }
1147
1383
 
1148
- var _name = _names[_i3];
1149
- str += describeKeyForErrorMessage(_name) + ': ';
1150
- var _value3 = _object[_name];
1384
+ var _name2 = _names[_i3];
1385
+ str += describeKeyForErrorMessage(_name2) + ': ';
1386
+ var _value3 = _object[_name2];
1151
1387
 
1152
1388
  var _substr3 = void 0;
1153
1389
 
1154
1390
  if (typeof _value3 === 'object' && _value3 !== null) {
1155
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1156
1391
  _substr3 = describeObjectForErrorMessage(_value3);
1157
1392
  } else {
1158
1393
  _substr3 = describeValueForErrorMessage(_value3);
1159
1394
  }
1160
1395
 
1161
- if (_name === expandedName) {
1396
+ if (_name2 === expandedName) {
1162
1397
  start = str.length;
1163
1398
  length = _substr3.length;
1164
1399
  str += _substr3;
@@ -1185,41 +1420,44 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1185
1420
  return '\n ' + str;
1186
1421
  }
1187
1422
 
1188
- var ContextRegistry = ReactSharedInternals.ContextRegistry;
1189
- function getOrCreateServerContext(globalName) {
1190
- if (!ContextRegistry[globalName]) {
1191
- ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value
1192
- REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED);
1193
- }
1423
+ var ReactSharedServerInternals = // $FlowFixMe: It's defined in the one we resolve to.
1424
+ React.__SECRET_SERVER_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1194
1425
 
1195
- return ContextRegistry[globalName];
1426
+ if (!ReactSharedServerInternals) {
1427
+ throw new Error('The "react" package in this environment is not configured correctly. ' + 'The "react-server" condition must be enabled in any environment that ' + 'runs React Server Components.');
1196
1428
  }
1197
1429
 
1430
+ var ObjectPrototype = Object.prototype;
1431
+ var stringify = JSON.stringify; // Serializable values
1198
1432
  // Thenable<ReactClientValue>
1199
1433
 
1200
1434
  var PENDING$1 = 0;
1201
1435
  var COMPLETED = 1;
1202
1436
  var ABORTED = 3;
1203
1437
  var ERRORED$1 = 4;
1438
+ var ReactCurrentCache = ReactSharedServerInternals.ReactCurrentCache;
1204
1439
  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1205
- var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache;
1206
1440
 
1207
1441
  function defaultErrorHandler(error) {
1208
1442
  console['error'](error); // Don't transform to our wrapper
1209
1443
  }
1210
1444
 
1445
+ function defaultPostponeHandler(reason) {// Noop
1446
+ }
1447
+
1211
1448
  var OPEN = 0;
1212
1449
  var CLOSING = 1;
1213
1450
  var CLOSED = 2;
1214
- function createRequest(model, bundlerConfig, onError, context, identifierPrefix) {
1451
+ function createRequest(model, bundlerConfig, onError, identifierPrefix, onPostpone, environmentName) {
1215
1452
  if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) {
1216
1453
  throw new Error('Currently React only supports one RSC renderer at a time.');
1217
1454
  }
1218
1455
 
1219
- prepareHostDispatcher();
1220
1456
  ReactCurrentCache.current = DefaultCacheDispatcher;
1221
1457
  var abortSet = new Set();
1222
1458
  var pingedTasks = [];
1459
+ var cleanupQueue = [];
1460
+
1223
1461
  var hints = createHints();
1224
1462
  var request = {
1225
1463
  status: OPEN,
@@ -1235,23 +1473,24 @@ function createRequest(model, bundlerConfig, onError, context, identifierPrefix)
1235
1473
  pingedTasks: pingedTasks,
1236
1474
  completedImportChunks: [],
1237
1475
  completedHintChunks: [],
1238
- completedJSONChunks: [],
1476
+ completedRegularChunks: [],
1239
1477
  completedErrorChunks: [],
1240
1478
  writtenSymbols: new Map(),
1241
1479
  writtenClientReferences: new Map(),
1242
1480
  writtenServerReferences: new Map(),
1243
- writtenProviders: new Map(),
1481
+ writtenObjects: new WeakMap(),
1244
1482
  identifierPrefix: identifierPrefix || '',
1245
1483
  identifierCount: 1,
1484
+ taintCleanupQueue: cleanupQueue,
1246
1485
  onError: onError === undefined ? defaultErrorHandler : onError,
1247
- // $FlowFixMe[missing-this-annot]
1248
- toJSON: function (key, value) {
1249
- return resolveModelToJSON(request, this, key, value);
1250
- }
1486
+ onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone
1251
1487
  };
1252
- request.pendingChunks++;
1253
- var rootContext = createRootContext(context);
1254
- var rootTask = createTask(request, model, rootContext, abortSet);
1488
+
1489
+ {
1490
+ request.environmentName = environmentName === undefined ? 'Server' : environmentName;
1491
+ }
1492
+
1493
+ var rootTask = createTask(request, model, null, false, abortSet);
1255
1494
  pingedTasks.push(rootTask);
1256
1495
  return request;
1257
1496
  }
@@ -1267,15 +1506,18 @@ function resolveRequest() {
1267
1506
  return null;
1268
1507
  }
1269
1508
 
1270
- function createRootContext(reqContext) {
1271
- return importServerContexts(reqContext);
1272
- }
1509
+ function serializeThenable(request, task, thenable) {
1510
+ var newTask = createTask(request, null, task.keyPath, // the server component sequence continues through Promise-as-a-child.
1511
+ task.implicitSlot, request.abortableTasks);
1273
1512
 
1274
- var POP = {};
1513
+ {
1514
+ // If this came from Flight, forward any debug info into this new row.
1515
+ var debugInfo = thenable._debugInfo;
1275
1516
 
1276
- function serializeThenable(request, thenable) {
1277
- request.pendingChunks++;
1278
- var newTask = createTask(request, null, getActiveContext(), request.abortableTasks);
1517
+ if (debugInfo) {
1518
+ forwardDebugInfo(request, newTask.id, debugInfo);
1519
+ }
1520
+ }
1279
1521
 
1280
1522
  switch (thenable.status) {
1281
1523
  case 'fulfilled':
@@ -1289,14 +1531,10 @@ function serializeThenable(request, thenable) {
1289
1531
  case 'rejected':
1290
1532
  {
1291
1533
  var x = thenable.reason;
1292
- var digest = logRecoverableError(request, x);
1293
1534
 
1294
1535
  {
1295
- var _getErrorMessageAndSt = getErrorMessageAndStackDev(x),
1296
- message = _getErrorMessageAndSt.message,
1297
- stack = _getErrorMessageAndSt.stack;
1298
-
1299
- emitErrorChunkDev(request, newTask.id, digest, message, stack);
1536
+ var digest = logRecoverableError(request, x);
1537
+ emitErrorChunk(request, newTask.id, digest, x);
1300
1538
  }
1301
1539
 
1302
1540
  return newTask.id;
@@ -1334,18 +1572,16 @@ function serializeThenable(request, thenable) {
1334
1572
  newTask.model = value;
1335
1573
  pingTask(request, newTask);
1336
1574
  }, function (reason) {
1337
- newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled
1338
-
1339
- var digest = logRecoverableError(request, reason);
1340
-
1341
1575
  {
1342
- var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason),
1343
- _message = _getErrorMessageAndSt2.message,
1344
- _stack = _getErrorMessageAndSt2.stack;
1576
+ newTask.status = ERRORED$1;
1577
+
1578
+ var _digest = logRecoverableError(request, reason);
1345
1579
 
1346
- emitErrorChunkDev(request, newTask.id, digest, _message, _stack);
1580
+ emitErrorChunk(request, newTask.id, _digest, reason);
1347
1581
  }
1348
1582
 
1583
+ request.abortableTasks.delete(newTask);
1584
+
1349
1585
  if (request.destination !== null) {
1350
1586
  flushCompletedChunks(request, request.destination);
1351
1587
  }
@@ -1417,14 +1653,136 @@ function createLazyWrapperAroundWakeable(wakeable) {
1417
1653
  _payload: thenable,
1418
1654
  _init: readThenable
1419
1655
  };
1656
+
1657
+ {
1658
+ // If this came from React, transfer the debug info.
1659
+ lazyType._debugInfo = thenable._debugInfo || [];
1660
+ }
1661
+
1420
1662
  return lazyType;
1421
1663
  }
1422
1664
 
1423
- function attemptResolveElement(request, type, key, ref, props, prevThenableState) {
1665
+ function renderFunctionComponent(request, task, key, Component, props) {
1666
+ // Reset the task's thenable state before continuing, so that if a later
1667
+ // component suspends we can reuse the same task object. If the same
1668
+ // component suspends again, the thenable state will be restored.
1669
+ var prevThenableState = task.thenableState;
1670
+ task.thenableState = null;
1671
+
1672
+ {
1673
+ if (debugID === null) {
1674
+ // We don't have a chunk to assign debug info. We need to outline this
1675
+ // component to assign it an ID.
1676
+ return outlineTask(request, task);
1677
+ } else if (prevThenableState !== null) ; else {
1678
+ // This is a new component in the same task so we can emit more debug info.
1679
+ var componentName = Component.displayName || Component.name || '';
1680
+ request.pendingChunks++;
1681
+ emitDebugChunk(request, debugID, {
1682
+ name: componentName,
1683
+ env: request.environmentName
1684
+ });
1685
+ }
1686
+ }
1687
+
1688
+ prepareToUseHooksForComponent(prevThenableState); // The secondArg is always undefined in Server Components since refs error early.
1689
+
1690
+ var secondArg = undefined;
1691
+ var result = Component(props, secondArg);
1692
+
1693
+ if (typeof result === 'object' && result !== null && typeof result.then === 'function') {
1694
+ // When the return value is in children position we can resolve it immediately,
1695
+ // to its value without a wrapper if it's synchronously available.
1696
+ var thenable = result;
1697
+
1698
+ if (thenable.status === 'fulfilled') {
1699
+ return thenable.value;
1700
+ } // TODO: Once we accept Promises as children on the client, we can just return
1701
+ // the thenable here.
1702
+
1703
+
1704
+ result = createLazyWrapperAroundWakeable(result);
1705
+ } // Track this element's key on the Server Component on the keyPath context..
1706
+
1707
+
1708
+ var prevKeyPath = task.keyPath;
1709
+ var prevImplicitSlot = task.implicitSlot;
1710
+
1711
+ if (key !== null) {
1712
+ // Append the key to the path. Technically a null key should really add the child
1713
+ // index. We don't do that to hold the payload small and implementation simple.
1714
+ task.keyPath = prevKeyPath === null ? key : prevKeyPath + ',' + key;
1715
+ } else if (prevKeyPath === null) {
1716
+ // This sequence of Server Components has no keys. This means that it was rendered
1717
+ // in a slot that needs to assign an implicit key. Even if children below have
1718
+ // explicit keys, they should not be used for the outer most key since it might
1719
+ // collide with other slots in that set.
1720
+ task.implicitSlot = true;
1721
+ }
1722
+
1723
+ var json = renderModelDestructive(request, task, emptyRoot, '', result);
1724
+ task.keyPath = prevKeyPath;
1725
+ task.implicitSlot = prevImplicitSlot;
1726
+ return json;
1727
+ }
1728
+
1729
+ function renderFragment(request, task, children) {
1730
+ {
1731
+ var debugInfo = children._debugInfo;
1732
+
1733
+ if (debugInfo) {
1734
+ // If this came from Flight, forward any debug info into this new row.
1735
+ if (debugID === null) {
1736
+ // We don't have a chunk to assign debug info. We need to outline this
1737
+ // component to assign it an ID.
1738
+ return outlineTask(request, task);
1739
+ } else {
1740
+ // Forward any debug info we have the first time we see it.
1741
+ // We do this after init so that we have received all the debug info
1742
+ // from the server by the time we emit it.
1743
+ forwardDebugInfo(request, debugID, debugInfo);
1744
+ }
1745
+ }
1746
+ }
1747
+
1748
+ {
1749
+ return children;
1750
+ }
1751
+ }
1752
+
1753
+ function renderClientElement(task, type, key, props) {
1754
+ {
1755
+ return [REACT_ELEMENT_TYPE, type, key, props];
1756
+ } // We prepend the terminal client element that actually gets serialized with
1757
+ } // The chunk ID we're currently rendering that we can assign debug data to.
1758
+
1759
+
1760
+ var debugID = null;
1761
+
1762
+ function outlineTask(request, task) {
1763
+ var newTask = createTask(request, task.model, // the currently rendering element
1764
+ task.keyPath, // unlike outlineModel this one carries along context
1765
+ task.implicitSlot, request.abortableTasks);
1766
+ retryTask(request, newTask);
1767
+
1768
+ if (newTask.status === COMPLETED) {
1769
+ // We completed synchronously so we can refer to this by reference. This
1770
+ // makes it behaves the same as prod during deserialization.
1771
+ return serializeByValueID(newTask.id);
1772
+ } // This didn't complete synchronously so it wouldn't have even if we didn't
1773
+ // outline it, so this would reduce to a lazy reference even in prod.
1774
+
1775
+
1776
+ return serializeLazyID(newTask.id);
1777
+ }
1778
+
1779
+ function renderElement(request, task, type, key, ref, props) {
1424
1780
  if (ref !== null && ref !== undefined) {
1425
1781
  // When the ref moves to the regular props object this will implicitly
1426
1782
  // throw for functions. We could probably relax it to a DEV warning for other
1427
1783
  // cases.
1784
+ // TODO: `ref` is now just a prop when `enableRefAsProp` is on. Should we
1785
+ // do what the above comment says?
1428
1786
  throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
1429
1787
  }
1430
1788
 
@@ -1437,49 +1795,38 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1437
1795
  }
1438
1796
 
1439
1797
  if (typeof type === 'function') {
1440
- if (isClientReference(type)) {
1798
+ if (isClientReference(type) || isTemporaryReference(type)) {
1441
1799
  // This is a reference to a Client Component.
1442
- return [REACT_ELEMENT_TYPE, type, key, props];
1443
- } // This is a server-side component.
1444
-
1445
-
1446
- prepareToUseHooksForComponent(prevThenableState);
1447
- var result = type(props);
1448
-
1449
- if (typeof result === 'object' && result !== null && typeof result.then === 'function') {
1450
- // When the return value is in children position we can resolve it immediately,
1451
- // to its value without a wrapper if it's synchronously available.
1452
- var thenable = result;
1800
+ return renderClientElement(task, type, key, props);
1801
+ } // This is a Server Component.
1453
1802
 
1454
- if (thenable.status === 'fulfilled') {
1455
- return thenable.value;
1456
- } // TODO: Once we accept Promises as children on the client, we can just return
1457
- // the thenable here.
1458
1803
 
1459
-
1460
- return createLazyWrapperAroundWakeable(result);
1461
- }
1462
-
1463
- return result;
1804
+ return renderFunctionComponent(request, task, key, type, props);
1464
1805
  } else if (typeof type === 'string') {
1465
1806
  // This is a host element. E.g. HTML.
1466
- return [REACT_ELEMENT_TYPE, type, key, props];
1807
+ return renderClientElement(task, type, key, props);
1467
1808
  } else if (typeof type === 'symbol') {
1468
- if (type === REACT_FRAGMENT_TYPE) {
1809
+ if (type === REACT_FRAGMENT_TYPE && key === null) {
1469
1810
  // For key-less fragments, we add a small optimization to avoid serializing
1470
1811
  // it as a wrapper.
1471
- // TODO: If a key is specified, we should propagate its key to any children.
1472
- // Same as if a Server Component has a key.
1473
- return props.children;
1812
+ var prevImplicitSlot = task.implicitSlot;
1813
+
1814
+ if (task.keyPath === null) {
1815
+ task.implicitSlot = true;
1816
+ }
1817
+
1818
+ var json = renderModelDestructive(request, task, emptyRoot, '', props.children);
1819
+ task.implicitSlot = prevImplicitSlot;
1820
+ return json;
1474
1821
  } // This might be a built-in React component. We'll let the client decide.
1475
1822
  // Any built-in works as long as its props are serializable.
1476
1823
 
1477
1824
 
1478
- return [REACT_ELEMENT_TYPE, type, key, props];
1825
+ return renderClientElement(task, type, key, props);
1479
1826
  } else if (type != null && typeof type === 'object') {
1480
1827
  if (isClientReference(type)) {
1481
1828
  // This is a reference to a Client Component.
1482
- return [REACT_ELEMENT_TYPE, type, key, props];
1829
+ return renderClientElement(task, type, key, props);
1483
1830
  }
1484
1831
 
1485
1832
  switch (type.$$typeof) {
@@ -1488,45 +1835,17 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1488
1835
  var payload = type._payload;
1489
1836
  var init = type._init;
1490
1837
  var wrappedType = init(payload);
1491
- return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState);
1838
+ return renderElement(request, task, wrappedType, key, ref, props);
1492
1839
  }
1493
1840
 
1494
1841
  case REACT_FORWARD_REF_TYPE:
1495
1842
  {
1496
- var render = type.render;
1497
- prepareToUseHooksForComponent(prevThenableState);
1498
- return render(props, undefined);
1843
+ return renderFunctionComponent(request, task, key, type.render, props);
1499
1844
  }
1500
1845
 
1501
1846
  case REACT_MEMO_TYPE:
1502
1847
  {
1503
- return attemptResolveElement(request, type.type, key, ref, props, prevThenableState);
1504
- }
1505
-
1506
- case REACT_PROVIDER_TYPE:
1507
- {
1508
- pushProvider(type._context, props.value);
1509
-
1510
- {
1511
- var extraKeys = Object.keys(props).filter(function (value) {
1512
- if (value === 'children' || value === 'value') {
1513
- return false;
1514
- }
1515
-
1516
- return true;
1517
- });
1518
-
1519
- if (extraKeys.length !== 0) {
1520
- error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys));
1521
- }
1522
- }
1523
-
1524
- return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider.
1525
- {
1526
- value: props.value,
1527
- children: props.children,
1528
- __pop: POP
1529
- }];
1848
+ return renderElement(request, task, type.type, key, ref, props);
1530
1849
  }
1531
1850
  }
1532
1851
  }
@@ -1546,16 +1865,51 @@ function pingTask(request, task) {
1546
1865
  }
1547
1866
  }
1548
1867
 
1549
- function createTask(request, model, context, abortSet) {
1868
+ function createTask(request, model, keyPath, implicitSlot, abortSet) {
1869
+ request.pendingChunks++;
1550
1870
  var id = request.nextChunkId++;
1871
+
1872
+ if (typeof model === 'object' && model !== null) {
1873
+ // If we're about to write this into a new task we can assign it an ID early so that
1874
+ // any other references can refer to the value we're about to write.
1875
+ {
1876
+ request.writtenObjects.set(model, id);
1877
+ }
1878
+ }
1879
+
1551
1880
  var task = {
1552
1881
  id: id,
1553
1882
  status: PENDING$1,
1554
1883
  model: model,
1555
- context: context,
1884
+ keyPath: keyPath,
1885
+ implicitSlot: implicitSlot,
1556
1886
  ping: function () {
1557
1887
  return pingTask(request, task);
1558
1888
  },
1889
+ toJSON: function (parentPropertyName, value) {
1890
+ var parent = this; // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
1891
+
1892
+ {
1893
+ // $FlowFixMe[incompatible-use]
1894
+ var originalValue = parent[parentPropertyName];
1895
+
1896
+ if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
1897
+ if (objectName(originalValue) !== 'Object') {
1898
+ var jsxParentType = jsxChildrenParents.get(parent);
1899
+
1900
+ if (typeof jsxParentType === 'string') {
1901
+ error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
1902
+ } else {
1903
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
1904
+ }
1905
+ } else {
1906
+ error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, parentPropertyName));
1907
+ }
1908
+ }
1909
+ }
1910
+
1911
+ return renderModel(request, task, parent, parentPropertyName, value);
1912
+ },
1559
1913
  thenableState: null
1560
1914
  };
1561
1915
  abortSet.add(task);
@@ -1578,12 +1932,12 @@ function serializeServerReferenceID(id) {
1578
1932
  return '$F' + id.toString(16);
1579
1933
  }
1580
1934
 
1581
- function serializeSymbolReference(name) {
1582
- return '$S' + name;
1935
+ function serializeTemporaryReferenceID(id) {
1936
+ return '$T' + id;
1583
1937
  }
1584
1938
 
1585
- function serializeProviderReference(name) {
1586
- return '$P' + name;
1939
+ function serializeSymbolReference(name) {
1940
+ return '$S' + name;
1587
1941
  }
1588
1942
 
1589
1943
  function serializeNumber(number) {
@@ -1618,13 +1972,23 @@ function serializeBigInt(n) {
1618
1972
  return '$n' + n.toString(10);
1619
1973
  }
1620
1974
 
1621
- function serializeClientReference(request, parent, key, clientReference) {
1975
+ function serializeRowHeader(tag, id) {
1976
+ return id.toString(16) + ':' + tag;
1977
+ }
1978
+
1979
+ function encodeReferenceChunk(request, id, reference) {
1980
+ var json = stringify(reference);
1981
+ var row = id.toString(16) + ':' + json + '\n';
1982
+ return stringToChunk(row);
1983
+ }
1984
+
1985
+ function serializeClientReference(request, parent, parentPropertyName, clientReference) {
1622
1986
  var clientReferenceKey = getClientReferenceKey(clientReference);
1623
1987
  var writtenClientReferences = request.writtenClientReferences;
1624
1988
  var existingId = writtenClientReferences.get(clientReferenceKey);
1625
1989
 
1626
1990
  if (existingId !== undefined) {
1627
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
1991
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1628
1992
  // If we're encoding the "type" of an element, we can refer
1629
1993
  // to that by a lazy reference instead of directly since React
1630
1994
  // knows how to deal with lazy values. This lets us suspend
@@ -1643,7 +2007,7 @@ function serializeClientReference(request, parent, key, clientReference) {
1643
2007
  emitImportChunk(request, importId, clientReferenceMetadata);
1644
2008
  writtenClientReferences.set(clientReferenceKey, importId);
1645
2009
 
1646
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
2010
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1647
2011
  // If we're encoding the "type" of an element, we can refer
1648
2012
  // to that by a lazy reference instead of directly since React
1649
2013
  // knows how to deal with lazy values. This lets us suspend
@@ -1657,20 +2021,20 @@ function serializeClientReference(request, parent, key, clientReference) {
1657
2021
  request.pendingChunks++;
1658
2022
  var errorId = request.nextChunkId++;
1659
2023
  var digest = logRecoverableError(request, x);
1660
-
1661
- {
1662
- var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x),
1663
- message = _getErrorMessageAndSt3.message,
1664
- stack = _getErrorMessageAndSt3.stack;
1665
-
1666
- emitErrorChunkDev(request, errorId, digest, message, stack);
1667
- }
1668
-
2024
+ emitErrorChunk(request, errorId, digest, x);
1669
2025
  return serializeByValueID(errorId);
1670
2026
  }
1671
2027
  }
1672
2028
 
1673
- function serializeServerReference(request, parent, key, serverReference) {
2029
+ function outlineModel(request, value) {
2030
+ var newTask = createTask(request, value, null, // The way we use outlining is for reusing an object.
2031
+ false, // It makes no sense for that use case to be contextual.
2032
+ request.abortableTasks);
2033
+ retryTask(request, newTask);
2034
+ return newTask.id;
2035
+ }
2036
+
2037
+ function serializeServerReference(request, serverReference) {
1674
2038
  var writtenServerReferences = request.writtenServerReferences;
1675
2039
  var existingId = writtenServerReferences.get(serverReference);
1676
2040
 
@@ -1683,15 +2047,69 @@ function serializeServerReference(request, parent, key, serverReference) {
1683
2047
  id: getServerReferenceId(request.bundlerConfig, serverReference),
1684
2048
  bound: bound ? Promise.resolve(bound) : null
1685
2049
  };
1686
- request.pendingChunks++;
1687
- var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend.
1688
-
1689
- var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata);
1690
- request.completedJSONChunks.push(processedChunk);
2050
+ var metadataId = outlineModel(request, serverReferenceMetadata);
1691
2051
  writtenServerReferences.set(serverReference, metadataId);
1692
2052
  return serializeServerReferenceID(metadataId);
1693
2053
  }
1694
2054
 
2055
+ function serializeTemporaryReference(request, temporaryReference) {
2056
+ var id = resolveTemporaryReferenceID(temporaryReference);
2057
+ return serializeTemporaryReferenceID(id);
2058
+ }
2059
+
2060
+ function serializeLargeTextString(request, text) {
2061
+ request.pendingChunks += 2;
2062
+ var textId = request.nextChunkId++;
2063
+ var textChunk = stringToChunk(text);
2064
+ var binaryLength = byteLengthOfChunk(textChunk);
2065
+ var row = textId.toString(16) + ':T' + binaryLength.toString(16) + ',';
2066
+ var headerChunk = stringToChunk(row);
2067
+ request.completedRegularChunks.push(headerChunk, textChunk);
2068
+ return serializeByValueID(textId);
2069
+ }
2070
+
2071
+ function serializeMap(request, map) {
2072
+ var entries = Array.from(map);
2073
+
2074
+ for (var i = 0; i < entries.length; i++) {
2075
+ var key = entries[i][0];
2076
+
2077
+ if (typeof key === 'object' && key !== null) {
2078
+ var writtenObjects = request.writtenObjects;
2079
+ var existingId = writtenObjects.get(key);
2080
+
2081
+ if (existingId === undefined) {
2082
+ // Mark all object keys as seen so that they're always outlined.
2083
+ writtenObjects.set(key, -1);
2084
+ }
2085
+ }
2086
+ }
2087
+
2088
+ var id = outlineModel(request, entries);
2089
+ return '$Q' + id.toString(16);
2090
+ }
2091
+
2092
+ function serializeSet(request, set) {
2093
+ var entries = Array.from(set);
2094
+
2095
+ for (var i = 0; i < entries.length; i++) {
2096
+ var key = entries[i];
2097
+
2098
+ if (typeof key === 'object' && key !== null) {
2099
+ var writtenObjects = request.writtenObjects;
2100
+ var existingId = writtenObjects.get(key);
2101
+
2102
+ if (existingId === undefined) {
2103
+ // Mark all object keys as seen so that they're always outlined.
2104
+ writtenObjects.set(key, -1);
2105
+ }
2106
+ }
2107
+ }
2108
+
2109
+ var id = outlineModel(request, entries);
2110
+ return '$W' + id.toString(16);
2111
+ }
2112
+
1695
2113
  function escapeStringValue(value) {
1696
2114
  if (value[0] === '$') {
1697
2115
  // We need to escape $ prefixed strings since we use those to encode
@@ -1702,166 +2120,262 @@ function escapeStringValue(value) {
1702
2120
  }
1703
2121
  }
1704
2122
 
1705
- var insideContextProps = null;
1706
- var isInsideContextValue = false;
1707
- function resolveModelToJSON(request, parent, key, value) {
1708
- // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us
1709
- {
1710
- // $FlowFixMe[incompatible-use]
1711
- var originalValue = parent[key];
2123
+ var modelRoot = false;
1712
2124
 
1713
- if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
1714
- if (objectName(originalValue) !== 'Object') {
1715
- var jsxParentType = jsxChildrenParents.get(parent);
2125
+ function renderModel(request, task, parent, key, value) {
2126
+ var prevKeyPath = task.keyPath;
2127
+ var prevImplicitSlot = task.implicitSlot;
1716
2128
 
1717
- if (typeof jsxParentType === 'string') {
1718
- error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
1719
- } else {
1720
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
2129
+ try {
2130
+ return renderModelDestructive(request, task, parent, key, value);
2131
+ } catch (thrownValue) {
2132
+ var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
2133
+ // reasons, the rest of the Suspense implementation expects the thrown
2134
+ // value to be a thenable, because before `use` existed that was the
2135
+ // (unstable) API for suspending. This implementation detail can change
2136
+ // later, once we deprecate the old API in favor of `use`.
2137
+ getSuspendedThenable() : thrownValue; // If the suspended/errored value was an element or lazy it can be reduced
2138
+ // to a lazy reference, so that it doesn't error the parent.
2139
+
2140
+ var model = task.model;
2141
+ var wasReactNode = typeof model === 'object' && model !== null && (model.$$typeof === REACT_ELEMENT_TYPE || model.$$typeof === REACT_LAZY_TYPE);
2142
+
2143
+ if (typeof x === 'object' && x !== null) {
2144
+ // $FlowFixMe[method-unbinding]
2145
+ if (typeof x.then === 'function') {
2146
+ // Something suspended, we'll need to create a new task and resolve it later.
2147
+ var newTask = createTask(request, task.model, task.keyPath, task.implicitSlot, request.abortableTasks);
2148
+ var ping = newTask.ping;
2149
+ x.then(ping, ping);
2150
+ newTask.thenableState = getThenableStateAfterSuspending(); // Restore the context. We assume that this will be restored by the inner
2151
+ // functions in case nothing throws so we don't use "finally" here.
2152
+
2153
+ task.keyPath = prevKeyPath;
2154
+ task.implicitSlot = prevImplicitSlot;
2155
+
2156
+ if (wasReactNode) {
2157
+ return serializeLazyID(newTask.id);
1721
2158
  }
1722
- } else {
1723
- error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key));
2159
+
2160
+ return serializeByValueID(newTask.id);
1724
2161
  }
1725
- }
1726
- } // Special Symbols
2162
+ } // Restore the context. We assume that this will be restored by the inner
2163
+ // functions in case nothing throws so we don't use "finally" here.
2164
+
2165
+
2166
+ task.keyPath = prevKeyPath;
2167
+ task.implicitSlot = prevImplicitSlot;
2168
+
2169
+ if (wasReactNode) {
2170
+ // Something errored. We'll still send everything we have up until this point.
2171
+ // We'll replace this element with a lazy reference that throws on the client
2172
+ // once it gets rendered.
2173
+ request.pendingChunks++;
2174
+ var errorId = request.nextChunkId++;
2175
+ var digest = logRecoverableError(request, x);
2176
+ emitErrorChunk(request, errorId, digest, x);
2177
+ return serializeLazyID(errorId);
2178
+ } // Something errored but it was not in a React Node. There's no need to serialize
2179
+ // it by value because it'll just error the whole parent row anyway so we can
2180
+ // just stop any siblings and error the whole parent row.
1727
2181
 
1728
2182
 
1729
- switch (value) {
1730
- case REACT_ELEMENT_TYPE:
1731
- return '$';
2183
+ throw x;
1732
2184
  }
2185
+ }
1733
2186
 
1734
- {
1735
- if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') {
1736
- insideContextProps = value;
1737
- } else if (insideContextProps === parent && key === 'value') {
1738
- isInsideContextValue = true;
1739
- } else if (insideContextProps === parent && key === 'children') {
1740
- isInsideContextValue = false;
1741
- }
1742
- } // Resolve Server Components.
2187
+ function renderModelDestructive(request, task, parent, parentPropertyName, value) {
2188
+ // Set the currently rendering model
2189
+ task.model = value; // Special Symbol, that's very common.
1743
2190
 
2191
+ if (value === REACT_ELEMENT_TYPE) {
2192
+ return '$';
2193
+ }
1744
2194
 
1745
- while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) {
1746
- {
1747
- if (isInsideContextValue) {
1748
- error('React elements are not allowed in ServerContext');
1749
- }
1750
- }
2195
+ if (value === null) {
2196
+ return null;
2197
+ }
1751
2198
 
1752
- try {
1753
- switch (value.$$typeof) {
1754
- case REACT_ELEMENT_TYPE:
1755
- {
1756
- // TODO: Concatenate keys of parents onto children.
1757
- var element = value; // Attempt to render the Server Component.
2199
+ if (typeof value === 'object') {
2200
+ switch (value.$$typeof) {
2201
+ case REACT_ELEMENT_TYPE:
2202
+ {
2203
+ var _writtenObjects = request.writtenObjects;
2204
+
2205
+ var _existingId = _writtenObjects.get(value);
2206
+
2207
+ if (_existingId !== undefined) {
2208
+ if (modelRoot === value) {
2209
+ // This is the ID we're currently emitting so we need to write it
2210
+ // once but if we discover it again, we refer to it by id.
2211
+ modelRoot = null;
2212
+ } else if (_existingId === -1) {
2213
+ // Seen but not yet outlined.
2214
+ // TODO: If we throw here we can treat this as suspending which causes an outline
2215
+ // but that is able to reuse the same task if we're already in one but then that
2216
+ // will be a lazy future value rather than guaranteed to exist but maybe that's good.
2217
+ var newId = outlineModel(request, value);
2218
+ return serializeByValueID(newId);
2219
+ } else {
2220
+ // We've already emitted this as an outlined object, so we can refer to that by its
2221
+ // existing ID. TODO: We should use a lazy reference since, unlike plain objects,
2222
+ // elements might suspend so it might not have emitted yet even if we have the ID for
2223
+ // it. However, this creates an extra wrapper when it's not needed. We should really
2224
+ // detect whether this already was emitted and synchronously available. In that
2225
+ // case we can refer to it synchronously and only make it lazy otherwise.
2226
+ // We currently don't have a data structure that lets us see that though.
2227
+ return serializeByValueID(_existingId);
2228
+ }
2229
+ } else {
2230
+ // This is the first time we've seen this object. We may never see it again
2231
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2232
+ _writtenObjects.set(value, -1);
2233
+ }
2234
+
2235
+ var element = value;
1758
2236
 
1759
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null);
1760
- break;
2237
+ {
2238
+ var debugInfo = value._debugInfo;
2239
+
2240
+ if (debugInfo) {
2241
+ // If this came from Flight, forward any debug info into this new row.
2242
+ if (debugID === null) {
2243
+ // We don't have a chunk to assign debug info. We need to outline this
2244
+ // component to assign it an ID.
2245
+ return outlineTask(request, task);
2246
+ } else {
2247
+ // Forward any debug info we have the first time we see it.
2248
+ forwardDebugInfo(request, debugID, debugInfo);
2249
+ }
2250
+ }
1761
2251
  }
1762
2252
 
1763
- case REACT_LAZY_TYPE:
2253
+ var props = element.props;
2254
+ var ref;
2255
+
2256
+ {
2257
+ ref = element.ref;
2258
+ } // Attempt to render the Server Component.
2259
+
2260
+
2261
+ return renderElement(request, task, element.type, // $FlowFixMe[incompatible-call] the key of an element is null | string
2262
+ element.key, ref, props);
2263
+ }
2264
+
2265
+ case REACT_LAZY_TYPE:
2266
+ {
2267
+ // Reset the task's thenable state before continuing. If there was one, it was
2268
+ // from suspending the lazy before.
2269
+ task.thenableState = null;
2270
+ var lazy = value;
2271
+ var payload = lazy._payload;
2272
+ var init = lazy._init;
2273
+ var resolvedModel = init(payload);
2274
+
1764
2275
  {
1765
- var payload = value._payload;
1766
- var init = value._init;
1767
- value = init(payload);
1768
- break;
2276
+ var _debugInfo = lazy._debugInfo;
2277
+
2278
+ if (_debugInfo) {
2279
+ // If this came from Flight, forward any debug info into this new row.
2280
+ if (debugID === null) {
2281
+ // We don't have a chunk to assign debug info. We need to outline this
2282
+ // component to assign it an ID.
2283
+ return outlineTask(request, task);
2284
+ } else {
2285
+ // Forward any debug info we have the first time we see it.
2286
+ // We do this after init so that we have received all the debug info
2287
+ // from the server by the time we emit it.
2288
+ forwardDebugInfo(request, debugID, _debugInfo);
2289
+ }
2290
+ }
1769
2291
  }
1770
- }
1771
- } catch (thrownValue) {
1772
- var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
1773
- // reasons, the rest of the Suspense implementation expects the thrown
1774
- // value to be a thenable, because before `use` existed that was the
1775
- // (unstable) API for suspending. This implementation detail can change
1776
- // later, once we deprecate the old API in favor of `use`.
1777
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
1778
-
1779
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
1780
- // Something suspended, we'll need to create a new task and resolve it later.
1781
- request.pendingChunks++;
1782
- var newTask = createTask(request, value, getActiveContext(), request.abortableTasks);
1783
- var ping = newTask.ping;
1784
- x.then(ping, ping);
1785
- newTask.thenableState = getThenableStateAfterSuspending();
1786
- return serializeLazyID(newTask.id);
1787
- } else {
1788
- // Something errored. We'll still send everything we have up until this point.
1789
- // We'll replace this element with a lazy reference that throws on the client
1790
- // once it gets rendered.
1791
- request.pendingChunks++;
1792
- var errorId = request.nextChunkId++;
1793
- var digest = logRecoverableError(request, x);
1794
2292
 
1795
- {
1796
- var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x),
1797
- message = _getErrorMessageAndSt4.message,
1798
- stack = _getErrorMessageAndSt4.stack;
1799
-
1800
- emitErrorChunkDev(request, errorId, digest, message, stack);
2293
+ return renderModelDestructive(request, task, emptyRoot, '', resolvedModel);
1801
2294
  }
2295
+ }
1802
2296
 
1803
- return serializeLazyID(errorId);
1804
- }
2297
+ if (isClientReference(value)) {
2298
+ return serializeClientReference(request, parent, parentPropertyName, value);
1805
2299
  }
1806
- }
1807
2300
 
1808
- if (value === null) {
1809
- return null;
1810
- }
2301
+ var writtenObjects = request.writtenObjects;
2302
+ var existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
1811
2303
 
1812
- if (typeof value === 'object') {
1813
- if (isClientReference(value)) {
1814
- return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding]
1815
- } else if (typeof value.then === 'function') {
1816
- // We assume that any object with a .then property is a "Thenable" type,
2304
+ if (typeof value.then === 'function') {
2305
+ if (existingId !== undefined) {
2306
+ if (modelRoot === value) {
2307
+ // This is the ID we're currently emitting so we need to write it
2308
+ // once but if we discover it again, we refer to it by id.
2309
+ modelRoot = null;
2310
+ } else {
2311
+ // We've seen this promise before, so we can just refer to the same result.
2312
+ return serializePromiseID(existingId);
2313
+ }
2314
+ } // We assume that any object with a .then property is a "Thenable" type,
1817
2315
  // or a Promise type. Either of which can be represented by a Promise.
1818
- var promiseId = serializeThenable(request, value);
2316
+
2317
+
2318
+ var promiseId = serializeThenable(request, task, value);
2319
+ writtenObjects.set(value, promiseId);
1819
2320
  return serializePromiseID(promiseId);
1820
- } else if (value.$$typeof === REACT_PROVIDER_TYPE) {
1821
- var providerKey = value._context._globalName;
1822
- var writtenProviders = request.writtenProviders;
1823
- var providerId = writtenProviders.get(key);
1824
-
1825
- if (providerId === undefined) {
1826
- request.pendingChunks++;
1827
- providerId = request.nextChunkId++;
1828
- writtenProviders.set(providerKey, providerId);
1829
- emitProviderChunk(request, providerId, providerKey);
2321
+ }
2322
+
2323
+ if (existingId !== undefined) {
2324
+ if (modelRoot === value) {
2325
+ // This is the ID we're currently emitting so we need to write it
2326
+ // once but if we discover it again, we refer to it by id.
2327
+ modelRoot = null;
2328
+ } else if (existingId === -1) {
2329
+ // Seen but not yet outlined.
2330
+ var _newId = outlineModel(request, value);
2331
+
2332
+ return serializeByValueID(_newId);
2333
+ } else {
2334
+ // We've already emitted this as an outlined object, so we can
2335
+ // just refer to that by its existing ID.
2336
+ return serializeByValueID(existingId);
1830
2337
  }
2338
+ } else {
2339
+ // This is the first time we've seen this object. We may never see it again
2340
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2341
+ writtenObjects.set(value, -1);
2342
+ }
1831
2343
 
1832
- return serializeByValueID(providerId);
1833
- } else if (value === POP) {
1834
- popProvider();
2344
+ if (isArray(value)) {
2345
+ return renderFragment(request, task, value);
2346
+ }
1835
2347
 
1836
- {
1837
- insideContextProps = null;
1838
- isInsideContextValue = false;
1839
- }
2348
+ if (value instanceof Map) {
2349
+ return serializeMap(request, value);
2350
+ }
1840
2351
 
1841
- return undefined;
2352
+ if (value instanceof Set) {
2353
+ return serializeSet(request, value);
1842
2354
  }
1843
2355
 
1844
- if (!isArray(value)) {
1845
- var iteratorFn = getIteratorFn(value);
2356
+ var iteratorFn = getIteratorFn(value);
1846
2357
 
1847
- if (iteratorFn) {
1848
- return Array.from(value);
1849
- }
2358
+ if (iteratorFn) {
2359
+ return renderFragment(request, task, Array.from(value));
2360
+ } // Verify that this is a simple plain object.
2361
+
2362
+
2363
+ var proto = getPrototypeOf(value);
2364
+
2365
+ if (proto !== ObjectPrototype && (proto === null || getPrototypeOf(proto) !== null)) {
2366
+ throw new Error('Only plain objects, and a few built-ins, can be passed to Client Components ' + 'from Server Components. Classes or null prototypes are not supported.');
1850
2367
  }
1851
2368
 
1852
2369
  {
1853
- if (value !== null && !isArray(value)) {
1854
- // Verify that this is a simple plain object.
1855
- if (objectName(value) !== 'Object') {
1856
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key));
1857
- } else if (!isSimpleObject(value)) {
1858
- error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key));
1859
- } else if (Object.getOwnPropertySymbols) {
1860
- var symbols = Object.getOwnPropertySymbols(value);
1861
-
1862
- if (symbols.length > 0) {
1863
- error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key));
1864
- }
2370
+ if (objectName(value) !== 'Object') {
2371
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, parentPropertyName));
2372
+ } else if (!isSimpleObject(value)) {
2373
+ error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, parentPropertyName));
2374
+ } else if (Object.getOwnPropertySymbols) {
2375
+ var symbols = Object.getOwnPropertySymbols(value);
2376
+
2377
+ if (symbols.length > 0) {
2378
+ error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, parentPropertyName));
1865
2379
  }
1866
2380
  }
1867
2381
  } // $FlowFixMe[incompatible-return]
@@ -1871,17 +2385,25 @@ function resolveModelToJSON(request, parent, key, value) {
1871
2385
  }
1872
2386
 
1873
2387
  if (typeof value === 'string') {
1874
- // TODO: Maybe too clever. If we support URL there's no similar trick.
2388
+
2389
+
1875
2390
  if (value[value.length - 1] === 'Z') {
1876
2391
  // Possibly a Date, whose toJSON automatically calls toISOString
1877
2392
  // $FlowFixMe[incompatible-use]
1878
- var _originalValue = parent[key]; // $FlowFixMe[method-unbinding]
2393
+ var originalValue = parent[parentPropertyName];
1879
2394
 
1880
- if (_originalValue instanceof Date) {
2395
+ if (originalValue instanceof Date) {
1881
2396
  return serializeDateFromDateJSON(value);
1882
2397
  }
1883
2398
  }
1884
2399
 
2400
+ if (value.length >= 1024) {
2401
+ // For large strings, we encode them outside the JSON payload so that we
2402
+ // don't have to double encode and double parse the strings. This can also
2403
+ // be more compact in case the string has a lot of escaped characters.
2404
+ return serializeLargeTextString(request, value);
2405
+ }
2406
+
1885
2407
  return escapeStringValue(value);
1886
2408
  }
1887
2409
 
@@ -1899,26 +2421,34 @@ function resolveModelToJSON(request, parent, key, value) {
1899
2421
 
1900
2422
  if (typeof value === 'function') {
1901
2423
  if (isClientReference(value)) {
1902
- return serializeClientReference(request, parent, key, value);
2424
+ return serializeClientReference(request, parent, parentPropertyName, value);
1903
2425
  }
1904
2426
 
1905
2427
  if (isServerReference(value)) {
1906
- return serializeServerReference(request, parent, key, value);
2428
+ return serializeServerReference(request, value);
2429
+ }
2430
+
2431
+ if (isTemporaryReference(value)) {
2432
+ return serializeTemporaryReference(request, value);
1907
2433
  }
1908
2434
 
1909
- if (/^on[A-Z]/.test(key)) {
1910
- throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.');
2435
+ if (/^on[A-Z]/.test(parentPropertyName)) {
2436
+ throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, parentPropertyName) + '\nIf you need interactivity, consider converting part of this to a Client Component.');
2437
+ } else if ((jsxChildrenParents.has(parent) || jsxPropsParents.has(parent) && parentPropertyName === 'children')) {
2438
+ var componentName = value.displayName || value.name || 'Component';
2439
+ throw new Error('Functions are not valid as a child of Client Components. This may happen if ' + 'you return ' + componentName + ' instead of <' + componentName + ' /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + describeObjectForErrorMessage(parent, parentPropertyName));
1911
2440
  } else {
1912
- throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key));
2441
+ throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server". ' + 'Or maybe you meant to call this function rather than return it.' + describeObjectForErrorMessage(parent, parentPropertyName));
1913
2442
  }
1914
2443
  }
1915
2444
 
1916
2445
  if (typeof value === 'symbol') {
1917
2446
  var writtenSymbols = request.writtenSymbols;
1918
- var existingId = writtenSymbols.get(value);
1919
2447
 
1920
- if (existingId !== undefined) {
1921
- return serializeByValueID(existingId);
2448
+ var _existingId2 = writtenSymbols.get(value);
2449
+
2450
+ if (_existingId2 !== undefined) {
2451
+ return serializeByValueID(_existingId2);
1922
2452
  } // $FlowFixMe[incompatible-type] `description` might be undefined
1923
2453
 
1924
2454
 
@@ -1926,7 +2456,7 @@ function resolveModelToJSON(request, parent, key, value) {
1926
2456
 
1927
2457
  if (Symbol.for(name) !== value) {
1928
2458
  throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined
1929
- value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key));
2459
+ value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, parentPropertyName));
1930
2460
  }
1931
2461
 
1932
2462
  request.pendingChunks++;
@@ -1937,15 +2467,48 @@ function resolveModelToJSON(request, parent, key, value) {
1937
2467
  }
1938
2468
 
1939
2469
  if (typeof value === 'bigint') {
2470
+
1940
2471
  return serializeBigInt(value);
1941
2472
  }
1942
2473
 
1943
- throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key));
2474
+ throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName));
2475
+ }
2476
+
2477
+ function logPostpone(request, reason) {
2478
+ var prevRequest = currentRequest;
2479
+ currentRequest = null;
2480
+
2481
+ try {
2482
+ var onPostpone = request.onPostpone;
2483
+
2484
+ if (supportsRequestStorage) {
2485
+ // Exit the request context while running callbacks.
2486
+ requestStorage.run(undefined, onPostpone, reason);
2487
+ } else {
2488
+ onPostpone(reason);
2489
+ }
2490
+ } finally {
2491
+ currentRequest = prevRequest;
2492
+ }
1944
2493
  }
1945
2494
 
1946
2495
  function logRecoverableError(request, error) {
1947
- var onError = request.onError;
1948
- var errorDigest = onError(error);
2496
+ var prevRequest = currentRequest;
2497
+ currentRequest = null;
2498
+ var errorDigest;
2499
+
2500
+ try {
2501
+ var onError = request.onError;
2502
+
2503
+ if (supportsRequestStorage) {
2504
+ // Exit the request context while running callbacks.
2505
+ errorDigest = requestStorage.run(undefined, onError, error);
2506
+ } else {
2507
+ errorDigest = onError(error);
2508
+ }
2509
+ } finally {
2510
+ currentRequest = prevRequest;
2511
+ }
1949
2512
 
1950
2513
  if (errorDigest != null && typeof errorDigest !== 'string') {
1951
2514
  // eslint-disable-next-line react-internal/prod-error-codes
@@ -1955,7 +2518,45 @@ function logRecoverableError(request, error) {
1955
2518
  return errorDigest || '';
1956
2519
  }
1957
2520
 
1958
- function getErrorMessageAndStackDev(error) {
2521
+ function fatalError(request, error) {
2522
+
2523
+
2524
+ if (request.destination !== null) {
2525
+ request.status = CLOSED;
2526
+ closeWithError(request.destination, error);
2527
+ } else {
2528
+ request.status = CLOSING;
2529
+ request.fatalError = error;
2530
+ }
2531
+ }
2532
+
2533
+ function emitPostponeChunk(request, id, postponeInstance) {
2534
+ var row;
2535
+
2536
+ {
2537
+ var reason = '';
2538
+ var stack = '';
2539
+
2540
+ try {
2541
+ // eslint-disable-next-line react-internal/safe-string-coercion
2542
+ reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion
2543
+
2544
+ stack = String(postponeInstance.stack);
2545
+ } catch (x) {}
2546
+
2547
+ row = serializeRowHeader('P', id) + stringify({
2548
+ reason: reason,
2549
+ stack: stack
2550
+ }) + '\n';
2551
+ }
2552
+
2553
+ var processedChunk = stringToChunk(row);
2554
+ request.completedErrorChunks.push(processedChunk);
2555
+ }
2556
+
2557
+ function emitErrorChunk(request, id, digest, error) {
2558
+ var errorInfo;
2559
+
1959
2560
  {
1960
2561
  var message;
1961
2562
  var stack = '';
@@ -1966,101 +2567,123 @@ function getErrorMessageAndStackDev(error) {
1966
2567
  message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
1967
2568
 
1968
2569
  stack = String(error.stack);
2570
+ } else if (typeof error === 'object' && error !== null) {
2571
+ message = describeObjectForErrorMessage(error);
1969
2572
  } else {
1970
- message = 'Error: ' + error;
2573
+ // eslint-disable-next-line react-internal/safe-string-coercion
2574
+ message = String(error);
1971
2575
  }
1972
2576
  } catch (x) {
1973
2577
  message = 'An error occurred but serializing the error message failed.';
1974
2578
  }
1975
2579
 
1976
- return {
2580
+ errorInfo = {
2581
+ digest: digest,
1977
2582
  message: message,
1978
2583
  stack: stack
1979
2584
  };
1980
2585
  }
1981
- }
1982
-
1983
- function fatalError(request, error) {
1984
- // This is called outside error handling code such as if an error happens in React internals.
1985
- if (request.destination !== null) {
1986
- request.status = CLOSED;
1987
- closeWithError(request.destination, error);
1988
- } else {
1989
- request.status = CLOSING;
1990
- request.fatalError = error;
1991
- }
1992
- }
1993
-
1994
- function emitErrorChunkProd(request, id, digest) {
1995
- var processedChunk = processErrorChunkProd();
1996
- request.completedErrorChunks.push(processedChunk);
1997
- }
1998
2586
 
1999
- function emitErrorChunkDev(request, id, digest, message, stack) {
2000
- var processedChunk = processErrorChunkDev(request, id, digest, message, stack);
2587
+ var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
2588
+ var processedChunk = stringToChunk(row);
2001
2589
  request.completedErrorChunks.push(processedChunk);
2002
2590
  }
2003
2591
 
2004
2592
  function emitImportChunk(request, id, clientReferenceMetadata) {
2005
- var processedChunk = processImportChunk(request, id, clientReferenceMetadata);
2593
+ // $FlowFixMe[incompatible-type] stringify can return null
2594
+ var json = stringify(clientReferenceMetadata);
2595
+ var row = serializeRowHeader('I', id) + json + '\n';
2596
+ var processedChunk = stringToChunk(row);
2006
2597
  request.completedImportChunks.push(processedChunk);
2007
2598
  }
2008
2599
 
2009
2600
  function emitHintChunk(request, code, model) {
2010
- var processedChunk = processHintChunk(request, request.nextChunkId++, code, model);
2601
+ var json = stringify(model);
2602
+ var id = request.nextChunkId++;
2603
+ var row = serializeRowHeader('H' + code, id) + json + '\n';
2604
+ var processedChunk = stringToChunk(row);
2011
2605
  request.completedHintChunks.push(processedChunk);
2012
2606
  }
2013
2607
 
2014
2608
  function emitSymbolChunk(request, id, name) {
2015
2609
  var symbolReference = serializeSymbolReference(name);
2016
- var processedChunk = processReferenceChunk(request, id, symbolReference);
2610
+ var processedChunk = encodeReferenceChunk(request, id, symbolReference);
2017
2611
  request.completedImportChunks.push(processedChunk);
2018
2612
  }
2019
2613
 
2020
- function emitProviderChunk(request, id, contextName) {
2021
- var contextReference = serializeProviderReference(contextName);
2022
- var processedChunk = processReferenceChunk(request, id, contextReference);
2023
- request.completedJSONChunks.push(processedChunk);
2614
+ function emitModelChunk(request, id, json) {
2615
+ var row = id.toString(16) + ':' + json + '\n';
2616
+ var processedChunk = stringToChunk(row);
2617
+ request.completedRegularChunks.push(processedChunk);
2618
+ }
2619
+
2620
+ function emitDebugChunk(request, id, debugInfo) {
2621
+
2622
+
2623
+ var json = stringify(debugInfo);
2624
+ var row = serializeRowHeader('D', id) + json + '\n';
2625
+ var processedChunk = stringToChunk(row);
2626
+ request.completedRegularChunks.push(processedChunk);
2627
+ }
2628
+
2629
+ function forwardDebugInfo(request, id, debugInfo) {
2630
+ for (var i = 0; i < debugInfo.length; i++) {
2631
+ request.pendingChunks++;
2632
+ emitDebugChunk(request, id, debugInfo[i]);
2633
+ }
2024
2634
  }
2025
2635
 
2636
+ var emptyRoot = {};
2637
+
2026
2638
  function retryTask(request, task) {
2027
2639
  if (task.status !== PENDING$1) {
2028
2640
  // We completed this by other means before we had a chance to retry it.
2029
2641
  return;
2030
2642
  }
2031
2643
 
2032
- switchContext(task.context);
2644
+ var prevDebugID = debugID;
2033
2645
 
2034
2646
  try {
2035
- var value = task.model;
2036
-
2037
- if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2038
- // TODO: Concatenate keys of parents onto children.
2039
- var element = value; // When retrying a component, reuse the thenableState from the
2040
- // previous attempt.
2041
-
2042
- var prevThenableState = task.thenableState; // Attempt to render the Server Component.
2043
- // Doing this here lets us reuse this same task if the next component
2044
- // also suspends.
2045
-
2046
- task.model = value;
2047
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering
2048
- // using the same task, but we reset its thenable state before continuing.
2049
-
2050
- task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate
2051
- // from the render above because we don't need to reset the thenable state
2052
- // until the next time something suspends and retries.
2053
-
2054
- while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2055
- // TODO: Concatenate keys of parents onto children.
2056
- var nextElement = value;
2057
- task.model = value;
2058
- value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null);
2059
- }
2647
+ // Track the root so we know that we have to emit this object even though it
2648
+ // already has an ID. This is needed because we might see this object twice
2649
+ // in the same toJSON if it is cyclic.
2650
+ modelRoot = task.model;
2651
+
2652
+ if (true) {
2653
+ // Track the ID of the current task so we can assign debug info to this id.
2654
+ debugID = task.id;
2655
+ } // We call the destructive form that mutates this task. That way if something
2656
+ // suspends again, we can reuse the same task instead of spawning a new one.
2657
+
2658
+
2659
+ var resolvedModel = renderModelDestructive(request, task, emptyRoot, '', task.model);
2660
+
2661
+ if (true) {
2662
+ // We're now past rendering this task and future renders will spawn new tasks for their
2663
+ // debug info.
2664
+ debugID = null;
2665
+ } // Track the root again for the resolved object.
2666
+
2667
+
2668
+ modelRoot = resolvedModel; // The keyPath resets at any terminal child node.
2669
+
2670
+ task.keyPath = null;
2671
+ task.implicitSlot = false;
2672
+ var json;
2673
+
2674
+ if (typeof resolvedModel === 'object' && resolvedModel !== null) {
2675
+ // Object might contain unresolved values like additional elements.
2676
+ // This is simulating what the JSON loop would do if this was part of it.
2677
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2678
+ json = stringify(resolvedModel, task.toJSON);
2679
+ } else {
2680
+ // If the value is a string, it means it's a terminal value and we already escaped it
2681
+ // We don't need to escape it again so it's not passed the toJSON replacer.
2682
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2683
+ json = stringify(resolvedModel);
2060
2684
  }
2061
2685
 
2062
- var processedChunk = processModelChunk(request, task.id, value);
2063
- request.completedJSONChunks.push(processedChunk);
2686
+ emitModelChunk(request, task.id, json);
2064
2687
  request.abortableTasks.delete(task);
2065
2688
  task.status = COMPLETED;
2066
2689
  } catch (thrownValue) {
@@ -2069,27 +2692,27 @@ function retryTask(request, task) {
2069
2692
  // value to be a thenable, because before `use` existed that was the
2070
2693
  // (unstable) API for suspending. This implementation detail can change
2071
2694
  // later, once we deprecate the old API in favor of `use`.
2072
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
2073
-
2074
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
2075
- // Something suspended again, let's pick it back up later.
2076
- var ping = task.ping;
2077
- x.then(ping, ping);
2078
- task.thenableState = getThenableStateAfterSuspending();
2079
- return;
2080
- } else {
2081
- request.abortableTasks.delete(task);
2082
- task.status = ERRORED$1;
2083
- var digest = logRecoverableError(request, x);
2084
-
2085
- {
2086
- var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x),
2087
- message = _getErrorMessageAndSt5.message,
2088
- stack = _getErrorMessageAndSt5.stack;
2695
+ getSuspendedThenable() : thrownValue;
2089
2696
 
2090
- emitErrorChunkDev(request, task.id, digest, message, stack);
2697
+ if (typeof x === 'object' && x !== null) {
2698
+ // $FlowFixMe[method-unbinding]
2699
+ if (typeof x.then === 'function') {
2700
+ // Something suspended again, let's pick it back up later.
2701
+ var ping = task.ping;
2702
+ x.then(ping, ping);
2703
+ task.thenableState = getThenableStateAfterSuspending();
2704
+ return;
2091
2705
  }
2092
2706
  }
2707
+
2708
+ request.abortableTasks.delete(task);
2709
+ task.status = ERRORED$1;
2710
+ var digest = logRecoverableError(request, x);
2711
+ emitErrorChunk(request, task.id, digest, x);
2712
+ } finally {
2713
+ {
2714
+ debugID = prevDebugID;
2715
+ }
2093
2716
  }
2094
2717
  }
2095
2718
 
@@ -2127,7 +2750,7 @@ function abortTask(task, request, errorId) {
2127
2750
  // has a single value referencing the error.
2128
2751
 
2129
2752
  var ref = serializeByValueID(errorId);
2130
- var processedChunk = processReferenceChunk(request, task.id, ref);
2753
+ var processedChunk = encodeReferenceChunk(request, task.id, ref);
2131
2754
  request.completedErrorChunks.push(processedChunk);
2132
2755
  }
2133
2756
 
@@ -2171,12 +2794,12 @@ function flushCompletedChunks(request, destination) {
2171
2794
 
2172
2795
  hintChunks.splice(0, i); // Next comes model data.
2173
2796
 
2174
- var jsonChunks = request.completedJSONChunks;
2797
+ var regularChunks = request.completedRegularChunks;
2175
2798
  i = 0;
2176
2799
 
2177
- for (; i < jsonChunks.length; i++) {
2800
+ for (; i < regularChunks.length; i++) {
2178
2801
  request.pendingChunks--;
2179
- var _chunk2 = jsonChunks[i];
2802
+ var _chunk2 = regularChunks[i];
2180
2803
 
2181
2804
  var _keepWriting2 = writeChunkAndReturn(destination, _chunk2);
2182
2805
 
@@ -2187,7 +2810,7 @@ function flushCompletedChunks(request, destination) {
2187
2810
  }
2188
2811
  }
2189
2812
 
2190
- jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
2813
+ regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
2191
2814
  // any error messages and prioritize display of other parts of
2192
2815
  // the page.
2193
2816
 
@@ -2214,7 +2837,7 @@ function flushCompletedChunks(request, destination) {
2214
2837
  }
2215
2838
 
2216
2839
  if (request.pendingChunks === 0) {
2217
- // We're done.
2840
+
2218
2841
  close$1(destination);
2219
2842
  }
2220
2843
  }
@@ -2270,6 +2893,9 @@ function startFlowing(request, destination) {
2270
2893
  logRecoverableError(request, error);
2271
2894
  fatalError(request, error);
2272
2895
  }
2896
+ }
2897
+ function stopFlowing(request) {
2898
+ request.destination = null;
2273
2899
  } // This is called to early terminate a request. It creates an error at all pending tasks.
2274
2900
 
2275
2901
  function abort(request, reason) {
@@ -2279,17 +2905,13 @@ function abort(request, reason) {
2279
2905
  if (abortableTasks.size > 0) {
2280
2906
  // We have tasks to abort. We'll emit one error row and then emit a reference
2281
2907
  // to that row from every row that's still remaining.
2282
- var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
2283
- var digest = logRecoverableError(request, error);
2284
2908
  request.pendingChunks++;
2285
2909
  var errorId = request.nextChunkId++;
2286
2910
 
2287
- if (true) {
2288
- var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error),
2289
- message = _getErrorMessageAndSt6.message,
2290
- stack = _getErrorMessageAndSt6.stack;
2291
-
2292
- emitErrorChunkDev(request, errorId, digest, message, stack);
2911
+ var postponeInstance; if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
2912
+ var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
2913
+ var digest = logRecoverableError(request, error);
2914
+ emitErrorChunk(request, errorId, digest, error);
2293
2915
  }
2294
2916
 
2295
2917
  abortableTasks.forEach(function (task) {
@@ -2307,28 +2929,20 @@ function abort(request, reason) {
2307
2929
  }
2308
2930
  }
2309
2931
 
2310
- function importServerContexts(contexts) {
2311
- if (contexts) {
2312
- var prevContext = getActiveContext();
2313
- switchContext(rootContextSnapshot);
2314
-
2315
- for (var i = 0; i < contexts.length; i++) {
2316
- var _contexts$i = contexts[i],
2317
- name = _contexts$i[0],
2318
- value = _contexts$i[1];
2319
- var context = getOrCreateServerContext(name);
2320
- pushProvider(context, value);
2321
- }
2322
-
2323
- var importedContext = getActiveContext();
2324
- switchContext(prevContext);
2325
- return importedContext;
2326
- }
2932
+ // This is the parsed shape of the wire format which is why it is
2933
+ // condensed to only the essentialy information
2934
+ var ID = 0;
2935
+ var CHUNKS = 1;
2936
+ var NAME = 2; // export const ASYNC = 3;
2937
+ // This logic is correct because currently only include the 4th tuple member
2938
+ // when the module is async. If that changes we will need to actually assert
2939
+ // the value is true. We don't index into the 4th slot because flow does not
2940
+ // like the potential out of bounds access
2327
2941
 
2328
- return rootContextSnapshot;
2942
+ function isAsyncImport(metadata) {
2943
+ return metadata.length === 4;
2329
2944
  }
2330
2945
 
2331
- // eslint-disable-next-line no-unused-vars
2332
2946
  function resolveServerReference(bundlerConfig, id) {
2333
2947
  var name = '';
2334
2948
  var resolvedModuleData = bundlerConfig[id];
@@ -2354,19 +2968,38 @@ function resolveServerReference(bundlerConfig, id) {
2354
2968
  } // TODO: This needs to return async: true if it's an async module.
2355
2969
 
2356
2970
 
2357
- return {
2358
- id: resolvedModuleData.id,
2359
- chunks: resolvedModuleData.chunks,
2360
- name: name,
2361
- async: false
2362
- };
2971
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
2363
2972
  } // The chunk cache contains all the chunks we've preloaded so far.
2364
2973
  // If they're still pending they're a thenable. This map also exists
2365
2974
  // in Webpack but unfortunately it's not exposed so we have to
2366
2975
  // replicate it in user space. null means that it has already loaded.
2367
2976
 
2368
2977
  var chunkCache = new Map();
2369
- var asyncModuleCache = new Map();
2978
+
2979
+ function requireAsyncModule(id) {
2980
+ // We've already loaded all the chunks. We can require the module.
2981
+ var promise = __webpack_require__(id);
2982
+
2983
+ if (typeof promise.then !== 'function') {
2984
+ // This wasn't a promise after all.
2985
+ return null;
2986
+ } else if (promise.status === 'fulfilled') {
2987
+ // This module was already resolved earlier.
2988
+ return null;
2989
+ } else {
2990
+ // Instrument the Promise to stash the result.
2991
+ promise.then(function (value) {
2992
+ var fulfilledThenable = promise;
2993
+ fulfilledThenable.status = 'fulfilled';
2994
+ fulfilledThenable.value = value;
2995
+ }, function (reason) {
2996
+ var rejectedThenable = promise;
2997
+ rejectedThenable.status = 'rejected';
2998
+ rejectedThenable.reason = reason;
2999
+ });
3000
+ return promise;
3001
+ }
3002
+ }
2370
3003
 
2371
3004
  function ignoreReject() {// We rely on rejected promises to be handled by another listener.
2372
3005
  } // Start preloading the modules since we might need them soon.
@@ -2374,16 +3007,17 @@ function ignoreReject() {// We rely on rejected promises to be handled by anothe
2374
3007
 
2375
3008
 
2376
3009
  function preloadModule(metadata) {
2377
- var chunks = metadata.chunks;
3010
+ var chunks = metadata[CHUNKS];
2378
3011
  var promises = [];
3012
+ var i = 0;
2379
3013
 
2380
- for (var i = 0; i < chunks.length; i++) {
2381
- var chunkId = chunks[i];
3014
+ while (i < chunks.length) {
3015
+ var chunkId = chunks[i++];
3016
+ chunks[i++];
2382
3017
  var entry = chunkCache.get(chunkId);
2383
3018
 
2384
3019
  if (entry === undefined) {
2385
- var thenable = __webpack_chunk_load__(chunkId);
2386
-
3020
+ var thenable = loadChunk(chunkId);
2387
3021
  promises.push(thenable); // $FlowFixMe[method-unbinding]
2388
3022
 
2389
3023
  var resolve = chunkCache.set.bind(chunkCache, chunkId, null);
@@ -2394,30 +3028,13 @@ function preloadModule(metadata) {
2394
3028
  }
2395
3029
  }
2396
3030
 
2397
- if (metadata.async) {
2398
- var existingPromise = asyncModuleCache.get(metadata.id);
2399
-
2400
- if (existingPromise) {
2401
- if (existingPromise.status === 'fulfilled') {
2402
- return null;
2403
- }
2404
-
2405
- return existingPromise;
3031
+ if (isAsyncImport(metadata)) {
3032
+ if (promises.length === 0) {
3033
+ return requireAsyncModule(metadata[ID]);
2406
3034
  } else {
2407
- var modulePromise = Promise.all(promises).then(function () {
2408
- return __webpack_require__(metadata.id);
2409
- });
2410
- modulePromise.then(function (value) {
2411
- var fulfilledThenable = modulePromise;
2412
- fulfilledThenable.status = 'fulfilled';
2413
- fulfilledThenable.value = value;
2414
- }, function (reason) {
2415
- var rejectedThenable = modulePromise;
2416
- rejectedThenable.status = 'rejected';
2417
- rejectedThenable.reason = reason;
3035
+ return Promise.all(promises).then(function () {
3036
+ return requireAsyncModule(metadata[ID]);
2418
3037
  });
2419
- asyncModuleCache.set(metadata.id, modulePromise);
2420
- return modulePromise;
2421
3038
  }
2422
3039
  } else if (promises.length > 0) {
2423
3040
  return Promise.all(promises);
@@ -2428,35 +3045,34 @@ function preloadModule(metadata) {
2428
3045
  // Increase priority if necessary.
2429
3046
 
2430
3047
  function requireModule(metadata) {
2431
- var moduleExports;
3048
+ var moduleExports = __webpack_require__(metadata[ID]);
2432
3049
 
2433
- if (metadata.async) {
2434
- // We assume that preloadModule has been called before, which
2435
- // should have added something to the module cache.
2436
- var promise = asyncModuleCache.get(metadata.id);
2437
-
2438
- if (promise.status === 'fulfilled') {
2439
- moduleExports = promise.value;
3050
+ if (isAsyncImport(metadata)) {
3051
+ if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') {
3052
+ // This Promise should've been instrumented by preloadModule.
3053
+ moduleExports = moduleExports.value;
2440
3054
  } else {
2441
- throw promise.reason;
3055
+ throw moduleExports.reason;
2442
3056
  }
2443
- } else {
2444
- moduleExports = __webpack_require__(metadata.id);
2445
3057
  }
2446
3058
 
2447
- if (metadata.name === '*') {
3059
+ if (metadata[NAME] === '*') {
2448
3060
  // This is a placeholder value that represents that the caller imported this
2449
3061
  // as a CommonJS module as is.
2450
3062
  return moduleExports;
2451
3063
  }
2452
3064
 
2453
- if (metadata.name === '') {
3065
+ if (metadata[NAME] === '') {
2454
3066
  // This is a placeholder value that represents that the caller accessed the
2455
3067
  // default property of this if it was an ESM interop module.
2456
3068
  return moduleExports.__esModule ? moduleExports.default : moduleExports;
2457
3069
  }
2458
3070
 
2459
- return moduleExports[metadata.name];
3071
+ return moduleExports[metadata[NAME]];
3072
+ }
3073
+
3074
+ function loadChunk(chunkId, filename) {
3075
+ return __webpack_chunk_load__(chunkId);
2460
3076
  }
2461
3077
 
2462
3078
  // The server acts as a Client of itself when resolving Server References.
@@ -2556,11 +3172,11 @@ function createResolvedModelChunk(response, value) {
2556
3172
  return new Chunk(RESOLVED_MODEL, value, null, response);
2557
3173
  }
2558
3174
 
2559
- function bindArgs(fn, args) {
3175
+ function bindArgs$1(fn, args) {
2560
3176
  return fn.bind.apply(fn, [null].concat(args));
2561
3177
  }
2562
3178
 
2563
- function loadServerReference(response, id, bound, parentChunk, parentObject, key) {
3179
+ function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) {
2564
3180
  var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
2565
3181
  // the relevant modules already loaded but it allows for lazy loading of code
2566
3182
  // if needed.
@@ -2571,7 +3187,7 @@ function loadServerReference(response, id, bound, parentChunk, parentObject, key
2571
3187
  if (bound) {
2572
3188
  promise = Promise.all([bound, preloadPromise]).then(function (_ref) {
2573
3189
  var args = _ref[0];
2574
- return bindArgs(requireModule(serverReference), args);
3190
+ return bindArgs$1(requireModule(serverReference), args);
2575
3191
  });
2576
3192
  } else {
2577
3193
  if (preloadPromise) {
@@ -2701,6 +3317,21 @@ function createModelReject(chunk) {
2701
3317
  };
2702
3318
  }
2703
3319
 
3320
+ function getOutlinedModel(response, id) {
3321
+ var chunk = getChunk(response, id);
3322
+
3323
+ if (chunk.status === RESOLVED_MODEL) {
3324
+ initializeModelChunk(chunk);
3325
+ }
3326
+
3327
+ if (chunk.status !== INITIALIZED) {
3328
+ // We know that this is emitted earlier so otherwise it's an error.
3329
+ throw chunk.reason;
3330
+ }
3331
+
3332
+ return chunk.value;
3333
+ }
3334
+
2704
3335
  function parseModelString(response, parentObject, key, value) {
2705
3336
  if (value[0] === '$') {
2706
3337
  switch (value[1]) {
@@ -2718,31 +3349,39 @@ function parseModelString(response, parentObject, key, value) {
2718
3349
  return chunk;
2719
3350
  }
2720
3351
 
2721
- case 'S':
3352
+ case 'F':
2722
3353
  {
2723
- // Symbol
2724
- return Symbol.for(value.slice(2));
3354
+ // Server Reference
3355
+ var _id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model.
3356
+
3357
+
3358
+ var metaData = getOutlinedModel(response, _id);
3359
+ return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key);
2725
3360
  }
2726
3361
 
2727
- case 'F':
3362
+ case 'T':
2728
3363
  {
2729
- // Server Reference
2730
- var _id = parseInt(value.slice(2), 16);
3364
+ // Temporary Reference
3365
+ return createTemporaryReference(value.slice(2));
3366
+ }
2731
3367
 
2732
- var _chunk = getChunk(response, _id);
3368
+ case 'Q':
3369
+ {
3370
+ // Map
3371
+ var _id2 = parseInt(value.slice(2), 16);
2733
3372
 
2734
- if (_chunk.status === RESOLVED_MODEL) {
2735
- initializeModelChunk(_chunk);
2736
- }
3373
+ var data = getOutlinedModel(response, _id2);
3374
+ return new Map(data);
3375
+ }
2737
3376
 
2738
- if (_chunk.status !== INITIALIZED) {
2739
- // We know that this is emitted earlier so otherwise it's an error.
2740
- throw _chunk.reason;
2741
- } // TODO: Just encode this in the reference inline instead of as a model.
3377
+ case 'W':
3378
+ {
3379
+ // Set
3380
+ var _id3 = parseInt(value.slice(2), 16);
2742
3381
 
3382
+ var _data = getOutlinedModel(response, _id3);
2743
3383
 
2744
- var metaData = _chunk.value;
2745
- return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key);
3384
+ return new Set(_data);
2746
3385
  }
2747
3386
 
2748
3387
  case 'K':
@@ -2750,7 +3389,9 @@ function parseModelString(response, parentObject, key, value) {
2750
3389
  // FormData
2751
3390
  var stringId = value.slice(2);
2752
3391
  var formPrefix = response._prefix + stringId + '_';
2753
- var data = new FormData();
3392
+
3393
+ var _data2 = new FormData();
3394
+
2754
3395
  var backingFormData = response._formData; // We assume that the reference to FormData always comes after each
2755
3396
  // entry that it references so we can assume they all exist in the
2756
3397
  // backing store already.
@@ -2758,10 +3399,10 @@ function parseModelString(response, parentObject, key, value) {
2758
3399
 
2759
3400
  backingFormData.forEach(function (entry, entryKey) {
2760
3401
  if (entryKey.startsWith(formPrefix)) {
2761
- data.append(entryKey.slice(formPrefix.length), entry);
3402
+ _data2.append(entryKey.slice(formPrefix.length), entry);
2762
3403
  }
2763
3404
  });
2764
- return data;
3405
+ return _data2;
2765
3406
  }
2766
3407
 
2767
3408
  case 'I':
@@ -2808,31 +3449,31 @@ function parseModelString(response, parentObject, key, value) {
2808
3449
  default:
2809
3450
  {
2810
3451
  // We assume that anything else is a reference ID.
2811
- var _id2 = parseInt(value.slice(1), 16);
3452
+ var _id4 = parseInt(value.slice(1), 16);
2812
3453
 
2813
- var _chunk2 = getChunk(response, _id2);
3454
+ var _chunk = getChunk(response, _id4);
2814
3455
 
2815
- switch (_chunk2.status) {
3456
+ switch (_chunk.status) {
2816
3457
  case RESOLVED_MODEL:
2817
- initializeModelChunk(_chunk2);
3458
+ initializeModelChunk(_chunk);
2818
3459
  break;
2819
3460
  } // The status might have changed after initialization.
2820
3461
 
2821
3462
 
2822
- switch (_chunk2.status) {
3463
+ switch (_chunk.status) {
2823
3464
  case INITIALIZED:
2824
- return _chunk2.value;
3465
+ return _chunk.value;
2825
3466
 
2826
3467
  case PENDING:
2827
3468
  case BLOCKED:
2828
3469
  var parentChunk = initializingChunk;
2829
3470
 
2830
- _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk));
3471
+ _chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk));
2831
3472
 
2832
3473
  return null;
2833
3474
 
2834
3475
  default:
2835
- throw _chunk2.reason;
3476
+ throw _chunk.reason;
2836
3477
  }
2837
3478
  }
2838
3479
  }
@@ -2868,8 +3509,130 @@ function close(response) {
2868
3509
  reportGlobalError(response, new Error('Connection closed.'));
2869
3510
  }
2870
3511
 
3512
+ function bindArgs(fn, args) {
3513
+ return fn.bind.apply(fn, [null].concat(args));
3514
+ }
3515
+
3516
+ function loadServerReference(bundlerConfig, id, bound) {
3517
+ var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
3518
+ // the relevant modules already loaded but it allows for lazy loading of code
3519
+ // if needed.
3520
+
3521
+ var preloadPromise = preloadModule(serverReference);
3522
+
3523
+ if (bound) {
3524
+ return Promise.all([bound, preloadPromise]).then(function (_ref) {
3525
+ var args = _ref[0];
3526
+ return bindArgs(requireModule(serverReference), args);
3527
+ });
3528
+ } else if (preloadPromise) {
3529
+ return Promise.resolve(preloadPromise).then(function () {
3530
+ return requireModule(serverReference);
3531
+ });
3532
+ } else {
3533
+ // Synchronously available
3534
+ return Promise.resolve(requireModule(serverReference));
3535
+ }
3536
+ }
3537
+
3538
+ function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) {
3539
+ // The data for this reference is encoded in multiple fields under this prefix.
3540
+ var actionResponse = createResponse(serverManifest, formFieldPrefix, body);
3541
+ close(actionResponse);
3542
+ var refPromise = getRoot(actionResponse); // Force it to initialize
3543
+ // $FlowFixMe
3544
+
3545
+ refPromise.then(function () {});
3546
+
3547
+ if (refPromise.status !== 'fulfilled') {
3548
+ // $FlowFixMe
3549
+ throw refPromise.reason;
3550
+ }
3551
+
3552
+ return refPromise.value;
3553
+ }
3554
+
3555
+ function decodeAction(body, serverManifest) {
3556
+ // We're going to create a new formData object that holds all the fields except
3557
+ // the implementation details of the action data.
3558
+ var formData = new FormData();
3559
+ var action = null; // $FlowFixMe[prop-missing]
3560
+
3561
+ body.forEach(function (value, key) {
3562
+ if (!key.startsWith('$ACTION_')) {
3563
+ formData.append(key, value);
3564
+ return;
3565
+ } // Later actions may override earlier actions if a button is used to override the default
3566
+ // form action.
3567
+
3568
+
3569
+ if (key.startsWith('$ACTION_REF_')) {
3570
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
3571
+ var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
3572
+ action = loadServerReference(serverManifest, metaData.id, metaData.bound);
3573
+ return;
3574
+ }
3575
+
3576
+ if (key.startsWith('$ACTION_ID_')) {
3577
+ var id = key.slice(11);
3578
+ action = loadServerReference(serverManifest, id, null);
3579
+ return;
3580
+ }
3581
+ });
3582
+
3583
+ if (action === null) {
3584
+ return null;
3585
+ } // Return the action with the remaining FormData bound to the first argument.
3586
+
3587
+
3588
+ return action.then(function (fn) {
3589
+ return fn.bind(null, formData);
3590
+ });
3591
+ }
3592
+ function decodeFormState(actionResult, body, serverManifest) {
3593
+ var keyPath = body.get('$ACTION_KEY');
3594
+
3595
+ if (typeof keyPath !== 'string') {
3596
+ // This form submission did not include any form state.
3597
+ return Promise.resolve(null);
3598
+ } // Search through the form data object to get the reference id and the number
3599
+ // of bound arguments. This repeats some of the work done in decodeAction.
3600
+
3601
+
3602
+ var metaData = null; // $FlowFixMe[prop-missing]
3603
+
3604
+ body.forEach(function (value, key) {
3605
+ if (key.startsWith('$ACTION_REF_')) {
3606
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
3607
+ metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
3608
+ } // We don't check for the simple $ACTION_ID_ case because form state actions
3609
+ // are always bound to the state argument.
3610
+
3611
+ });
3612
+
3613
+ if (metaData === null) {
3614
+ // Should be unreachable.
3615
+ return Promise.resolve(null);
3616
+ }
3617
+
3618
+ var referenceId = metaData.id;
3619
+ return Promise.resolve(metaData.bound).then(function (bound) {
3620
+ if (bound === null) {
3621
+ // Should be unreachable because form state actions are always bound to the
3622
+ // state argument.
3623
+ return null;
3624
+ } // The form action dispatch method is always bound to the initial state.
3625
+ // But when comparing signatures, we compare to the original unbound action.
3626
+ // Subtract one from the arity to account for this.
3627
+
3628
+
3629
+ var boundArity = bound.length - 1;
3630
+ return [actionResult, keyPath, referenceId, boundArity];
3631
+ });
3632
+ }
3633
+
2871
3634
  function renderToReadableStream(model, webpackMap, options) {
2872
- var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined);
3635
+ var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, options ? options.environmentName : undefined);
2873
3636
 
2874
3637
  if (options && options.signal) {
2875
3638
  var signal = options.signal;
@@ -2894,7 +3657,10 @@ function renderToReadableStream(model, webpackMap, options) {
2894
3657
  pull: function (controller) {
2895
3658
  startFlowing(request, controller);
2896
3659
  },
2897
- cancel: function (reason) {}
3660
+ cancel: function (reason) {
3661
+ stopFlowing(request);
3662
+ abort(request, reason);
3663
+ }
2898
3664
  }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams.
2899
3665
  {
2900
3666
  highWaterMark: 0
@@ -2910,11 +3676,17 @@ function decodeReply(body, webpackMap) {
2910
3676
  }
2911
3677
 
2912
3678
  var response = createResponse(webpackMap, '', body);
3679
+ var root = getRoot(response);
2913
3680
  close(response);
2914
- return getRoot(response);
3681
+ return root;
2915
3682
  }
2916
3683
 
3684
+ exports.createClientModuleProxy = createClientModuleProxy;
3685
+ exports.decodeAction = decodeAction;
3686
+ exports.decodeFormState = decodeFormState;
2917
3687
  exports.decodeReply = decodeReply;
3688
+ exports.registerClientReference = registerClientReference;
3689
+ exports.registerServerReference = registerServerReference;
2918
3690
  exports.renderToReadableStream = renderToReadableStream;
2919
3691
  })();
2920
3692
  }