react-server-dom-webpack 18.3.0-next-fa4314841-20230502 → 19.0.0-beta-4508873393-20240430

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 (40) hide show
  1. package/cjs/react-server-dom-webpack-client.browser.development.js +1893 -1200
  2. package/cjs/react-server-dom-webpack-client.browser.production.js +931 -0
  3. package/cjs/react-server-dom-webpack-client.edge.development.js +1888 -241
  4. package/cjs/react-server-dom-webpack-client.edge.production.js +1093 -0
  5. package/cjs/react-server-dom-webpack-client.node.development.js +1876 -259
  6. package/cjs/react-server-dom-webpack-client.node.production.js +1070 -0
  7. package/cjs/react-server-dom-webpack-client.node.unbundled.development.js +1833 -212
  8. package/cjs/react-server-dom-webpack-client.node.unbundled.production.js +1049 -0
  9. package/cjs/react-server-dom-webpack-node-register.js +59 -10
  10. package/cjs/react-server-dom-webpack-plugin.js +389 -11
  11. package/cjs/react-server-dom-webpack-server.browser.development.js +2187 -937
  12. package/cjs/react-server-dom-webpack-server.browser.production.js +1935 -0
  13. package/cjs/react-server-dom-webpack-server.edge.development.js +2183 -941
  14. package/cjs/react-server-dom-webpack-server.edge.production.js +1956 -0
  15. package/cjs/react-server-dom-webpack-server.node.development.js +2169 -929
  16. package/cjs/react-server-dom-webpack-server.node.production.js +2083 -0
  17. package/cjs/react-server-dom-webpack-server.node.unbundled.development.js +2116 -881
  18. package/cjs/react-server-dom-webpack-server.node.unbundled.production.js +2051 -0
  19. package/client.browser.js +1 -1
  20. package/client.edge.js +1 -1
  21. package/client.node.js +1 -1
  22. package/client.node.unbundled.js +1 -1
  23. package/esm/{react-server-dom-webpack-node-loader.production.min.js → react-server-dom-webpack-node-loader.production.js} +20 -13
  24. package/package.json +8 -15
  25. package/server.browser.js +1 -1
  26. package/server.edge.js +1 -1
  27. package/server.node.js +1 -1
  28. package/server.node.unbundled.js +1 -1
  29. package/cjs/react-server-dom-webpack-client.browser.production.min.js +0 -34
  30. package/cjs/react-server-dom-webpack-client.edge.production.min.js +0 -28
  31. package/cjs/react-server-dom-webpack-client.node.production.min.js +0 -28
  32. package/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js +0 -26
  33. package/cjs/react-server-dom-webpack-server.browser.production.min.js +0 -62
  34. package/cjs/react-server-dom-webpack-server.edge.production.min.js +0 -62
  35. package/cjs/react-server-dom-webpack-server.node.production.min.js +0 -67
  36. package/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js +0 -65
  37. package/umd/react-server-dom-webpack-client.browser.development.js +0 -1731
  38. package/umd/react-server-dom-webpack-client.browser.production.min.js +0 -29
  39. package/umd/react-server-dom-webpack-server.browser.development.js +0 -2904
  40. package/umd/react-server-dom-webpack-server.browser.production.min.js +0 -51
@@ -15,11 +15,32 @@ if (process.env.NODE_ENV !== "production") {
15
15
  'use strict';
16
16
 
17
17
  var React = require('react');
18
- var async_hooks = require('async_hooks');
19
18
  var util = require('util');
19
+ require('crypto');
20
+ var async_hooks = require('async_hooks');
20
21
  var ReactDOM = require('react-dom');
21
22
 
22
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
23
+ function _defineProperty(obj, key, value) {
24
+ if (key in obj) {
25
+ Object.defineProperty(obj, key, {
26
+ value: value,
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true
30
+ });
31
+ } else {
32
+ obj[key] = value;
33
+ }
34
+
35
+ return obj;
36
+ }
37
+
38
+ var ReactSharedInternalsServer = // $FlowFixMe: It's defined in the one we resolve to.
39
+ React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
40
+
41
+ if (!ReactSharedInternalsServer) {
42
+ 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.');
43
+ }
23
44
 
24
45
  function error(format) {
25
46
  {
@@ -37,8 +58,7 @@ function printWarning(level, format, args) {
37
58
  // When changing this logic, you might want to also
38
59
  // update consoleWithStackDev.www.js as well.
39
60
  {
40
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
41
- var stack = ReactDebugCurrentFrame.getStackAddendum();
61
+ var stack = ReactSharedInternalsServer.getStackAddendum();
42
62
 
43
63
  if (stack !== '') {
44
64
  format += '%s';
@@ -58,6 +78,9 @@ function printWarning(level, format, args) {
58
78
  }
59
79
  }
60
80
 
81
+ // -----------------------------------------------------------------------------
82
+ var enablePostpone = false;
83
+
61
84
  function scheduleWork(callback) {
62
85
  setImmediate(callback);
63
86
  }
@@ -128,15 +151,9 @@ function writeViewChunk(destination, chunk) {
128
151
  }
129
152
 
130
153
  if (chunk.byteLength > VIEW_SIZE) {
131
- {
132
- if (precomputedChunkSet && precomputedChunkSet.has(chunk)) {
133
- 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.');
134
- }
135
- } // this chunk may overflow a single view which implies it was not
154
+ // this chunk may overflow a single view which implies it was not
136
155
  // one that is cached by the streaming renderer. We will enqueu
137
156
  // it directly and expect it is not re-used
138
-
139
-
140
157
  if (writtenBytes > 0) {
141
158
  writeToDestination(destination, currentView.subarray(0, writtenBytes));
142
159
  currentView = new Uint8Array(VIEW_SIZE);
@@ -212,71 +229,278 @@ var textEncoder = new util.TextEncoder();
212
229
  function stringToChunk(content) {
213
230
  return content;
214
231
  }
215
- var precomputedChunkSet = new Set() ;
232
+ function byteLengthOfChunk(chunk) {
233
+ return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength;
234
+ }
216
235
  function closeWithError(destination, error) {
217
236
  // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
218
237
  destination.destroy(error);
219
238
  }
220
239
 
221
- // This file is an intermediate layer to translate between Flight
222
- var stringify = JSON.stringify;
223
-
224
- function serializeRowHeader(tag, id) {
225
- return id.toString(16) + ':' + tag;
240
+ // eslint-disable-next-line no-unused-vars
241
+ var CLIENT_REFERENCE_TAG$1 = Symbol.for('react.client.reference');
242
+ var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
243
+ function isClientReference(reference) {
244
+ return reference.$$typeof === CLIENT_REFERENCE_TAG$1;
245
+ }
246
+ function isServerReference(reference) {
247
+ return reference.$$typeof === SERVER_REFERENCE_TAG;
248
+ }
249
+ function registerClientReference(proxyImplementation, id, exportName) {
250
+ return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false);
226
251
  }
227
252
 
228
- function processErrorChunkProd(request, id, digest) {
229
- {
230
- // These errors should never make it into a build so we don't need to encode them in codes.json
231
- // eslint-disable-next-line react-internal/prod-error-codes
232
- throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.');
253
+ function registerClientReferenceImpl(proxyImplementation, id, async) {
254
+ return Object.defineProperties(proxyImplementation, {
255
+ $$typeof: {
256
+ value: CLIENT_REFERENCE_TAG$1
257
+ },
258
+ $$id: {
259
+ value: id
260
+ },
261
+ $$async: {
262
+ value: async
263
+ }
264
+ });
265
+ } // $FlowFixMe[method-unbinding]
266
+
267
+
268
+ var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding]
269
+
270
+ var ArraySlice = Array.prototype.slice;
271
+
272
+ function bind() {
273
+ // $FlowFixMe[unsupported-syntax]
274
+ var newFn = FunctionBind.apply(this, arguments);
275
+
276
+ if (this.$$typeof === SERVER_REFERENCE_TAG) {
277
+ {
278
+ var thisBind = arguments[0];
279
+
280
+ if (thisBind != null) {
281
+ error('Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().');
282
+ }
283
+ }
284
+
285
+ var args = ArraySlice.call(arguments, 1);
286
+ return Object.defineProperties(newFn, {
287
+ $$typeof: {
288
+ value: SERVER_REFERENCE_TAG
289
+ },
290
+ $$id: {
291
+ value: this.$$id
292
+ },
293
+ $$bound: {
294
+ value: this.$$bound ? this.$$bound.concat(args) : args
295
+ },
296
+ bind: {
297
+ value: bind
298
+ }
299
+ });
233
300
  }
234
- }
235
- function processErrorChunkDev(request, id, digest, message, stack) {
236
301
 
237
- var errorInfo = {
238
- digest: digest,
239
- message: message,
240
- stack: stack
241
- };
242
- var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
243
- return stringToChunk(row);
302
+ return newFn;
244
303
  }
245
- function processModelChunk(request, id, model) {
246
- // $FlowFixMe[incompatible-type] stringify can return null
247
- var json = stringify(model, request.toJSON);
248
- var row = id.toString(16) + ':' + json + '\n';
249
- return stringToChunk(row);
250
- }
251
- function processReferenceChunk(request, id, reference) {
252
- var json = stringify(reference);
253
- var row = id.toString(16) + ':' + json + '\n';
254
- return stringToChunk(row);
304
+
305
+ function registerServerReference(reference, id, exportName) {
306
+ return Object.defineProperties(reference, {
307
+ $$typeof: {
308
+ value: SERVER_REFERENCE_TAG
309
+ },
310
+ $$id: {
311
+ value: exportName === null ? id : id + '#' + exportName,
312
+ configurable: true
313
+ },
314
+ $$bound: {
315
+ value: null,
316
+ configurable: true
317
+ },
318
+ bind: {
319
+ value: bind,
320
+ configurable: true
321
+ }
322
+ });
255
323
  }
256
- function processImportChunk(request, id, clientReferenceMetadata) {
257
- // $FlowFixMe[incompatible-type] stringify can return null
258
- var json = stringify(clientReferenceMetadata);
259
- var row = serializeRowHeader('I', id) + json + '\n';
260
- return stringToChunk(row);
324
+ var PROMISE_PROTOTYPE = Promise.prototype;
325
+ var deepProxyHandlers = {
326
+ get: function (target, name, receiver) {
327
+ switch (name) {
328
+ // These names are read by the Flight runtime if you end up using the exports object.
329
+ case '$$typeof':
330
+ // These names are a little too common. We should probably have a way to
331
+ // have the Flight runtime extract the inner target instead.
332
+ return target.$$typeof;
333
+
334
+ case '$$id':
335
+ return target.$$id;
336
+
337
+ case '$$async':
338
+ return target.$$async;
339
+
340
+ case 'name':
341
+ return target.name;
342
+
343
+ case 'displayName':
344
+ return undefined;
345
+ // We need to special case this because createElement reads it if we pass this
346
+ // reference.
347
+
348
+ case 'defaultProps':
349
+ return undefined;
350
+ // Avoid this attempting to be serialized.
351
+
352
+ case 'toJSON':
353
+ return undefined;
354
+
355
+ case Symbol.toPrimitive:
356
+ // $FlowFixMe[prop-missing]
357
+ return Object.prototype[Symbol.toPrimitive];
358
+
359
+ case Symbol.toStringTag:
360
+ // $FlowFixMe[prop-missing]
361
+ return Object.prototype[Symbol.toStringTag];
362
+
363
+ case 'Provider':
364
+ 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.");
365
+ } // eslint-disable-next-line react-internal/safe-string-coercion
366
+
367
+
368
+ var expression = String(target.name) + '.' + String(name);
369
+ 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.');
370
+ },
371
+ set: function () {
372
+ throw new Error('Cannot assign to a client module from a server module.');
373
+ }
374
+ };
375
+
376
+ function getReference(target, name) {
377
+ switch (name) {
378
+ // These names are read by the Flight runtime if you end up using the exports object.
379
+ case '$$typeof':
380
+ return target.$$typeof;
381
+
382
+ case '$$id':
383
+ return target.$$id;
384
+
385
+ case '$$async':
386
+ return target.$$async;
387
+
388
+ case 'name':
389
+ return target.name;
390
+ // We need to special case this because createElement reads it if we pass this
391
+ // reference.
392
+
393
+ case 'defaultProps':
394
+ return undefined;
395
+ // Avoid this attempting to be serialized.
396
+
397
+ case 'toJSON':
398
+ return undefined;
399
+
400
+ case Symbol.toPrimitive:
401
+ // $FlowFixMe[prop-missing]
402
+ return Object.prototype[Symbol.toPrimitive];
403
+
404
+ case Symbol.toStringTag:
405
+ // $FlowFixMe[prop-missing]
406
+ return Object.prototype[Symbol.toStringTag];
407
+
408
+ case '__esModule':
409
+ // Something is conditionally checking which export to use. We'll pretend to be
410
+ // an ESM compat module but then we'll check again on the client.
411
+ var moduleId = target.$$id;
412
+ target.default = registerClientReferenceImpl(function () {
413
+ 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.");
414
+ }, target.$$id + '#', target.$$async);
415
+ return true;
416
+
417
+ case 'then':
418
+ if (target.then) {
419
+ // Use a cached value
420
+ return target.then;
421
+ }
422
+
423
+ if (!target.$$async) {
424
+ // If this module is expected to return a Promise (such as an AsyncModule) then
425
+ // we should resolve that with a client reference that unwraps the Promise on
426
+ // the client.
427
+ var clientReference = registerClientReferenceImpl({}, target.$$id, true);
428
+ var proxy = new Proxy(clientReference, proxyHandlers$1); // Treat this as a resolved Promise for React's use()
429
+
430
+ target.status = 'fulfilled';
431
+ target.value = proxy;
432
+ var then = target.then = registerClientReferenceImpl(function then(resolve, reject) {
433
+ // Expose to React.
434
+ return Promise.resolve(resolve(proxy));
435
+ }, // If this is not used as a Promise but is treated as a reference to a `.then`
436
+ // export then we should treat it as a reference to that name.
437
+ target.$$id + '#then', false);
438
+ return then;
439
+ } else {
440
+ // Since typeof .then === 'function' is a feature test we'd continue recursing
441
+ // indefinitely if we return a function. Instead, we return an object reference
442
+ // if we check further.
443
+ return undefined;
444
+ }
445
+
446
+ }
447
+
448
+ if (typeof name === 'symbol') {
449
+ throw new Error('Cannot read Symbol exports. Only named exports are supported on a client module ' + 'imported on the server.');
450
+ }
451
+
452
+ var cachedReference = target[name];
453
+
454
+ if (!cachedReference) {
455
+ var reference = registerClientReferenceImpl(function () {
456
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
457
+ "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.");
458
+ }, target.$$id + '#' + name, target.$$async);
459
+ Object.defineProperty(reference, 'name', {
460
+ value: name
461
+ });
462
+ cachedReference = target[name] = new Proxy(reference, deepProxyHandlers);
463
+ }
464
+
465
+ return cachedReference;
261
466
  }
262
- function processHintChunk(request, id, code, model) {
263
- var json = stringify(model);
264
- var row = serializeRowHeader('H' + code, id) + json + '\n';
265
- return stringToChunk(row);
467
+
468
+ var proxyHandlers$1 = {
469
+ get: function (target, name, receiver) {
470
+ return getReference(target, name);
471
+ },
472
+ getOwnPropertyDescriptor: function (target, name) {
473
+ var descriptor = Object.getOwnPropertyDescriptor(target, name);
474
+
475
+ if (!descriptor) {
476
+ descriptor = {
477
+ value: getReference(target, name),
478
+ writable: false,
479
+ configurable: false,
480
+ enumerable: false
481
+ };
482
+ Object.defineProperty(target, name, descriptor);
483
+ }
484
+
485
+ return descriptor;
486
+ },
487
+ getPrototypeOf: function (target) {
488
+ // Pretend to be a Promise in case anyone asks.
489
+ return PROMISE_PROTOTYPE;
490
+ },
491
+ set: function () {
492
+ throw new Error('Cannot assign to a client module from a server module.');
493
+ }
494
+ };
495
+ function createClientModuleProxy(moduleId) {
496
+ var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import.
497
+ moduleId, false);
498
+ return new Proxy(clientReference, proxyHandlers$1);
266
499
  }
267
500
 
268
- // eslint-disable-next-line no-unused-vars
269
- var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
270
- var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
271
501
  function getClientReferenceKey(reference) {
272
502
  return reference.$$async ? reference.$$id + '#async' : reference.$$id;
273
503
  }
274
- function isClientReference(reference) {
275
- return reference.$$typeof === CLIENT_REFERENCE_TAG;
276
- }
277
- function isServerReference(reference) {
278
- return reference.$$typeof === SERVER_REFERENCE_TAG;
279
- }
280
504
  function resolveClientReferenceMetadata(config, clientReference) {
281
505
  var modulePath = clientReference.$$id;
282
506
  var name = '';
@@ -302,12 +526,11 @@ function resolveClientReferenceMetadata(config, clientReference) {
302
526
  }
303
527
  }
304
528
 
305
- return {
306
- id: resolvedModuleData.id,
307
- chunks: resolvedModuleData.chunks,
308
- name: name,
309
- async: !!clientReference.$$async
310
- };
529
+ if (clientReference.$$async === true) {
530
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1];
531
+ } else {
532
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
533
+ }
311
534
  }
312
535
  function getServerReferenceId(config, serverReference) {
313
536
  return serverReference.$$id;
@@ -316,347 +539,402 @@ function getServerReferenceBoundArguments(config, serverReference) {
316
539
  return serverReference.$$bound;
317
540
  }
318
541
 
319
- var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
320
-
321
- var ReactDOMFlightServerDispatcher = {
322
- prefetchDNS: prefetchDNS,
323
- preconnect: preconnect,
324
- preload: preload,
325
- preinit: preinit
542
+ var ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
543
+
544
+ var previousDispatcher = ReactDOMSharedInternals.d;
545
+ /* ReactDOMCurrentDispatcher */
546
+
547
+ ReactDOMSharedInternals.d
548
+ /* ReactDOMCurrentDispatcher */
549
+ = {
550
+ f
551
+ /* flushSyncWork */
552
+ : previousDispatcher.f
553
+ /* flushSyncWork */
554
+ ,
555
+ r
556
+ /* requestFormReset */
557
+ : previousDispatcher.r
558
+ /* requestFormReset */
559
+ ,
560
+ D
561
+ /* prefetchDNS */
562
+ : prefetchDNS,
563
+ C
564
+ /* preconnect */
565
+ : preconnect,
566
+ L
567
+ /* preload */
568
+ : preload,
569
+ m
570
+ /* preloadModule */
571
+ : preloadModule$1,
572
+ X
573
+ /* preinitScript */
574
+ : preinitScript,
575
+ S
576
+ /* preinitStyle */
577
+ : preinitStyle,
578
+ M
579
+ /* preinitModuleScript */
580
+ : preinitModuleScript
326
581
  };
327
582
 
328
- function prefetchDNS(href, options) {
329
- {
330
- if (typeof href === 'string') {
331
- var request = resolveRequest();
332
-
333
- if (request) {
334
- var hints = getHints(request);
335
- var key = 'D' + href;
336
-
337
- if (hints.has(key)) {
338
- // duplicate hint
339
- return;
340
- }
583
+ function prefetchDNS(href) {
584
+ if (typeof href === 'string' && href) {
585
+ var request = resolveRequest();
341
586
 
342
- hints.add(key);
587
+ if (request) {
588
+ var hints = getHints(request);
589
+ var key = 'D|' + href;
343
590
 
344
- if (options) {
345
- emitHint(request, 'D', [href, options]);
346
- } else {
347
- emitHint(request, 'D', href);
348
- }
591
+ if (hints.has(key)) {
592
+ // duplicate hint
593
+ return;
349
594
  }
595
+
596
+ hints.add(key);
597
+ emitHint(request, 'D', href);
598
+ } else {
599
+ previousDispatcher.D(
600
+ /* prefetchDNS */
601
+ href);
350
602
  }
351
603
  }
352
604
  }
353
605
 
354
- function preconnect(href, options) {
355
- {
356
- if (typeof href === 'string') {
357
- var request = resolveRequest();
606
+ function preconnect(href, crossOrigin) {
607
+ if (typeof href === 'string') {
608
+ var request = resolveRequest();
358
609
 
359
- if (request) {
360
- var hints = getHints(request);
361
- var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : '';
362
- var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href;
610
+ if (request) {
611
+ var hints = getHints(request);
612
+ var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href;
363
613
 
364
- if (hints.has(key)) {
365
- // duplicate hint
366
- return;
367
- }
614
+ if (hints.has(key)) {
615
+ // duplicate hint
616
+ return;
617
+ }
368
618
 
369
- hints.add(key);
619
+ hints.add(key);
370
620
 
371
- if (options) {
372
- emitHint(request, 'C', [href, options]);
373
- } else {
374
- emitHint(request, 'C', href);
375
- }
621
+ if (typeof crossOrigin === 'string') {
622
+ emitHint(request, 'C', [href, crossOrigin]);
623
+ } else {
624
+ emitHint(request, 'C', href);
376
625
  }
626
+ } else {
627
+ previousDispatcher.C(
628
+ /* preconnect */
629
+ href, crossOrigin);
377
630
  }
378
631
  }
379
632
  }
380
633
 
381
- function preload(href, options) {
382
- {
383
- if (typeof href === 'string') {
384
- var request = resolveRequest();
385
-
386
- if (request) {
387
- var hints = getHints(request);
388
- var key = 'L' + href;
634
+ function preload(href, as, options) {
635
+ if (typeof href === 'string') {
636
+ var request = resolveRequest();
389
637
 
390
- if (hints.has(key)) {
391
- // duplicate hint
392
- return;
393
- }
638
+ if (request) {
639
+ var hints = getHints(request);
640
+ var key = 'L';
394
641
 
395
- hints.add(key);
396
- emitHint(request, 'L', [href, options]);
642
+ if (as === 'image' && options) {
643
+ key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes);
644
+ } else {
645
+ key += "[" + as + "]" + href;
397
646
  }
398
- }
399
- }
400
- }
401
647
 
402
- function preinit(href, options) {
403
- {
404
- if (typeof href === 'string') {
405
- var request = resolveRequest();
406
-
407
- if (request) {
408
- var hints = getHints(request);
409
- var key = 'I' + href;
648
+ if (hints.has(key)) {
649
+ // duplicate hint
650
+ return;
651
+ }
410
652
 
411
- if (hints.has(key)) {
412
- // duplicate hint
413
- return;
414
- }
653
+ hints.add(key);
654
+ var trimmed = trimOptions(options);
415
655
 
416
- hints.add(key);
417
- emitHint(request, 'I', [href, options]);
656
+ if (trimmed) {
657
+ emitHint(request, 'L', [href, as, trimmed]);
658
+ } else {
659
+ emitHint(request, 'L', [href, as]);
418
660
  }
661
+ } else {
662
+ previousDispatcher.L(
663
+ /* preload */
664
+ href, as, options);
419
665
  }
420
666
  }
421
667
  }
422
668
 
423
- var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher;
424
- function prepareHostDispatcher() {
425
- ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher;
426
- } // Used to distinguish these contexts from ones used in other renderers.
427
- function createHints() {
428
- return new Set();
429
- }
669
+ function preloadModule$1(href, options) {
670
+ if (typeof href === 'string') {
671
+ var request = resolveRequest();
430
672
 
431
- var requestStorage = new async_hooks.AsyncLocalStorage();
673
+ if (request) {
674
+ var hints = getHints(request);
675
+ var key = 'm|' + href;
432
676
 
433
- // ATTENTION
434
- // When adding new symbols to this file,
435
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
436
- // The Symbol used to tag the ReactElement-like types.
437
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
438
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
439
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
440
- var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
441
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
442
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
443
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
444
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
445
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
446
- var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
447
- var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
448
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
449
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
450
- function getIteratorFn(maybeIterable) {
451
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
452
- return null;
453
- }
677
+ if (hints.has(key)) {
678
+ // duplicate hint
679
+ return;
680
+ }
454
681
 
455
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
682
+ hints.add(key);
683
+ var trimmed = trimOptions(options);
456
684
 
457
- if (typeof maybeIterator === 'function') {
458
- return maybeIterator;
685
+ if (trimmed) {
686
+ return emitHint(request, 'm', [href, trimmed]);
687
+ } else {
688
+ return emitHint(request, 'm', href);
689
+ }
690
+ } else {
691
+ previousDispatcher.m(
692
+ /* preloadModule */
693
+ href, options);
694
+ }
459
695
  }
460
-
461
- return null;
462
696
  }
463
697
 
464
- var rendererSigil;
465
-
466
- {
467
- // Use this to detect multiple renderers using the same context
468
- rendererSigil = {};
469
- } // Used to store the parent path of all context overrides in a shared linked list.
470
- // Forming a reverse tree.
471
- // The structure of a context snapshot is an implementation of this file.
472
- // Currently, it's implemented as tracking the current active node.
698
+ function preinitStyle(href, precedence, options) {
699
+ if (typeof href === 'string') {
700
+ var request = resolveRequest();
473
701
 
702
+ if (request) {
703
+ var hints = getHints(request);
704
+ var key = 'S|' + href;
474
705
 
475
- var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
476
- // This global (actually thread local) state represents what state all those "current",
477
- // fields are currently in.
706
+ if (hints.has(key)) {
707
+ // duplicate hint
708
+ return;
709
+ }
478
710
 
479
- var currentActiveSnapshot = null;
711
+ hints.add(key);
712
+ var trimmed = trimOptions(options);
480
713
 
481
- function popNode(prev) {
482
- {
483
- prev.context._currentValue = prev.parentValue;
714
+ if (trimmed) {
715
+ return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]);
716
+ } else if (typeof precedence === 'string') {
717
+ return emitHint(request, 'S', [href, precedence]);
718
+ } else {
719
+ return emitHint(request, 'S', href);
720
+ }
721
+ } else {
722
+ previousDispatcher.S(
723
+ /* preinitStyle */
724
+ href, precedence, options);
725
+ }
484
726
  }
485
727
  }
486
728
 
487
- function pushNode(next) {
488
- {
489
- next.context._currentValue = next.value;
490
- }
491
- }
729
+ function preinitScript(src, options) {
730
+ if (typeof src === 'string') {
731
+ var request = resolveRequest();
492
732
 
493
- function popToNearestCommonAncestor(prev, next) {
494
- if (prev === next) ; else {
495
- popNode(prev);
496
- var parentPrev = prev.parent;
497
- var parentNext = next.parent;
733
+ if (request) {
734
+ var hints = getHints(request);
735
+ var key = 'X|' + src;
498
736
 
499
- if (parentPrev === null) {
500
- if (parentNext !== null) {
501
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
502
- }
503
- } else {
504
- if (parentNext === null) {
505
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
737
+ if (hints.has(key)) {
738
+ // duplicate hint
739
+ return;
506
740
  }
507
741
 
508
- popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common.
742
+ hints.add(key);
743
+ var trimmed = trimOptions(options);
509
744
 
510
- pushNode(next);
745
+ if (trimmed) {
746
+ return emitHint(request, 'X', [src, trimmed]);
747
+ } else {
748
+ return emitHint(request, 'X', src);
749
+ }
750
+ } else {
751
+ previousDispatcher.X(
752
+ /* preinitScript */
753
+ src, options);
511
754
  }
512
755
  }
513
756
  }
514
757
 
515
- function popAllPrevious(prev) {
516
- popNode(prev);
517
- var parentPrev = prev.parent;
758
+ function preinitModuleScript(src, options) {
759
+ if (typeof src === 'string') {
760
+ var request = resolveRequest();
518
761
 
519
- if (parentPrev !== null) {
520
- popAllPrevious(parentPrev);
521
- }
522
- }
762
+ if (request) {
763
+ var hints = getHints(request);
764
+ var key = 'M|' + src;
765
+
766
+ if (hints.has(key)) {
767
+ // duplicate hint
768
+ return;
769
+ }
523
770
 
524
- function pushAllNext(next) {
525
- var parentNext = next.parent;
771
+ hints.add(key);
772
+ var trimmed = trimOptions(options);
526
773
 
527
- if (parentNext !== null) {
528
- pushAllNext(parentNext);
774
+ if (trimmed) {
775
+ return emitHint(request, 'M', [src, trimmed]);
776
+ } else {
777
+ return emitHint(request, 'M', src);
778
+ }
779
+ } else {
780
+ previousDispatcher.M(
781
+ /* preinitModuleScript */
782
+ src, options);
783
+ }
784
+ }
785
+ } // Flight normally encodes undefined as a special character however for directive option
786
+ // arguments we don't want to send unnecessary keys and bloat the payload so we create a
787
+ // trimmed object which omits any keys with null or undefined values.
788
+ // This is only typesafe because these option objects have entirely optional fields where
789
+ // null and undefined represent the same thing as no property.
790
+
791
+
792
+ function trimOptions(options) {
793
+ if (options == null) return null;
794
+ var hasProperties = false;
795
+ var trimmed = {};
796
+
797
+ for (var key in options) {
798
+ if (options[key] != null) {
799
+ hasProperties = true;
800
+ trimmed[key] = options[key];
801
+ }
529
802
  }
530
803
 
531
- pushNode(next);
804
+ return hasProperties ? trimmed : null;
532
805
  }
533
806
 
534
- function popPreviousToCommonLevel(prev, next) {
535
- popNode(prev);
536
- var parentPrev = prev.parent;
807
+ function getImagePreloadKey(href, imageSrcSet, imageSizes) {
808
+ var uniquePart = '';
537
809
 
538
- if (parentPrev === null) {
539
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
540
- }
810
+ if (typeof imageSrcSet === 'string' && imageSrcSet !== '') {
811
+ uniquePart += '[' + imageSrcSet + ']';
541
812
 
542
- if (parentPrev.depth === next.depth) {
543
- // We found the same level. Now we just need to find a shared ancestor.
544
- popToNearestCommonAncestor(parentPrev, next);
813
+ if (typeof imageSizes === 'string') {
814
+ uniquePart += '[' + imageSizes + ']';
815
+ }
545
816
  } else {
546
- // We must still be deeper.
547
- popPreviousToCommonLevel(parentPrev, next);
817
+ uniquePart += '[][]' + href;
548
818
  }
819
+
820
+ return "[image]" + uniquePart;
549
821
  }
550
822
 
551
- function popNextToCommonLevel(prev, next) {
552
- var parentNext = next.parent;
823
+ // This module registers the host dispatcher so it needs to be imported
824
+ // small, smaller than how we encode undefined, and is unambiguous. We could use
825
+ // a different tuple structure to encode this instead but this makes the runtime
826
+ // cost cheaper by eliminating a type checks in more positions.
827
+ // prettier-ignore
553
828
 
554
- if (parentNext === null) {
555
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
556
- }
829
+ function createHints() {
830
+ return new Set();
831
+ }
557
832
 
558
- if (prev.depth === parentNext.depth) {
559
- // We found the same level. Now we just need to find a shared ancestor.
560
- popToNearestCommonAncestor(prev, parentNext);
561
- } else {
562
- // We must still be deeper.
563
- popNextToCommonLevel(prev, parentNext);
564
- }
565
-
566
- pushNode(next);
567
- } // Perform context switching to the new snapshot.
568
- // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
569
- // updating all the context's current values. That way reads, always just read the current value.
570
- // At the cost of updating contexts even if they're never read by this subtree.
571
-
572
-
573
- function switchContext(newSnapshot) {
574
- // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
575
- // We also need to update any new contexts that are now on the stack with the deepest value.
576
- // The easiest way to update new contexts is to just reapply them in reverse order from the
577
- // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
578
- // for that. Therefore this algorithm is recursive.
579
- // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
580
- // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
581
- // 3) Then we reapply new contexts on the way back up the stack.
582
- var prev = currentActiveSnapshot;
583
- var next = newSnapshot;
584
-
585
- if (prev !== next) {
586
- if (prev === null) {
587
- // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev.
588
- pushAllNext(next);
589
- } else if (next === null) {
590
- popAllPrevious(prev);
591
- } else if (prev.depth === next.depth) {
592
- popToNearestCommonAncestor(prev, next);
593
- } else if (prev.depth > next.depth) {
594
- popPreviousToCommonLevel(prev, next);
595
- } else {
596
- popNextToCommonLevel(prev, next);
597
- }
833
+ var supportsRequestStorage = true;
834
+ var requestStorage = new async_hooks.AsyncLocalStorage();
598
835
 
599
- currentActiveSnapshot = next;
600
- }
836
+ var TEMPORARY_REFERENCE_TAG = Symbol.for('react.temporary.reference'); // eslint-disable-next-line no-unused-vars
837
+
838
+ function isTemporaryReference(reference) {
839
+ return reference.$$typeof === TEMPORARY_REFERENCE_TAG;
840
+ }
841
+ function resolveTemporaryReferenceID(temporaryReference) {
842
+ return temporaryReference.$$id;
601
843
  }
602
- function pushProvider(context, nextValue) {
603
- var prevValue;
844
+ var proxyHandlers = {
845
+ get: function (target, name, receiver) {
846
+ switch (name) {
847
+ // These names are read by the Flight runtime if you end up using the exports object.
848
+ case '$$typeof':
849
+ // These names are a little too common. We should probably have a way to
850
+ // have the Flight runtime extract the inner target instead.
851
+ return target.$$typeof;
604
852
 
605
- {
606
- prevValue = context._currentValue;
607
- context._currentValue = nextValue;
853
+ case '$$id':
854
+ return target.$$id;
608
855
 
609
- {
610
- if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
611
- error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
612
- }
856
+ case '$$async':
857
+ return target.$$async;
613
858
 
614
- context._currentRenderer = rendererSigil;
615
- }
616
- }
859
+ case 'name':
860
+ return undefined;
617
861
 
618
- var prevNode = currentActiveSnapshot;
619
- var newNode = {
620
- parent: prevNode,
621
- depth: prevNode === null ? 0 : prevNode.depth + 1,
622
- context: context,
623
- parentValue: prevValue,
624
- value: nextValue
625
- };
626
- currentActiveSnapshot = newNode;
627
- return newNode;
628
- }
629
- function popProvider() {
630
- var prevSnapshot = currentActiveSnapshot;
862
+ case 'displayName':
863
+ return undefined;
864
+ // We need to special case this because createElement reads it if we pass this
865
+ // reference.
631
866
 
632
- if (prevSnapshot === null) {
633
- throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
634
- }
867
+ case 'defaultProps':
868
+ return undefined;
869
+ // Avoid this attempting to be serialized.
635
870
 
636
- {
637
- var value = prevSnapshot.parentValue;
871
+ case 'toJSON':
872
+ return undefined;
638
873
 
639
- if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
640
- prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
641
- } else {
642
- prevSnapshot.context._currentValue = value;
874
+ case Symbol.toPrimitive:
875
+ // $FlowFixMe[prop-missing]
876
+ return Object.prototype[Symbol.toPrimitive];
877
+
878
+ case Symbol.toStringTag:
879
+ // $FlowFixMe[prop-missing]
880
+ return Object.prototype[Symbol.toStringTag];
881
+
882
+ case 'Provider':
883
+ 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.");
643
884
  }
644
- }
645
885
 
646
- return currentActiveSnapshot = prevSnapshot.parent;
647
- }
648
- function getActiveContext() {
649
- return currentActiveSnapshot;
650
- }
651
- function readContext$1(context) {
652
- var value = context._currentValue ;
653
- return value;
886
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
887
+ "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.');
888
+ },
889
+ set: function () {
890
+ throw new Error('Cannot assign to a temporary client reference from a server module.');
891
+ }
892
+ };
893
+ function createTemporaryReference(id) {
894
+ var reference = Object.defineProperties(function () {
895
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
896
+ "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.");
897
+ }, {
898
+ $$typeof: {
899
+ value: TEMPORARY_REFERENCE_TAG
900
+ },
901
+ $$id: {
902
+ value: id
903
+ }
904
+ });
905
+ return new Proxy(reference, proxyHandlers);
654
906
  }
655
907
 
656
- // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
657
- // changes to one module should be reflected in the others.
658
- // TODO: Rename this module and the corresponding Fiber one to "Thenable"
659
- // instead of "Wakeable". Or some other more appropriate name.
908
+ var REACT_ELEMENT_TYPE = Symbol.for('react.transitional.element') ;
909
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
910
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
911
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
912
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
913
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
914
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
915
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
916
+ var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
917
+ var REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
918
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
919
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
920
+ function getIteratorFn(maybeIterable) {
921
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
922
+ return null;
923
+ }
924
+
925
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
926
+
927
+ if (typeof maybeIterator === 'function') {
928
+ return maybeIterator;
929
+ }
930
+
931
+ return null;
932
+ }
933
+
934
+ // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
935
+ // changes to one module should be reflected in the others.
936
+ // TODO: Rename this module and the corresponding Fiber one to "Thenable"
937
+ // instead of "Wakeable". Or some other more appropriate name.
660
938
  // An error that is thrown (e.g. by `use`) to trigger Suspense. If we
661
939
  // detect this is caught by userspace, we'll log a warning in development.
662
940
  var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`");
@@ -705,7 +983,14 @@ function trackUsedThenable(thenableState, thenable, index) {
705
983
 
706
984
  default:
707
985
  {
708
- if (typeof thenable.status === 'string') ; else {
986
+ if (typeof thenable.status === 'string') {
987
+ // Only instrument the thenable if the status if not defined. If
988
+ // it's defined, but an unknown value, assume it's been instrumented by
989
+ // some custom userspace implementation. We treat it as "pending".
990
+ // Attach a dummy listener, to ensure that any lazy initialization can
991
+ // happen. Flight lazily parses JSON when the value is actually awaited.
992
+ thenable.then(noop, noop);
993
+ } else {
709
994
  var pendingThenable = thenable;
710
995
  pendingThenable.status = 'pending';
711
996
  pendingThenable.then(function (fulfilledValue) {
@@ -720,21 +1005,22 @@ function trackUsedThenable(thenableState, thenable, index) {
720
1005
  rejectedThenable.status = 'rejected';
721
1006
  rejectedThenable.reason = error;
722
1007
  }
723
- }); // Check one more time in case the thenable resolved synchronously
1008
+ });
1009
+ } // Check one more time in case the thenable resolved synchronously
724
1010
 
725
- switch (thenable.status) {
726
- case 'fulfilled':
727
- {
728
- var fulfilledThenable = thenable;
729
- return fulfilledThenable.value;
730
- }
731
1011
 
732
- case 'rejected':
733
- {
734
- var rejectedThenable = thenable;
735
- throw rejectedThenable.reason;
736
- }
737
- }
1012
+ switch (thenable.status) {
1013
+ case 'fulfilled':
1014
+ {
1015
+ var fulfilledThenable = thenable;
1016
+ return fulfilledThenable.value;
1017
+ }
1018
+
1019
+ case 'rejected':
1020
+ {
1021
+ var rejectedThenable = thenable;
1022
+ throw rejectedThenable.reason;
1023
+ }
738
1024
  } // Suspend.
739
1025
  //
740
1026
  // Throwing here is an implementation detail that allows us to unwind the
@@ -770,40 +1056,37 @@ function getSuspendedThenable() {
770
1056
  var currentRequest$1 = null;
771
1057
  var thenableIndexCounter = 0;
772
1058
  var thenableState = null;
1059
+ var currentComponentDebugInfo = null;
773
1060
  function prepareToUseHooksForRequest(request) {
774
1061
  currentRequest$1 = request;
775
1062
  }
776
1063
  function resetHooksForRequest() {
777
1064
  currentRequest$1 = null;
778
1065
  }
779
- function prepareToUseHooksForComponent(prevThenableState) {
1066
+ function prepareToUseHooksForComponent(prevThenableState, componentDebugInfo) {
780
1067
  thenableIndexCounter = 0;
781
1068
  thenableState = prevThenableState;
1069
+
1070
+ {
1071
+ currentComponentDebugInfo = componentDebugInfo;
1072
+ }
782
1073
  }
783
1074
  function getThenableStateAfterSuspending() {
784
- var state = thenableState;
785
- thenableState = null;
786
- return state;
787
- }
1075
+ // If you use() to Suspend this should always exist but if you throw a Promise instead,
1076
+ // which is not really supported anymore, it will be empty. We use the empty set as a
1077
+ // marker to know if this was a replay of the same component or first attempt.
1078
+ var state = thenableState || createThenableState();
788
1079
 
789
- function readContext(context) {
790
1080
  {
791
- if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) {
792
- if (isClientReference(context)) {
793
- error('Cannot read a Client Context from a Server Component.');
794
- } else {
795
- error('Only createServerContext is supported in Server Components.');
796
- }
797
- }
798
-
799
- if (currentRequest$1 === null) {
800
- 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().');
801
- }
1081
+ // This is a hack but we stash the debug info here so that we don't need a completely
1082
+ // different data structure just for this in DEV. Not too happy about it.
1083
+ state._componentDebugInfo = currentComponentDebugInfo;
1084
+ currentComponentDebugInfo = null;
802
1085
  }
803
1086
 
804
- return readContext$1(context);
1087
+ thenableState = null;
1088
+ return state;
805
1089
  }
806
-
807
1090
  var HooksDispatcher = {
808
1091
  useMemo: function (nextCreate) {
809
1092
  return nextCreate();
@@ -814,8 +1097,8 @@ var HooksDispatcher = {
814
1097
  useDebugValue: function () {},
815
1098
  useDeferredValue: unsupportedHook,
816
1099
  useTransition: unsupportedHook,
817
- readContext: readContext,
818
- useContext: readContext,
1100
+ readContext: unsupportedContext,
1101
+ useContext: unsupportedContext,
819
1102
  useReducer: unsupportedHook,
820
1103
  useRef: unsupportedHook,
821
1104
  useState: unsupportedHook,
@@ -824,7 +1107,6 @@ var HooksDispatcher = {
824
1107
  useImperativeHandle: unsupportedHook,
825
1108
  useEffect: unsupportedHook,
826
1109
  useId: useId,
827
- useMutableSource: unsupportedHook,
828
1110
  useSyncExternalStore: unsupportedHook,
829
1111
  useCacheRefresh: function () {
830
1112
  return unsupportedRefresh;
@@ -849,6 +1131,10 @@ function unsupportedRefresh() {
849
1131
  throw new Error('Refreshing the cache is not supported in Server Components.');
850
1132
  }
851
1133
 
1134
+ function unsupportedContext() {
1135
+ throw new Error('Cannot read a Client Context from a Server Component.');
1136
+ }
1137
+
852
1138
  function useId() {
853
1139
  if (currentRequest$1 === null) {
854
1140
  throw new Error('useId can only be used while React is rendering');
@@ -874,24 +1160,22 @@ function use(usable) {
874
1160
  }
875
1161
 
876
1162
  return trackUsedThenable(thenableState, thenable, index);
877
- } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
878
- var context = usable;
879
- return readContext(context);
1163
+ } else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
1164
+ unsupportedContext();
880
1165
  }
881
1166
  }
882
1167
 
883
- {
884
- if (isClientReference(usable)) {
885
- error('Cannot use() an already resolved Client Reference.');
1168
+ if (isClientReference(usable)) {
1169
+ if (usable.value != null && usable.value.$$typeof === REACT_CONTEXT_TYPE) {
1170
+ // Show a more specific message since it's a common mistake.
1171
+ throw new Error('Cannot read a Client Context from a Server Component.');
1172
+ } else {
1173
+ throw new Error('Cannot use() an already resolved Client Reference.');
886
1174
  }
887
- } // eslint-disable-next-line react-internal/safe-string-coercion
888
-
889
-
890
- throw new Error('An unsupported type was passed to use(): ' + String(usable));
891
- }
892
-
893
- function createSignal() {
894
- return new AbortController().signal;
1175
+ } else {
1176
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
1177
+ 'An unsupported type was passed to use(): ' + String(usable));
1178
+ }
895
1179
  }
896
1180
 
897
1181
  function resolveCache() {
@@ -904,18 +1188,7 @@ function resolveCache() {
904
1188
  return new Map();
905
1189
  }
906
1190
 
907
- var DefaultCacheDispatcher = {
908
- getCacheSignal: function () {
909
- var cache = resolveCache();
910
- var entry = cache.get(createSignal);
911
-
912
- if (entry === undefined) {
913
- entry = createSignal();
914
- cache.set(createSignal, entry);
915
- }
916
-
917
- return entry;
918
- },
1191
+ var DefaultAsyncDispatcher = {
919
1192
  getCacheForType: function (resourceType) {
920
1193
  var cache = resolveCache();
921
1194
  var entry = cache.get(resourceType);
@@ -929,6 +1202,17 @@ var DefaultCacheDispatcher = {
929
1202
  return entry;
930
1203
  }
931
1204
  };
1205
+ var currentOwner = null;
1206
+
1207
+ {
1208
+ DefaultAsyncDispatcher.getOwner = function () {
1209
+ return currentOwner;
1210
+ };
1211
+ }
1212
+
1213
+ function setCurrentOwner(componentInfo) {
1214
+ currentOwner = componentInfo;
1215
+ }
932
1216
 
933
1217
  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
934
1218
 
@@ -936,6 +1220,8 @@ function isArray(a) {
936
1220
  return isArrayImpl(a);
937
1221
  }
938
1222
 
1223
+ var getPrototypeOf = Object.getPrototypeOf;
1224
+
939
1225
  // in case they error.
940
1226
 
941
1227
  var jsxPropsParents = new WeakMap();
@@ -954,7 +1240,7 @@ function isObjectPrototype(object) {
954
1240
  // still just a plain simple object.
955
1241
 
956
1242
 
957
- if (Object.getPrototypeOf(object)) {
1243
+ if (getPrototypeOf(object)) {
958
1244
  return false;
959
1245
  }
960
1246
 
@@ -970,7 +1256,7 @@ function isObjectPrototype(object) {
970
1256
  }
971
1257
 
972
1258
  function isSimpleObject(object) {
973
- if (!isObjectPrototype(Object.getPrototypeOf(object))) {
1259
+ if (!isObjectPrototype(getPrototypeOf(object))) {
974
1260
  return false;
975
1261
  }
976
1262
 
@@ -1023,6 +1309,10 @@ function describeValueForErrorMessage(value) {
1023
1309
  return '[...]';
1024
1310
  }
1025
1311
 
1312
+ if (value !== null && value.$$typeof === CLIENT_REFERENCE_TAG) {
1313
+ return describeClientReference();
1314
+ }
1315
+
1026
1316
  var name = objectName(value);
1027
1317
 
1028
1318
  if (name === 'Object') {
@@ -1033,7 +1323,15 @@ function describeValueForErrorMessage(value) {
1033
1323
  }
1034
1324
 
1035
1325
  case 'function':
1036
- return 'function';
1326
+ {
1327
+ if (value.$$typeof === CLIENT_REFERENCE_TAG) {
1328
+ return describeClientReference();
1329
+ }
1330
+
1331
+ var _name = value.displayName || value.name;
1332
+
1333
+ return _name ? 'function ' + _name : 'function';
1334
+ }
1037
1335
 
1038
1336
  default:
1039
1337
  // eslint-disable-next-line react-internal/safe-string-coercion
@@ -1079,6 +1377,12 @@ function describeElementType(type) {
1079
1377
  return '';
1080
1378
  }
1081
1379
 
1380
+ var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
1381
+
1382
+ function describeClientReference(ref) {
1383
+ return 'client';
1384
+ }
1385
+
1082
1386
  function describeObjectForErrorMessage(objectOrArray, expandedName) {
1083
1387
  var objKind = objectName(objectOrArray);
1084
1388
 
@@ -1104,7 +1408,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1104
1408
  if (typeof value === 'string') {
1105
1409
  substr = value;
1106
1410
  } else if (typeof value === 'object' && value !== null) {
1107
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1108
1411
  substr = '{' + describeObjectForErrorMessage(value) + '}';
1109
1412
  } else {
1110
1413
  substr = '{' + describeValueForErrorMessage(value) + '}';
@@ -1137,7 +1440,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1137
1440
  var _substr = void 0;
1138
1441
 
1139
1442
  if (typeof _value === 'object' && _value !== null) {
1140
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1141
1443
  _substr = describeObjectForErrorMessage(_value);
1142
1444
  } else {
1143
1445
  _substr = describeValueForErrorMessage(_value);
@@ -1159,6 +1461,8 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1159
1461
  } else {
1160
1462
  if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) {
1161
1463
  str = '<' + describeElementType(objectOrArray.type) + '/>';
1464
+ } else if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) {
1465
+ return describeClientReference();
1162
1466
  } else if (jsxPropsParents.has(objectOrArray)) {
1163
1467
  // Print JSX
1164
1468
  var _type = jsxPropsParents.get(objectOrArray);
@@ -1176,7 +1480,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1176
1480
  var _substr2 = void 0;
1177
1481
 
1178
1482
  if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) {
1179
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1180
1483
  _substr2 = describeObjectForErrorMessage(_value2);
1181
1484
  } else {
1182
1485
  _substr2 = describeValueForErrorMessage(_value2);
@@ -1210,20 +1513,19 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1210
1513
  str += ', ';
1211
1514
  }
1212
1515
 
1213
- var _name = _names[_i3];
1214
- str += describeKeyForErrorMessage(_name) + ': ';
1215
- var _value3 = _object[_name];
1516
+ var _name2 = _names[_i3];
1517
+ str += describeKeyForErrorMessage(_name2) + ': ';
1518
+ var _value3 = _object[_name2];
1216
1519
 
1217
1520
  var _substr3 = void 0;
1218
1521
 
1219
1522
  if (typeof _value3 === 'object' && _value3 !== null) {
1220
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1221
1523
  _substr3 = describeObjectForErrorMessage(_value3);
1222
1524
  } else {
1223
1525
  _substr3 = describeValueForErrorMessage(_value3);
1224
1526
  }
1225
1527
 
1226
- if (_name === expandedName) {
1528
+ if (_name2 === expandedName) {
1227
1529
  start = str.length;
1228
1530
  length = _substr3.length;
1229
1531
  str += _substr3;
@@ -1250,41 +1552,41 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1250
1552
  return '\n ' + str;
1251
1553
  }
1252
1554
 
1253
- var ContextRegistry = ReactSharedInternals.ContextRegistry;
1254
- function getOrCreateServerContext(globalName) {
1255
- if (!ContextRegistry[globalName]) {
1256
- ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value
1257
- REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED);
1258
- }
1259
-
1260
- return ContextRegistry[globalName];
1261
- }
1555
+ var ReactSharedInternals = ReactSharedInternalsServer;
1262
1556
 
1557
+ var ObjectPrototype = Object.prototype;
1558
+ var stringify = JSON.stringify; // Serializable values
1263
1559
  // Thenable<ReactClientValue>
1560
+ // task status
1264
1561
 
1265
1562
  var PENDING$1 = 0;
1266
1563
  var COMPLETED = 1;
1267
1564
  var ABORTED = 3;
1268
- var ERRORED$1 = 4;
1269
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1270
- var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache;
1565
+ var ERRORED$1 = 4; // object reference status
1566
+
1567
+ var SEEN_BUT_NOT_YET_OUTLINED = -1;
1568
+ var NEVER_OUTLINED = -2;
1271
1569
 
1272
1570
  function defaultErrorHandler(error) {
1273
1571
  console['error'](error); // Don't transform to our wrapper
1274
1572
  }
1275
1573
 
1574
+ function defaultPostponeHandler(reason) {// Noop
1575
+ }
1576
+
1276
1577
  var OPEN = 0;
1277
1578
  var CLOSING = 1;
1278
1579
  var CLOSED = 2;
1279
- function createRequest(model, bundlerConfig, onError, context, identifierPrefix) {
1280
- if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) {
1580
+ function createRequest(model, bundlerConfig, onError, identifierPrefix, onPostpone, environmentName) {
1581
+ if (ReactSharedInternals.A !== null && ReactSharedInternals.A !== DefaultAsyncDispatcher) {
1281
1582
  throw new Error('Currently React only supports one RSC renderer at a time.');
1282
1583
  }
1283
1584
 
1284
- prepareHostDispatcher();
1285
- ReactCurrentCache.current = DefaultCacheDispatcher;
1585
+ ReactSharedInternals.A = DefaultAsyncDispatcher;
1286
1586
  var abortSet = new Set();
1287
1587
  var pingedTasks = [];
1588
+ var cleanupQueue = [];
1589
+
1288
1590
  var hints = createHints();
1289
1591
  var request = {
1290
1592
  status: OPEN,
@@ -1296,27 +1598,29 @@ function createRequest(model, bundlerConfig, onError, context, identifierPrefix)
1296
1598
  nextChunkId: 0,
1297
1599
  pendingChunks: 0,
1298
1600
  hints: hints,
1601
+ abortListeners: new Set(),
1299
1602
  abortableTasks: abortSet,
1300
1603
  pingedTasks: pingedTasks,
1301
1604
  completedImportChunks: [],
1302
1605
  completedHintChunks: [],
1303
- completedJSONChunks: [],
1606
+ completedRegularChunks: [],
1304
1607
  completedErrorChunks: [],
1305
1608
  writtenSymbols: new Map(),
1306
1609
  writtenClientReferences: new Map(),
1307
1610
  writtenServerReferences: new Map(),
1308
- writtenProviders: new Map(),
1611
+ writtenObjects: new WeakMap(),
1309
1612
  identifierPrefix: identifierPrefix || '',
1310
1613
  identifierCount: 1,
1614
+ taintCleanupQueue: cleanupQueue,
1311
1615
  onError: onError === undefined ? defaultErrorHandler : onError,
1312
- // $FlowFixMe[missing-this-annot]
1313
- toJSON: function (key, value) {
1314
- return resolveModelToJSON(request, this, key, value);
1315
- }
1616
+ onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone
1316
1617
  };
1317
- request.pendingChunks++;
1318
- var rootContext = createRootContext(context);
1319
- var rootTask = createTask(request, model, rootContext, abortSet);
1618
+
1619
+ {
1620
+ request.environmentName = environmentName === undefined ? 'Server' : environmentName;
1621
+ }
1622
+
1623
+ var rootTask = createTask(request, model, null, false, abortSet);
1320
1624
  pingedTasks.push(rootTask);
1321
1625
  return request;
1322
1626
  }
@@ -1332,15 +1636,18 @@ function resolveRequest() {
1332
1636
  return null;
1333
1637
  }
1334
1638
 
1335
- function createRootContext(reqContext) {
1336
- return importServerContexts(reqContext);
1337
- }
1639
+ function serializeThenable(request, task, thenable) {
1640
+ var newTask = createTask(request, null, task.keyPath, // the server component sequence continues through Promise-as-a-child.
1641
+ task.implicitSlot, request.abortableTasks);
1338
1642
 
1339
- var POP = {};
1643
+ {
1644
+ // If this came from Flight, forward any debug info into this new row.
1645
+ var debugInfo = thenable._debugInfo;
1340
1646
 
1341
- function serializeThenable(request, thenable) {
1342
- request.pendingChunks++;
1343
- var newTask = createTask(request, null, getActiveContext(), request.abortableTasks);
1647
+ if (debugInfo) {
1648
+ forwardDebugInfo(request, newTask.id, debugInfo);
1649
+ }
1650
+ }
1344
1651
 
1345
1652
  switch (thenable.status) {
1346
1653
  case 'fulfilled':
@@ -1354,14 +1661,10 @@ function serializeThenable(request, thenable) {
1354
1661
  case 'rejected':
1355
1662
  {
1356
1663
  var x = thenable.reason;
1357
- var digest = logRecoverableError(request, x);
1358
1664
 
1359
1665
  {
1360
- var _getErrorMessageAndSt = getErrorMessageAndStackDev(x),
1361
- message = _getErrorMessageAndSt.message,
1362
- stack = _getErrorMessageAndSt.stack;
1363
-
1364
- emitErrorChunkDev(request, newTask.id, digest, message, stack);
1666
+ var digest = logRecoverableError(request, x);
1667
+ emitErrorChunk(request, newTask.id, digest, x);
1365
1668
  }
1366
1669
 
1367
1670
  return newTask.id;
@@ -1399,21 +1702,16 @@ function serializeThenable(request, thenable) {
1399
1702
  newTask.model = value;
1400
1703
  pingTask(request, newTask);
1401
1704
  }, function (reason) {
1402
- newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled
1403
-
1404
- var digest = logRecoverableError(request, reason);
1405
-
1406
1705
  {
1407
- var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason),
1408
- _message = _getErrorMessageAndSt2.message,
1409
- _stack = _getErrorMessageAndSt2.stack;
1706
+ newTask.status = ERRORED$1;
1410
1707
 
1411
- emitErrorChunkDev(request, newTask.id, digest, _message, _stack);
1412
- }
1708
+ var _digest = logRecoverableError(request, reason);
1413
1709
 
1414
- if (request.destination !== null) {
1415
- flushCompletedChunks(request, request.destination);
1710
+ emitErrorChunk(request, newTask.id, _digest, reason);
1416
1711
  }
1712
+
1713
+ request.abortableTasks.delete(newTask);
1714
+ enqueueFlush(request);
1417
1715
  });
1418
1716
  return newTask.id;
1419
1717
  }
@@ -1482,36 +1780,68 @@ function createLazyWrapperAroundWakeable(wakeable) {
1482
1780
  _payload: thenable,
1483
1781
  _init: readThenable
1484
1782
  };
1783
+
1784
+ {
1785
+ // If this came from React, transfer the debug info.
1786
+ lazyType._debugInfo = thenable._debugInfo || [];
1787
+ }
1788
+
1485
1789
  return lazyType;
1486
1790
  }
1487
1791
 
1488
- function attemptResolveElement(request, type, key, ref, props, prevThenableState) {
1489
- if (ref !== null && ref !== undefined) {
1490
- // When the ref moves to the regular props object this will implicitly
1491
- // throw for functions. We could probably relax it to a DEV warning for other
1492
- // cases.
1493
- throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
1494
- }
1792
+ function renderFunctionComponent(request, task, key, Component, props, owner) {
1793
+ // Reset the task's thenable state before continuing, so that if a later
1794
+ // component suspends we can reuse the same task object. If the same
1795
+ // component suspends again, the thenable state will be restored.
1796
+ var prevThenableState = task.thenableState;
1797
+ task.thenableState = null;
1798
+ var componentDebugInfo = null;
1495
1799
 
1496
1800
  {
1497
- jsxPropsParents.set(props, type);
1498
-
1499
- if (typeof props.children === 'object' && props.children !== null) {
1500
- jsxChildrenParents.set(props.children, type);
1801
+ if (debugID === null) {
1802
+ // We don't have a chunk to assign debug info. We need to outline this
1803
+ // component to assign it an ID.
1804
+ return outlineTask(request, task);
1805
+ } else if (prevThenableState !== null) {
1806
+ // This is a replay and we've already emitted the debug info of this component
1807
+ // in the first pass. We skip emitting a duplicate line.
1808
+ // As a hack we stashed the previous component debug info on this object in DEV.
1809
+ componentDebugInfo = prevThenableState._componentDebugInfo;
1810
+ } else {
1811
+ // This is a new component in the same task so we can emit more debug info.
1812
+ var componentName = Component.displayName || Component.name || '';
1813
+ request.pendingChunks++;
1814
+ var componentDebugID = debugID;
1815
+ componentDebugInfo = {
1816
+ name: componentName,
1817
+ env: request.environmentName,
1818
+ owner: owner
1819
+ }; // We outline this model eagerly so that we can refer to by reference as an owner.
1820
+ // If we had a smarter way to dedupe we might not have to do this if there ends up
1821
+ // being no references to this as an owner.
1822
+
1823
+ outlineModel(request, componentDebugInfo);
1824
+ emitDebugChunk(request, componentDebugID, componentDebugInfo);
1501
1825
  }
1502
1826
  }
1503
1827
 
1504
- if (typeof type === 'function') {
1505
- if (isClientReference(type)) {
1506
- // This is a reference to a Client Component.
1507
- return [REACT_ELEMENT_TYPE, type, key, props];
1508
- } // This is a server-side component.
1828
+ prepareToUseHooksForComponent(prevThenableState, componentDebugInfo); // The secondArg is always undefined in Server Components since refs error early.
1509
1829
 
1830
+ var secondArg = undefined;
1831
+ var result;
1832
+
1833
+ {
1834
+ setCurrentOwner(componentDebugInfo);
1510
1835
 
1511
- prepareToUseHooksForComponent(prevThenableState);
1512
- var result = type(props);
1836
+ try {
1837
+ result = Component(props, secondArg);
1838
+ } finally {
1839
+ setCurrentOwner(null);
1840
+ }
1841
+ }
1513
1842
 
1514
- if (typeof result === 'object' && result !== null && typeof result.then === 'function') {
1843
+ if (typeof result === 'object' && result !== null) {
1844
+ if (typeof result.then === 'function') {
1515
1845
  // When the return value is in children position we can resolve it immediately,
1516
1846
  // to its value without a wrapper if it's synchronously available.
1517
1847
  var thenable = result;
@@ -1522,29 +1852,228 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1522
1852
  // the thenable here.
1523
1853
 
1524
1854
 
1525
- return createLazyWrapperAroundWakeable(result);
1855
+ result = createLazyWrapperAroundWakeable(result);
1856
+ } // Normally we'd serialize an Iterator/AsyncIterator as a single-shot which is not compatible
1857
+ // to be rendered as a React Child. However, because we have the function to recreate
1858
+ // an iterable from rendering the element again, we can effectively treat it as multi-
1859
+ // shot. Therefore we treat this as an Iterable/AsyncIterable, whether it was one or not, by
1860
+ // adding a wrapper so that this component effectively renders down to an AsyncIterable.
1861
+
1862
+
1863
+ var iteratorFn = getIteratorFn(result);
1864
+
1865
+ if (iteratorFn) {
1866
+ var iterableChild = result;
1867
+ result = _defineProperty({}, Symbol.iterator, function () {
1868
+ var iterator = iteratorFn.call(iterableChild);
1869
+
1870
+ {
1871
+ // If this was an Iterator but not a GeneratorFunction we warn because
1872
+ // it might have been a mistake. Technically you can make this mistake with
1873
+ // GeneratorFunctions and even single-shot Iterables too but it's extra
1874
+ // tempting to try to return the value from a generator.
1875
+ if (iterator === iterableChild) {
1876
+ var isGeneratorComponent = // $FlowIgnore[method-unbinding]
1877
+ Object.prototype.toString.call(Component) === '[object GeneratorFunction]' && // $FlowIgnore[method-unbinding]
1878
+ Object.prototype.toString.call(iterableChild) === '[object Generator]';
1879
+
1880
+ if (!isGeneratorComponent) {
1881
+ error('Returning an Iterator from a Server Component is not supported ' + 'since it cannot be looped over more than once. ');
1882
+ }
1883
+ }
1884
+ }
1885
+
1886
+ return iterator;
1887
+ });
1888
+
1889
+ {
1890
+ result._debugInfo = iterableChild._debugInfo;
1891
+ }
1892
+ }
1893
+ } // Track this element's key on the Server Component on the keyPath context..
1894
+
1895
+
1896
+ var prevKeyPath = task.keyPath;
1897
+ var prevImplicitSlot = task.implicitSlot;
1898
+
1899
+ if (key !== null) {
1900
+ // Append the key to the path. Technically a null key should really add the child
1901
+ // index. We don't do that to hold the payload small and implementation simple.
1902
+ task.keyPath = prevKeyPath === null ? key : prevKeyPath + ',' + key;
1903
+ } else if (prevKeyPath === null) {
1904
+ // This sequence of Server Components has no keys. This means that it was rendered
1905
+ // in a slot that needs to assign an implicit key. Even if children below have
1906
+ // explicit keys, they should not be used for the outer most key since it might
1907
+ // collide with other slots in that set.
1908
+ task.implicitSlot = true;
1909
+ }
1910
+
1911
+ var json = renderModelDestructive(request, task, emptyRoot, '', result);
1912
+ task.keyPath = prevKeyPath;
1913
+ task.implicitSlot = prevImplicitSlot;
1914
+ return json;
1915
+ }
1916
+
1917
+ function renderFragment(request, task, children) {
1918
+ if (task.keyPath !== null) {
1919
+ // We have a Server Component that specifies a key but we're now splitting
1920
+ // the tree using a fragment.
1921
+ var fragment = [REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, task.keyPath, {
1922
+ children: children
1923
+ }];
1924
+
1925
+ if (!task.implicitSlot) {
1926
+ // If this was keyed inside a set. I.e. the outer Server Component was keyed
1927
+ // then we need to handle reorders of the whole set. To do this we need to wrap
1928
+ // this array in a keyed Fragment.
1929
+ return fragment;
1930
+ } // If the outer Server Component was implicit but then an inner one had a key
1931
+ // we don't actually need to be able to move the whole set around. It'll always be
1932
+ // in an implicit slot. The key only exists to be able to reset the state of the
1933
+ // children. We could achieve the same effect by passing on the keyPath to the next
1934
+ // set of components inside the fragment. This would also allow a keyless fragment
1935
+ // reconcile against a single child.
1936
+ // Unfortunately because of JSON.stringify, we can't call the recursive loop for
1937
+ // each child within this context because we can't return a set with already resolved
1938
+ // values. E.g. a string would get double encoded. Returning would pop the context.
1939
+ // So instead, we wrap it with an unkeyed fragment and inner keyed fragment.
1940
+
1941
+
1942
+ return [fragment];
1943
+ } // Since we're yielding here, that implicitly resets the keyPath context on the
1944
+ // way up. Which is what we want since we've consumed it. If this changes to
1945
+ // be recursive serialization, we need to reset the keyPath and implicitSlot,
1946
+ // before recursing here.
1947
+
1948
+
1949
+ {
1950
+ var debugInfo = children._debugInfo;
1951
+
1952
+ if (debugInfo) {
1953
+ // If this came from Flight, forward any debug info into this new row.
1954
+ if (debugID === null) {
1955
+ // We don't have a chunk to assign debug info. We need to outline this
1956
+ // component to assign it an ID.
1957
+ return outlineTask(request, task);
1958
+ } else {
1959
+ // Forward any debug info we have the first time we see it.
1960
+ // We do this after init so that we have received all the debug info
1961
+ // from the server by the time we emit it.
1962
+ forwardDebugInfo(request, debugID, debugInfo);
1963
+ } // Since we're rendering this array again, create a copy that doesn't
1964
+ // have the debug info so we avoid outlining or emitting debug info again.
1965
+
1966
+
1967
+ children = Array.from(children);
1968
+ }
1969
+ }
1970
+
1971
+ return children;
1972
+ }
1973
+
1974
+ function renderClientElement(task, type, key, props, owner) // DEV-only
1975
+ {
1976
+ // the keys of any Server Components which are not serialized.
1977
+
1978
+
1979
+ var keyPath = task.keyPath;
1980
+
1981
+ if (key === null) {
1982
+ key = keyPath;
1983
+ } else if (keyPath !== null) {
1984
+ key = keyPath + ',' + key;
1985
+ }
1986
+
1987
+ var element = [REACT_ELEMENT_TYPE, type, key, props, owner] ;
1988
+
1989
+ if (task.implicitSlot && key !== null) {
1990
+ // The root Server Component had no key so it was in an implicit slot.
1991
+ // If we had a key lower, it would end up in that slot with an explicit key.
1992
+ // We wrap the element in a fragment to give it an implicit key slot with
1993
+ // an inner explicit key.
1994
+ return [element];
1995
+ } // Since we're yielding here, that implicitly resets the keyPath context on the
1996
+ // way up. Which is what we want since we've consumed it. If this changes to
1997
+ // be recursive serialization, we need to reset the keyPath and implicitSlot,
1998
+ // before recursing here. We also need to reset it once we render into an array
1999
+ // or anything else too which we also get implicitly.
2000
+
2001
+
2002
+ return element;
2003
+ } // The chunk ID we're currently rendering that we can assign debug data to.
2004
+
2005
+
2006
+ var debugID = null;
2007
+
2008
+ function outlineTask(request, task) {
2009
+ var newTask = createTask(request, task.model, // the currently rendering element
2010
+ task.keyPath, // unlike outlineModel this one carries along context
2011
+ task.implicitSlot, request.abortableTasks);
2012
+ retryTask(request, newTask);
2013
+
2014
+ if (newTask.status === COMPLETED) {
2015
+ // We completed synchronously so we can refer to this by reference. This
2016
+ // makes it behaves the same as prod during deserialization.
2017
+ return serializeByValueID(newTask.id);
2018
+ } // This didn't complete synchronously so it wouldn't have even if we didn't
2019
+ // outline it, so this would reduce to a lazy reference even in prod.
2020
+
2021
+
2022
+ return serializeLazyID(newTask.id);
2023
+ }
2024
+
2025
+ function renderElement(request, task, type, key, ref, props, owner) // DEV only
2026
+ {
2027
+ if (ref !== null && ref !== undefined) {
2028
+ // When the ref moves to the regular props object this will implicitly
2029
+ // throw for functions. We could probably relax it to a DEV warning for other
2030
+ // cases.
2031
+ // TODO: `ref` is now just a prop when `enableRefAsProp` is on. Should we
2032
+ // do what the above comment says?
2033
+ throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
2034
+ }
2035
+
2036
+ {
2037
+ jsxPropsParents.set(props, type);
2038
+
2039
+ if (typeof props.children === 'object' && props.children !== null) {
2040
+ jsxChildrenParents.set(props.children, type);
1526
2041
  }
2042
+ }
2043
+
2044
+ if (typeof type === 'function') {
2045
+ if (isClientReference(type) || isTemporaryReference(type)) {
2046
+ // This is a reference to a Client Component.
2047
+ return renderClientElement(task, type, key, props, owner);
2048
+ } // This is a Server Component.
1527
2049
 
1528
- return result;
2050
+
2051
+ return renderFunctionComponent(request, task, key, type, props, owner);
1529
2052
  } else if (typeof type === 'string') {
1530
2053
  // This is a host element. E.g. HTML.
1531
- return [REACT_ELEMENT_TYPE, type, key, props];
2054
+ return renderClientElement(task, type, key, props, owner);
1532
2055
  } else if (typeof type === 'symbol') {
1533
- if (type === REACT_FRAGMENT_TYPE) {
2056
+ if (type === REACT_FRAGMENT_TYPE && key === null) {
1534
2057
  // For key-less fragments, we add a small optimization to avoid serializing
1535
2058
  // it as a wrapper.
1536
- // TODO: If a key is specified, we should propagate its key to any children.
1537
- // Same as if a Server Component has a key.
1538
- return props.children;
2059
+ var prevImplicitSlot = task.implicitSlot;
2060
+
2061
+ if (task.keyPath === null) {
2062
+ task.implicitSlot = true;
2063
+ }
2064
+
2065
+ var json = renderModelDestructive(request, task, emptyRoot, '', props.children);
2066
+ task.implicitSlot = prevImplicitSlot;
2067
+ return json;
1539
2068
  } // This might be a built-in React component. We'll let the client decide.
1540
2069
  // Any built-in works as long as its props are serializable.
1541
2070
 
1542
2071
 
1543
- return [REACT_ELEMENT_TYPE, type, key, props];
2072
+ return renderClientElement(task, type, key, props, owner);
1544
2073
  } else if (type != null && typeof type === 'object') {
1545
2074
  if (isClientReference(type)) {
1546
2075
  // This is a reference to a Client Component.
1547
- return [REACT_ELEMENT_TYPE, type, key, props];
2076
+ return renderClientElement(task, type, key, props, owner);
1548
2077
  }
1549
2078
 
1550
2079
  switch (type.$$typeof) {
@@ -1553,45 +2082,17 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1553
2082
  var payload = type._payload;
1554
2083
  var init = type._init;
1555
2084
  var wrappedType = init(payload);
1556
- return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState);
2085
+ return renderElement(request, task, wrappedType, key, ref, props, owner);
1557
2086
  }
1558
2087
 
1559
2088
  case REACT_FORWARD_REF_TYPE:
1560
2089
  {
1561
- var render = type.render;
1562
- prepareToUseHooksForComponent(prevThenableState);
1563
- return render(props, undefined);
2090
+ return renderFunctionComponent(request, task, key, type.render, props, owner);
1564
2091
  }
1565
2092
 
1566
2093
  case REACT_MEMO_TYPE:
1567
2094
  {
1568
- return attemptResolveElement(request, type.type, key, ref, props, prevThenableState);
1569
- }
1570
-
1571
- case REACT_PROVIDER_TYPE:
1572
- {
1573
- pushProvider(type._context, props.value);
1574
-
1575
- {
1576
- var extraKeys = Object.keys(props).filter(function (value) {
1577
- if (value === 'children' || value === 'value') {
1578
- return false;
1579
- }
1580
-
1581
- return true;
1582
- });
1583
-
1584
- if (extraKeys.length !== 0) {
1585
- error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys));
1586
- }
1587
- }
1588
-
1589
- return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider.
1590
- {
1591
- value: props.value,
1592
- children: props.children,
1593
- __pop: POP
1594
- }];
2095
+ return renderElement(request, task, type.type, key, ref, props, owner);
1595
2096
  }
1596
2097
  }
1597
2098
  }
@@ -1611,16 +2112,51 @@ function pingTask(request, task) {
1611
2112
  }
1612
2113
  }
1613
2114
 
1614
- function createTask(request, model, context, abortSet) {
2115
+ function createTask(request, model, keyPath, implicitSlot, abortSet) {
2116
+ request.pendingChunks++;
1615
2117
  var id = request.nextChunkId++;
2118
+
2119
+ if (typeof model === 'object' && model !== null) {
2120
+ // If we're about to write this into a new task we can assign it an ID early so that
2121
+ // any other references can refer to the value we're about to write.
2122
+ if ((keyPath !== null || implicitSlot)) ; else {
2123
+ request.writtenObjects.set(model, id);
2124
+ }
2125
+ }
2126
+
1616
2127
  var task = {
1617
2128
  id: id,
1618
2129
  status: PENDING$1,
1619
2130
  model: model,
1620
- context: context,
2131
+ keyPath: keyPath,
2132
+ implicitSlot: implicitSlot,
1621
2133
  ping: function () {
1622
2134
  return pingTask(request, task);
1623
2135
  },
2136
+ toJSON: function (parentPropertyName, value) {
2137
+ var parent = this; // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
2138
+
2139
+ {
2140
+ // $FlowFixMe[incompatible-use]
2141
+ var originalValue = parent[parentPropertyName];
2142
+
2143
+ if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
2144
+ if (objectName(originalValue) !== 'Object') {
2145
+ var jsxParentType = jsxChildrenParents.get(parent);
2146
+
2147
+ if (typeof jsxParentType === 'string') {
2148
+ error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
2149
+ } else {
2150
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
2151
+ }
2152
+ } else {
2153
+ 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));
2154
+ }
2155
+ }
2156
+ }
2157
+
2158
+ return renderModel(request, task, parent, parentPropertyName, value);
2159
+ },
1624
2160
  thenableState: null
1625
2161
  };
1626
2162
  abortSet.add(task);
@@ -1635,6 +2171,10 @@ function serializeLazyID(id) {
1635
2171
  return '$L' + id.toString(16);
1636
2172
  }
1637
2173
 
2174
+ function serializeInfinitePromise() {
2175
+ return '$@';
2176
+ }
2177
+
1638
2178
  function serializePromiseID(id) {
1639
2179
  return '$@' + id.toString(16);
1640
2180
  }
@@ -1643,12 +2183,12 @@ function serializeServerReferenceID(id) {
1643
2183
  return '$F' + id.toString(16);
1644
2184
  }
1645
2185
 
1646
- function serializeSymbolReference(name) {
1647
- return '$S' + name;
2186
+ function serializeTemporaryReferenceID(id) {
2187
+ return '$T' + id;
1648
2188
  }
1649
2189
 
1650
- function serializeProviderReference(name) {
1651
- return '$P' + name;
2190
+ function serializeSymbolReference(name) {
2191
+ return '$S' + name;
1652
2192
  }
1653
2193
 
1654
2194
  function serializeNumber(number) {
@@ -1683,13 +2223,23 @@ function serializeBigInt(n) {
1683
2223
  return '$n' + n.toString(10);
1684
2224
  }
1685
2225
 
1686
- function serializeClientReference(request, parent, key, clientReference) {
2226
+ function serializeRowHeader(tag, id) {
2227
+ return id.toString(16) + ':' + tag;
2228
+ }
2229
+
2230
+ function encodeReferenceChunk(request, id, reference) {
2231
+ var json = stringify(reference);
2232
+ var row = id.toString(16) + ':' + json + '\n';
2233
+ return stringToChunk(row);
2234
+ }
2235
+
2236
+ function serializeClientReference(request, parent, parentPropertyName, clientReference) {
1687
2237
  var clientReferenceKey = getClientReferenceKey(clientReference);
1688
2238
  var writtenClientReferences = request.writtenClientReferences;
1689
2239
  var existingId = writtenClientReferences.get(clientReferenceKey);
1690
2240
 
1691
2241
  if (existingId !== undefined) {
1692
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
2242
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1693
2243
  // If we're encoding the "type" of an element, we can refer
1694
2244
  // to that by a lazy reference instead of directly since React
1695
2245
  // knows how to deal with lazy values. This lets us suspend
@@ -1708,7 +2258,7 @@ function serializeClientReference(request, parent, key, clientReference) {
1708
2258
  emitImportChunk(request, importId, clientReferenceMetadata);
1709
2259
  writtenClientReferences.set(clientReferenceKey, importId);
1710
2260
 
1711
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
2261
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1712
2262
  // If we're encoding the "type" of an element, we can refer
1713
2263
  // to that by a lazy reference instead of directly since React
1714
2264
  // knows how to deal with lazy values. This lets us suspend
@@ -1722,20 +2272,20 @@ function serializeClientReference(request, parent, key, clientReference) {
1722
2272
  request.pendingChunks++;
1723
2273
  var errorId = request.nextChunkId++;
1724
2274
  var digest = logRecoverableError(request, x);
1725
-
1726
- {
1727
- var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x),
1728
- message = _getErrorMessageAndSt3.message,
1729
- stack = _getErrorMessageAndSt3.stack;
1730
-
1731
- emitErrorChunkDev(request, errorId, digest, message, stack);
1732
- }
1733
-
2275
+ emitErrorChunk(request, errorId, digest, x);
1734
2276
  return serializeByValueID(errorId);
1735
2277
  }
1736
2278
  }
1737
2279
 
1738
- function serializeServerReference(request, parent, key, serverReference) {
2280
+ function outlineModel(request, value) {
2281
+ var newTask = createTask(request, value, null, // The way we use outlining is for reusing an object.
2282
+ false, // It makes no sense for that use case to be contextual.
2283
+ request.abortableTasks);
2284
+ retryTask(request, newTask);
2285
+ return newTask.id;
2286
+ }
2287
+
2288
+ function serializeServerReference(request, serverReference) {
1739
2289
  var writtenServerReferences = request.writtenServerReferences;
1740
2290
  var existingId = writtenServerReferences.get(serverReference);
1741
2291
 
@@ -1748,15 +2298,74 @@ function serializeServerReference(request, parent, key, serverReference) {
1748
2298
  id: getServerReferenceId(request.bundlerConfig, serverReference),
1749
2299
  bound: bound ? Promise.resolve(bound) : null
1750
2300
  };
1751
- request.pendingChunks++;
1752
- var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend.
1753
-
1754
- var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata);
1755
- request.completedJSONChunks.push(processedChunk);
2301
+ var metadataId = outlineModel(request, serverReferenceMetadata);
1756
2302
  writtenServerReferences.set(serverReference, metadataId);
1757
2303
  return serializeServerReferenceID(metadataId);
1758
2304
  }
1759
2305
 
2306
+ function serializeTemporaryReference(request, temporaryReference) {
2307
+ var id = resolveTemporaryReferenceID(temporaryReference);
2308
+ return serializeTemporaryReferenceID(id);
2309
+ }
2310
+
2311
+ function serializeLargeTextString(request, text) {
2312
+ request.pendingChunks++;
2313
+ var textId = request.nextChunkId++;
2314
+ emitTextChunk(request, textId, text);
2315
+ return serializeByValueID(textId);
2316
+ }
2317
+
2318
+ function serializeMap(request, map) {
2319
+ var entries = Array.from(map);
2320
+
2321
+ for (var i = 0; i < entries.length; i++) {
2322
+ var key = entries[i][0];
2323
+
2324
+ if (typeof key === 'object' && key !== null) {
2325
+ var writtenObjects = request.writtenObjects;
2326
+ var existingId = writtenObjects.get(key);
2327
+
2328
+ if (existingId === undefined) {
2329
+ writtenObjects.set(key, SEEN_BUT_NOT_YET_OUTLINED);
2330
+ }
2331
+ }
2332
+ }
2333
+
2334
+ var id = outlineModel(request, entries);
2335
+ return '$Q' + id.toString(16);
2336
+ }
2337
+
2338
+ function serializeFormData(request, formData) {
2339
+ var entries = Array.from(formData.entries());
2340
+ var id = outlineModel(request, entries);
2341
+ return '$K' + id.toString(16);
2342
+ }
2343
+
2344
+ function serializeSet(request, set) {
2345
+ var entries = Array.from(set);
2346
+
2347
+ for (var i = 0; i < entries.length; i++) {
2348
+ var key = entries[i];
2349
+
2350
+ if (typeof key === 'object' && key !== null) {
2351
+ var writtenObjects = request.writtenObjects;
2352
+ var existingId = writtenObjects.get(key);
2353
+
2354
+ if (existingId === undefined) {
2355
+ writtenObjects.set(key, SEEN_BUT_NOT_YET_OUTLINED);
2356
+ }
2357
+ }
2358
+ }
2359
+
2360
+ var id = outlineModel(request, entries);
2361
+ return '$W' + id.toString(16);
2362
+ }
2363
+
2364
+ function serializeIterator(request, iterator) {
2365
+ var id = outlineModel(request, Array.from(iterator));
2366
+ return '$i' + id.toString(16);
2367
+ }
2368
+
1760
2369
  function escapeStringValue(value) {
1761
2370
  if (value[0] === '$') {
1762
2371
  // We need to escape $ prefixed strings since we use those to encode
@@ -1767,168 +2376,651 @@ function escapeStringValue(value) {
1767
2376
  }
1768
2377
  }
1769
2378
 
1770
- var insideContextProps = null;
1771
- var isInsideContextValue = false;
1772
- function resolveModelToJSON(request, parent, key, value) {
1773
- // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us
1774
- {
1775
- // $FlowFixMe[incompatible-use]
1776
- var originalValue = parent[key];
2379
+ var modelRoot = false;
2380
+
2381
+ function renderModel(request, task, parent, key, value) {
2382
+ var prevKeyPath = task.keyPath;
2383
+ var prevImplicitSlot = task.implicitSlot;
2384
+
2385
+ try {
2386
+ return renderModelDestructive(request, task, parent, key, value);
2387
+ } catch (thrownValue) {
2388
+ var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
2389
+ // reasons, the rest of the Suspense implementation expects the thrown
2390
+ // value to be a thenable, because before `use` existed that was the
2391
+ // (unstable) API for suspending. This implementation detail can change
2392
+ // later, once we deprecate the old API in favor of `use`.
2393
+ getSuspendedThenable() : thrownValue; // If the suspended/errored value was an element or lazy it can be reduced
2394
+ // to a lazy reference, so that it doesn't error the parent.
2395
+
2396
+ var model = task.model;
2397
+ var wasReactNode = typeof model === 'object' && model !== null && (model.$$typeof === REACT_ELEMENT_TYPE || model.$$typeof === REACT_LAZY_TYPE);
2398
+
2399
+ if (typeof x === 'object' && x !== null) {
2400
+ // $FlowFixMe[method-unbinding]
2401
+ if (typeof x.then === 'function') {
2402
+ // Something suspended, we'll need to create a new task and resolve it later.
2403
+ var newTask = createTask(request, task.model, task.keyPath, task.implicitSlot, request.abortableTasks);
2404
+ var ping = newTask.ping;
2405
+ x.then(ping, ping);
2406
+ newTask.thenableState = getThenableStateAfterSuspending(); // Restore the context. We assume that this will be restored by the inner
2407
+ // functions in case nothing throws so we don't use "finally" here.
2408
+
2409
+ task.keyPath = prevKeyPath;
2410
+ task.implicitSlot = prevImplicitSlot;
2411
+
2412
+ if (wasReactNode) {
2413
+ return serializeLazyID(newTask.id);
2414
+ }
2415
+
2416
+ return serializeByValueID(newTask.id);
2417
+ }
2418
+ } // Restore the context. We assume that this will be restored by the inner
2419
+ // functions in case nothing throws so we don't use "finally" here.
2420
+
2421
+
2422
+ task.keyPath = prevKeyPath;
2423
+ task.implicitSlot = prevImplicitSlot;
2424
+
2425
+ if (wasReactNode) {
2426
+ // Something errored. We'll still send everything we have up until this point.
2427
+ // We'll replace this element with a lazy reference that throws on the client
2428
+ // once it gets rendered.
2429
+ request.pendingChunks++;
2430
+ var errorId = request.nextChunkId++;
2431
+ var digest = logRecoverableError(request, x);
2432
+ emitErrorChunk(request, errorId, digest, x);
2433
+ return serializeLazyID(errorId);
2434
+ } // Something errored but it was not in a React Node. There's no need to serialize
2435
+ // it by value because it'll just error the whole parent row anyway so we can
2436
+ // just stop any siblings and error the whole parent row.
2437
+
2438
+
2439
+ throw x;
2440
+ }
2441
+ }
2442
+
2443
+ function renderModelDestructive(request, task, parent, parentPropertyName, value) {
2444
+ // Set the currently rendering model
2445
+ task.model = value; // Special Symbol, that's very common.
2446
+
2447
+ if (value === REACT_ELEMENT_TYPE) {
2448
+ return '$';
2449
+ }
2450
+
2451
+ if (value === null) {
2452
+ return null;
2453
+ }
2454
+
2455
+ if (typeof value === 'object') {
2456
+ switch (value.$$typeof) {
2457
+ case REACT_ELEMENT_TYPE:
2458
+ {
2459
+ var _writtenObjects = request.writtenObjects;
2460
+
2461
+ var _existingId = _writtenObjects.get(value);
2462
+
2463
+ if (_existingId !== undefined) {
2464
+ if ((task.keyPath !== null || task.implicitSlot)) ; else if (modelRoot === value) {
2465
+ // This is the ID we're currently emitting so we need to write it
2466
+ // once but if we discover it again, we refer to it by id.
2467
+ modelRoot = null;
2468
+ } else if (_existingId === SEEN_BUT_NOT_YET_OUTLINED) {
2469
+ // TODO: If we throw here we can treat this as suspending which causes an outline
2470
+ // but that is able to reuse the same task if we're already in one but then that
2471
+ // will be a lazy future value rather than guaranteed to exist but maybe that's good.
2472
+ var newId = outlineModel(request, value);
2473
+ return serializeByValueID(newId);
2474
+ } else {
2475
+ // We've already emitted this as an outlined object, so we can refer to that by its
2476
+ // existing ID. TODO: We should use a lazy reference since, unlike plain objects,
2477
+ // elements might suspend so it might not have emitted yet even if we have the ID for
2478
+ // it. However, this creates an extra wrapper when it's not needed. We should really
2479
+ // detect whether this already was emitted and synchronously available. In that
2480
+ // case we can refer to it synchronously and only make it lazy otherwise.
2481
+ // We currently don't have a data structure that lets us see that though.
2482
+ return serializeByValueID(_existingId);
2483
+ }
2484
+ } else {
2485
+ // This is the first time we've seen this object. We may never see it again
2486
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2487
+ _writtenObjects.set(value, SEEN_BUT_NOT_YET_OUTLINED); // The element's props are marked as "never outlined" so that they are inlined into
2488
+ // the same row as the element itself.
2489
+
2490
+
2491
+ _writtenObjects.set(value.props, NEVER_OUTLINED);
2492
+ }
2493
+
2494
+ var element = value;
1777
2495
 
1778
- if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
1779
- if (objectName(originalValue) !== 'Object') {
1780
- var jsxParentType = jsxChildrenParents.get(parent);
2496
+ {
2497
+ var debugInfo = value._debugInfo;
2498
+
2499
+ if (debugInfo) {
2500
+ // If this came from Flight, forward any debug info into this new row.
2501
+ if (debugID === null) {
2502
+ // We don't have a chunk to assign debug info. We need to outline this
2503
+ // component to assign it an ID.
2504
+ return outlineTask(request, task);
2505
+ } else {
2506
+ // Forward any debug info we have the first time we see it.
2507
+ forwardDebugInfo(request, debugID, debugInfo);
2508
+ }
2509
+ }
2510
+ }
2511
+
2512
+ var props = element.props;
2513
+ var ref;
2514
+
2515
+ {
2516
+ // TODO: This is a temporary, intermediate step. Once the feature
2517
+ // flag is removed, we should get the ref off the props object right
2518
+ // before using it.
2519
+ var refProp = props.ref;
2520
+ ref = refProp !== undefined ? refProp : null;
2521
+ } // Attempt to render the Server Component.
2522
+
2523
+
2524
+ return renderElement(request, task, element.type, // $FlowFixMe[incompatible-call] the key of an element is null | string
2525
+ element.key, ref, props, element._owner );
2526
+ }
1781
2527
 
1782
- if (typeof jsxParentType === 'string') {
1783
- error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
2528
+ case REACT_LAZY_TYPE:
2529
+ {
2530
+ // Reset the task's thenable state before continuing. If there was one, it was
2531
+ // from suspending the lazy before.
2532
+ task.thenableState = null;
2533
+ var lazy = value;
2534
+ var payload = lazy._payload;
2535
+ var init = lazy._init;
2536
+ var resolvedModel = init(payload);
2537
+
2538
+ {
2539
+ var _debugInfo = lazy._debugInfo;
2540
+
2541
+ if (_debugInfo) {
2542
+ // If this came from Flight, forward any debug info into this new row.
2543
+ if (debugID === null) {
2544
+ // We don't have a chunk to assign debug info. We need to outline this
2545
+ // component to assign it an ID.
2546
+ return outlineTask(request, task);
2547
+ } else {
2548
+ // Forward any debug info we have the first time we see it.
2549
+ // We do this after init so that we have received all the debug info
2550
+ // from the server by the time we emit it.
2551
+ forwardDebugInfo(request, debugID, _debugInfo);
2552
+ }
2553
+ }
2554
+ }
2555
+
2556
+ return renderModelDestructive(request, task, emptyRoot, '', resolvedModel);
2557
+ }
2558
+ }
2559
+
2560
+ if (isClientReference(value)) {
2561
+ return serializeClientReference(request, parent, parentPropertyName, value);
2562
+ }
2563
+
2564
+ var writtenObjects = request.writtenObjects;
2565
+ var existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
2566
+
2567
+ if (typeof value.then === 'function') {
2568
+ if (existingId !== undefined) {
2569
+ if ((task.keyPath !== null || task.implicitSlot)) {
2570
+ // If we're in some kind of context we can't reuse the result of this render or
2571
+ // previous renders of this element. We only reuse Promises if they're not wrapped
2572
+ // by another Server Component.
2573
+ var _promiseId = serializeThenable(request, task, value);
2574
+
2575
+ return serializePromiseID(_promiseId);
2576
+ } else if (modelRoot === value) {
2577
+ // This is the ID we're currently emitting so we need to write it
2578
+ // once but if we discover it again, we refer to it by id.
2579
+ modelRoot = null;
1784
2580
  } else {
1785
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
2581
+ // We've seen this promise before, so we can just refer to the same result.
2582
+ return serializePromiseID(existingId);
1786
2583
  }
1787
- } else {
1788
- 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));
2584
+ } // We assume that any object with a .then property is a "Thenable" type,
2585
+ // or a Promise type. Either of which can be represented by a Promise.
2586
+
2587
+
2588
+ var promiseId = serializeThenable(request, task, value);
2589
+ writtenObjects.set(value, promiseId);
2590
+ return serializePromiseID(promiseId);
2591
+ }
2592
+
2593
+ if (existingId !== undefined) {
2594
+ if (modelRoot === value) {
2595
+ // This is the ID we're currently emitting so we need to write it
2596
+ // once but if we discover it again, we refer to it by id.
2597
+ modelRoot = null;
2598
+ } else if (existingId === SEEN_BUT_NOT_YET_OUTLINED) {
2599
+ var _newId = outlineModel(request, value);
2600
+
2601
+ return serializeByValueID(_newId);
2602
+ } else if (existingId !== NEVER_OUTLINED) {
2603
+ // We've already emitted this as an outlined object, so we can
2604
+ // just refer to that by its existing ID.
2605
+ return serializeByValueID(existingId);
1789
2606
  }
2607
+ } else {
2608
+ // This is the first time we've seen this object. We may never see it again
2609
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2610
+ writtenObjects.set(value, SEEN_BUT_NOT_YET_OUTLINED);
1790
2611
  }
1791
- } // Special Symbols
1792
2612
 
2613
+ if (isArray(value)) {
2614
+ return renderFragment(request, task, value);
2615
+ }
1793
2616
 
1794
- switch (value) {
1795
- case REACT_ELEMENT_TYPE:
1796
- return '$';
1797
- }
2617
+ if (value instanceof Map) {
2618
+ return serializeMap(request, value);
2619
+ }
1798
2620
 
1799
- {
1800
- if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') {
1801
- insideContextProps = value;
1802
- } else if (insideContextProps === parent && key === 'value') {
1803
- isInsideContextValue = true;
1804
- } else if (insideContextProps === parent && key === 'children') {
1805
- isInsideContextValue = false;
2621
+ if (value instanceof Set) {
2622
+ return serializeSet(request, value);
2623
+ } // TODO: FormData is not available in old Node. Remove the typeof later.
2624
+
2625
+
2626
+ if (typeof FormData === 'function' && value instanceof FormData) {
2627
+ return serializeFormData(request, value);
1806
2628
  }
1807
- } // Resolve Server Components.
1808
2629
 
2630
+ var iteratorFn = getIteratorFn(value);
2631
+
2632
+ if (iteratorFn) {
2633
+ // TODO: Should we serialize the return value as well like we do for AsyncIterables?
2634
+ var iterator = iteratorFn.call(value);
2635
+
2636
+ if (iterator === value) {
2637
+ // Iterator, not Iterable
2638
+ return serializeIterator(request, iterator);
2639
+ }
2640
+
2641
+ return renderFragment(request, task, Array.from(iterator));
2642
+ }
2643
+
2644
+
2645
+ var proto = getPrototypeOf(value);
2646
+
2647
+ if (proto !== ObjectPrototype && (proto === null || getPrototypeOf(proto) !== null)) {
2648
+ 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.');
2649
+ }
1809
2650
 
1810
- while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) {
1811
2651
  {
1812
- if (isInsideContextValue) {
1813
- error('React elements are not allowed in ServerContext');
2652
+ if (objectName(value) !== 'Object') {
2653
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, parentPropertyName));
2654
+ } else if (!isSimpleObject(value)) {
2655
+ 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));
2656
+ } else if (Object.getOwnPropertySymbols) {
2657
+ var symbols = Object.getOwnPropertySymbols(value);
2658
+
2659
+ if (symbols.length > 0) {
2660
+ 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));
2661
+ }
1814
2662
  }
2663
+ } // $FlowFixMe[incompatible-return]
2664
+
2665
+
2666
+ return value;
2667
+ }
2668
+
2669
+ if (typeof value === 'string') {
2670
+
2671
+
2672
+ if (value[value.length - 1] === 'Z') {
2673
+ // Possibly a Date, whose toJSON automatically calls toISOString
2674
+ // $FlowFixMe[incompatible-use]
2675
+ var originalValue = parent[parentPropertyName];
2676
+
2677
+ if (originalValue instanceof Date) {
2678
+ return serializeDateFromDateJSON(value);
2679
+ }
2680
+ }
2681
+
2682
+ if (value.length >= 1024) {
2683
+ // For large strings, we encode them outside the JSON payload so that we
2684
+ // don't have to double encode and double parse the strings. This can also
2685
+ // be more compact in case the string has a lot of escaped characters.
2686
+ return serializeLargeTextString(request, value);
1815
2687
  }
1816
2688
 
2689
+ return escapeStringValue(value);
2690
+ }
2691
+
2692
+ if (typeof value === 'boolean') {
2693
+ return value;
2694
+ }
2695
+
2696
+ if (typeof value === 'number') {
2697
+ return serializeNumber(value);
2698
+ }
2699
+
2700
+ if (typeof value === 'undefined') {
2701
+ return serializeUndefined();
2702
+ }
2703
+
2704
+ if (typeof value === 'function') {
2705
+ if (isClientReference(value)) {
2706
+ return serializeClientReference(request, parent, parentPropertyName, value);
2707
+ }
2708
+
2709
+ if (isServerReference(value)) {
2710
+ return serializeServerReference(request, value);
2711
+ }
2712
+
2713
+ if (isTemporaryReference(value)) {
2714
+ return serializeTemporaryReference(request, value);
2715
+ }
2716
+
2717
+ if (/^on[A-Z]/.test(parentPropertyName)) {
2718
+ 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.');
2719
+ } else if ((jsxChildrenParents.has(parent) || jsxPropsParents.has(parent) && parentPropertyName === 'children')) {
2720
+ var componentName = value.displayName || value.name || 'Component';
2721
+ 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));
2722
+ } else {
2723
+ 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));
2724
+ }
2725
+ }
2726
+
2727
+ if (typeof value === 'symbol') {
2728
+ var writtenSymbols = request.writtenSymbols;
2729
+
2730
+ var _existingId2 = writtenSymbols.get(value);
2731
+
2732
+ if (_existingId2 !== undefined) {
2733
+ return serializeByValueID(_existingId2);
2734
+ } // $FlowFixMe[incompatible-type] `description` might be undefined
2735
+
2736
+
2737
+ var name = value.description;
2738
+
2739
+ if (Symbol.for(name) !== value) {
2740
+ 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
2741
+ value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, parentPropertyName));
2742
+ }
2743
+
2744
+ request.pendingChunks++;
2745
+ var symbolId = request.nextChunkId++;
2746
+ emitSymbolChunk(request, symbolId, name);
2747
+ writtenSymbols.set(value, symbolId);
2748
+ return serializeByValueID(symbolId);
2749
+ }
2750
+
2751
+ if (typeof value === 'bigint') {
2752
+
2753
+ return serializeBigInt(value);
2754
+ }
2755
+
2756
+ throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName));
2757
+ }
2758
+
2759
+ function logPostpone(request, reason) {
2760
+ var prevRequest = currentRequest;
2761
+ currentRequest = null;
2762
+
2763
+ try {
2764
+ var onPostpone = request.onPostpone;
2765
+
2766
+ if (supportsRequestStorage) {
2767
+ // Exit the request context while running callbacks.
2768
+ requestStorage.run(undefined, onPostpone, reason);
2769
+ }
2770
+ } finally {
2771
+ currentRequest = prevRequest;
2772
+ }
2773
+ }
2774
+
2775
+ function logRecoverableError(request, error) {
2776
+ var prevRequest = currentRequest;
2777
+ currentRequest = null;
2778
+ var errorDigest;
2779
+
2780
+ try {
2781
+ var onError = request.onError;
2782
+
2783
+ if (supportsRequestStorage) {
2784
+ // Exit the request context while running callbacks.
2785
+ errorDigest = requestStorage.run(undefined, onError, error);
2786
+ }
2787
+ } finally {
2788
+ currentRequest = prevRequest;
2789
+ }
2790
+
2791
+ if (errorDigest != null && typeof errorDigest !== 'string') {
2792
+ // eslint-disable-next-line react-internal/prod-error-codes
2793
+ throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
2794
+ }
2795
+
2796
+ return errorDigest || '';
2797
+ }
2798
+
2799
+ function fatalError(request, error) {
2800
+
2801
+
2802
+ if (request.destination !== null) {
2803
+ request.status = CLOSED;
2804
+ closeWithError(request.destination, error);
2805
+ } else {
2806
+ request.status = CLOSING;
2807
+ request.fatalError = error;
2808
+ }
2809
+ }
2810
+
2811
+ function emitPostponeChunk(request, id, postponeInstance) {
2812
+ var row;
2813
+
2814
+ {
2815
+ var reason = '';
2816
+ var stack = '';
2817
+
1817
2818
  try {
1818
- switch (value.$$typeof) {
1819
- case REACT_ELEMENT_TYPE:
1820
- {
1821
- // TODO: Concatenate keys of parents onto children.
1822
- var element = value; // Attempt to render the Server Component.
2819
+ // eslint-disable-next-line react-internal/safe-string-coercion
2820
+ reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion
1823
2821
 
1824
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null);
1825
- break;
1826
- }
2822
+ stack = String(postponeInstance.stack);
2823
+ } catch (x) {}
1827
2824
 
1828
- case REACT_LAZY_TYPE:
1829
- {
1830
- var payload = value._payload;
1831
- var init = value._init;
1832
- value = init(payload);
1833
- break;
1834
- }
1835
- }
1836
- } catch (thrownValue) {
1837
- var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
1838
- // reasons, the rest of the Suspense implementation expects the thrown
1839
- // value to be a thenable, because before `use` existed that was the
1840
- // (unstable) API for suspending. This implementation detail can change
1841
- // later, once we deprecate the old API in favor of `use`.
1842
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
1843
-
1844
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
1845
- // Something suspended, we'll need to create a new task and resolve it later.
1846
- request.pendingChunks++;
1847
- var newTask = createTask(request, value, getActiveContext(), request.abortableTasks);
1848
- var ping = newTask.ping;
1849
- x.then(ping, ping);
1850
- newTask.thenableState = getThenableStateAfterSuspending();
1851
- return serializeLazyID(newTask.id);
1852
- } else {
1853
- // Something errored. We'll still send everything we have up until this point.
1854
- // We'll replace this element with a lazy reference that throws on the client
1855
- // once it gets rendered.
1856
- request.pendingChunks++;
1857
- var errorId = request.nextChunkId++;
1858
- var digest = logRecoverableError(request, x);
2825
+ row = serializeRowHeader('P', id) + stringify({
2826
+ reason: reason,
2827
+ stack: stack
2828
+ }) + '\n';
2829
+ }
1859
2830
 
1860
- {
1861
- var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x),
1862
- message = _getErrorMessageAndSt4.message,
1863
- stack = _getErrorMessageAndSt4.stack;
2831
+ var processedChunk = stringToChunk(row);
2832
+ request.completedErrorChunks.push(processedChunk);
2833
+ }
1864
2834
 
1865
- emitErrorChunkDev(request, errorId, digest, message, stack);
1866
- }
2835
+ function emitErrorChunk(request, id, digest, error) {
2836
+ var errorInfo;
1867
2837
 
1868
- return serializeLazyID(errorId);
2838
+ {
2839
+ var message;
2840
+ var stack = '';
2841
+
2842
+ try {
2843
+ if (error instanceof Error) {
2844
+ // eslint-disable-next-line react-internal/safe-string-coercion
2845
+ message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
2846
+
2847
+ stack = String(error.stack);
2848
+ } else if (typeof error === 'object' && error !== null) {
2849
+ message = describeObjectForErrorMessage(error);
2850
+ } else {
2851
+ // eslint-disable-next-line react-internal/safe-string-coercion
2852
+ message = String(error);
1869
2853
  }
2854
+ } catch (x) {
2855
+ message = 'An error occurred but serializing the error message failed.';
1870
2856
  }
2857
+
2858
+ errorInfo = {
2859
+ digest: digest,
2860
+ message: message,
2861
+ stack: stack
2862
+ };
1871
2863
  }
1872
2864
 
2865
+ var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
2866
+ var processedChunk = stringToChunk(row);
2867
+ request.completedErrorChunks.push(processedChunk);
2868
+ }
2869
+
2870
+ function emitImportChunk(request, id, clientReferenceMetadata) {
2871
+ // $FlowFixMe[incompatible-type] stringify can return null
2872
+ var json = stringify(clientReferenceMetadata);
2873
+ var row = serializeRowHeader('I', id) + json + '\n';
2874
+ var processedChunk = stringToChunk(row);
2875
+ request.completedImportChunks.push(processedChunk);
2876
+ }
2877
+
2878
+ function emitHintChunk(request, code, model) {
2879
+ var json = stringify(model);
2880
+ var id = request.nextChunkId++;
2881
+ var row = serializeRowHeader('H' + code, id) + json + '\n';
2882
+ var processedChunk = stringToChunk(row);
2883
+ request.completedHintChunks.push(processedChunk);
2884
+ }
2885
+
2886
+ function emitSymbolChunk(request, id, name) {
2887
+ var symbolReference = serializeSymbolReference(name);
2888
+ var processedChunk = encodeReferenceChunk(request, id, symbolReference);
2889
+ request.completedImportChunks.push(processedChunk);
2890
+ }
2891
+
2892
+ function emitModelChunk(request, id, json) {
2893
+ var row = id.toString(16) + ':' + json + '\n';
2894
+ var processedChunk = stringToChunk(row);
2895
+ request.completedRegularChunks.push(processedChunk);
2896
+ }
2897
+
2898
+ function emitDebugChunk(request, id, debugInfo) {
2899
+ // use the full serialization that requires a task.
2900
+
2901
+
2902
+ var counter = {
2903
+ objectCount: 0
2904
+ };
2905
+
2906
+ function replacer(parentPropertyName, value) {
2907
+ return renderConsoleValue(request, counter, this, parentPropertyName, value);
2908
+ } // $FlowFixMe[incompatible-type] stringify can return null
2909
+
2910
+
2911
+ var json = stringify(debugInfo, replacer);
2912
+ var row = serializeRowHeader('D', id) + json + '\n';
2913
+ var processedChunk = stringToChunk(row);
2914
+ request.completedRegularChunks.push(processedChunk);
2915
+ }
2916
+
2917
+ function emitTextChunk(request, id, text) {
2918
+ request.pendingChunks++; // Extra chunk for the header.
2919
+
2920
+ var textChunk = stringToChunk(text);
2921
+ var binaryLength = byteLengthOfChunk(textChunk);
2922
+ var row = id.toString(16) + ':T' + binaryLength.toString(16) + ',';
2923
+ var headerChunk = stringToChunk(row);
2924
+ request.completedRegularChunks.push(headerChunk, textChunk);
2925
+ }
2926
+
2927
+ function serializeEval(source) {
2928
+
2929
+ return '$E' + source;
2930
+ } // This is a forked version of renderModel which should never error, never suspend and is limited
2931
+ // in the depth it can encode.
2932
+
2933
+
2934
+ function renderConsoleValue(request, counter, parent, parentPropertyName, value) {
2935
+ // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
2936
+ // $FlowFixMe[incompatible-use]
2937
+ var originalValue = parent[parentPropertyName];
2938
+
1873
2939
  if (value === null) {
1874
2940
  return null;
1875
2941
  }
1876
2942
 
1877
- if (typeof value === 'object') {
1878
- if (isClientReference(value)) {
1879
- return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding]
1880
- } else if (typeof value.then === 'function') {
1881
- // We assume that any object with a .then property is a "Thenable" type,
1882
- // or a Promise type. Either of which can be represented by a Promise.
1883
- var promiseId = serializeThenable(request, value);
1884
- return serializePromiseID(promiseId);
1885
- } else if (value.$$typeof === REACT_PROVIDER_TYPE) {
1886
- var providerKey = value._context._globalName;
1887
- var writtenProviders = request.writtenProviders;
1888
- var providerId = writtenProviders.get(key);
1889
-
1890
- if (providerId === undefined) {
1891
- request.pendingChunks++;
1892
- providerId = request.nextChunkId++;
1893
- writtenProviders.set(providerKey, providerId);
1894
- emitProviderChunk(request, providerId, providerKey);
1895
- }
2943
+ if (typeof value === 'object') {
2944
+ if (isClientReference(value)) {
2945
+ // We actually have this value on the client so we could import it.
2946
+ // This might be confusing though because on the Server it won't actually
2947
+ // be this value, so if you're debugging client references maybe you'd be
2948
+ // better with a place holder.
2949
+ return serializeClientReference(request, parent, parentPropertyName, value);
2950
+ }
2951
+
2952
+ if (counter.objectCount > 20) {
2953
+ // We've reached our max number of objects to serialize across the wire so we serialize this
2954
+ // object but no properties inside of it, as a place holder.
2955
+ return Array.isArray(value) ? [] : {};
2956
+ }
2957
+
2958
+ counter.objectCount++;
2959
+ var writtenObjects = request.writtenObjects;
2960
+ var existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
2961
+
2962
+ if (typeof value.then === 'function') {
2963
+ if (existingId !== undefined) {
2964
+ // We've seen this promise before, so we can just refer to the same result.
2965
+ return serializePromiseID(existingId);
2966
+ }
2967
+
2968
+ var thenable = value;
2969
+
2970
+ switch (thenable.status) {
2971
+ case 'fulfilled':
2972
+ {
2973
+ return serializePromiseID(outlineConsoleValue(request, counter, thenable.value));
2974
+ }
2975
+
2976
+ case 'rejected':
2977
+ {
2978
+ var x = thenable.reason;
2979
+ request.pendingChunks++;
2980
+ var errorId = request.nextChunkId++;
2981
+
2982
+ {
2983
+ // We don't log these errors since they didn't actually throw into Flight.
2984
+ var digest = '';
2985
+ emitErrorChunk(request, errorId, digest, x);
2986
+ }
2987
+
2988
+ return serializePromiseID(errorId);
2989
+ }
2990
+ } // If it hasn't already resolved (and been instrumented) we just encode an infinite
2991
+ // promise that will never resolve.
2992
+
2993
+
2994
+ return serializeInfinitePromise();
2995
+ }
1896
2996
 
1897
- return serializeByValueID(providerId);
1898
- } else if (value === POP) {
1899
- popProvider();
2997
+ if (existingId !== undefined && existingId >= 0) {
2998
+ // We've already emitted this as a real object, so we can
2999
+ // just refer to that by its existing ID.
3000
+ return serializeByValueID(existingId);
3001
+ }
1900
3002
 
1901
- {
1902
- insideContextProps = null;
1903
- isInsideContextValue = false;
1904
- }
3003
+ if (isArray(value)) {
3004
+ return value;
3005
+ }
1905
3006
 
1906
- return undefined;
3007
+ if (value instanceof Map) {
3008
+ return serializeMap(request, value);
1907
3009
  }
1908
3010
 
1909
- if (!isArray(value)) {
1910
- var iteratorFn = getIteratorFn(value);
3011
+ if (value instanceof Set) {
3012
+ return serializeSet(request, value);
3013
+ } // TODO: FormData is not available in old Node. Remove the typeof later.
1911
3014
 
1912
- if (iteratorFn) {
1913
- return Array.from(value);
1914
- }
3015
+
3016
+ if (typeof FormData === 'function' && value instanceof FormData) {
3017
+ return serializeFormData(request, value);
1915
3018
  }
1916
3019
 
1917
- {
1918
- if (value !== null && !isArray(value)) {
1919
- // Verify that this is a simple plain object.
1920
- if (objectName(value) !== 'Object') {
1921
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key));
1922
- } else if (!isSimpleObject(value)) {
1923
- 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));
1924
- } else if (Object.getOwnPropertySymbols) {
1925
- var symbols = Object.getOwnPropertySymbols(value);
1926
-
1927
- if (symbols.length > 0) {
1928
- 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));
1929
- }
1930
- }
1931
- }
3020
+ var iteratorFn = getIteratorFn(value);
3021
+
3022
+ if (iteratorFn) {
3023
+ return Array.from(value);
1932
3024
  } // $FlowFixMe[incompatible-return]
1933
3025
 
1934
3026
 
@@ -1936,17 +3028,20 @@ function resolveModelToJSON(request, parent, key, value) {
1936
3028
  }
1937
3029
 
1938
3030
  if (typeof value === 'string') {
1939
- // TODO: Maybe too clever. If we support URL there's no similar trick.
1940
3031
  if (value[value.length - 1] === 'Z') {
1941
3032
  // Possibly a Date, whose toJSON automatically calls toISOString
1942
- // $FlowFixMe[incompatible-use]
1943
- var _originalValue = parent[key]; // $FlowFixMe[method-unbinding]
1944
-
1945
- if (_originalValue instanceof Date) {
3033
+ if (originalValue instanceof Date) {
1946
3034
  return serializeDateFromDateJSON(value);
1947
3035
  }
1948
3036
  }
1949
3037
 
3038
+ if (value.length >= 1024) {
3039
+ // For large strings, we encode them outside the JSON payload so that we
3040
+ // don't have to double encode and double parse the strings. This can also
3041
+ // be more compact in case the string has a lot of escaped characters.
3042
+ return serializeLargeTextString(request, value);
3043
+ }
3044
+
1950
3045
  return escapeStringValue(value);
1951
3046
  }
1952
3047
 
@@ -1964,40 +3059,33 @@ function resolveModelToJSON(request, parent, key, value) {
1964
3059
 
1965
3060
  if (typeof value === 'function') {
1966
3061
  if (isClientReference(value)) {
1967
- return serializeClientReference(request, parent, key, value);
3062
+ return serializeClientReference(request, parent, parentPropertyName, value);
1968
3063
  }
1969
3064
 
1970
- if (isServerReference(value)) {
1971
- return serializeServerReference(request, parent, key, value);
1972
- }
3065
+ if (isTemporaryReference(value)) {
3066
+ return serializeTemporaryReference(request, value);
3067
+ } // Serialize the body of the function as an eval so it can be printed.
3068
+ // $FlowFixMe[method-unbinding]
1973
3069
 
1974
- if (/^on[A-Z]/.test(key)) {
1975
- 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.');
1976
- } else {
1977
- 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));
1978
- }
3070
+
3071
+ return serializeEval('(' + Function.prototype.toString.call(value) + ')');
1979
3072
  }
1980
3073
 
1981
3074
  if (typeof value === 'symbol') {
1982
3075
  var writtenSymbols = request.writtenSymbols;
1983
- var existingId = writtenSymbols.get(value);
1984
3076
 
1985
- if (existingId !== undefined) {
1986
- return serializeByValueID(existingId);
1987
- } // $FlowFixMe[incompatible-type] `description` might be undefined
3077
+ var _existingId3 = writtenSymbols.get(value);
1988
3078
 
3079
+ if (_existingId3 !== undefined) {
3080
+ return serializeByValueID(_existingId3);
3081
+ } // $FlowFixMe[incompatible-type] `description` might be undefined
1989
3082
 
1990
- var name = value.description;
1991
3083
 
1992
- if (Symbol.for(name) !== value) {
1993
- 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
1994
- value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key));
1995
- }
3084
+ var name = value.description; // We use the Symbol.for version if it's not a global symbol. Close enough.
1996
3085
 
1997
3086
  request.pendingChunks++;
1998
3087
  var symbolId = request.nextChunkId++;
1999
3088
  emitSymbolChunk(request, symbolId, name);
2000
- writtenSymbols.set(value, symbolId);
2001
3089
  return serializeByValueID(symbolId);
2002
3090
  }
2003
3091
 
@@ -2005,88 +3093,53 @@ function resolveModelToJSON(request, parent, key, value) {
2005
3093
  return serializeBigInt(value);
2006
3094
  }
2007
3095
 
2008
- throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key));
2009
- }
2010
-
2011
- function logRecoverableError(request, error) {
2012
- var onError = request.onError;
2013
- var errorDigest = onError(error);
2014
-
2015
- if (errorDigest != null && typeof errorDigest !== 'string') {
2016
- // eslint-disable-next-line react-internal/prod-error-codes
2017
- throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
2018
- }
2019
-
2020
- return errorDigest || '';
3096
+ return 'unknown type ' + typeof value;
2021
3097
  }
2022
3098
 
2023
- function getErrorMessageAndStackDev(error) {
2024
- {
2025
- var message;
2026
- var stack = '';
3099
+ function outlineConsoleValue(request, counter, model) {
2027
3100
 
3101
+ function replacer(parentPropertyName, value) {
2028
3102
  try {
2029
- if (error instanceof Error) {
2030
- // eslint-disable-next-line react-internal/safe-string-coercion
2031
- message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
2032
-
2033
- stack = String(error.stack);
2034
- } else {
2035
- message = 'Error: ' + error;
2036
- }
3103
+ return renderConsoleValue(request, counter, this, parentPropertyName, value);
2037
3104
  } catch (x) {
2038
- message = 'An error occurred but serializing the error message failed.';
3105
+ return 'unknown value';
2039
3106
  }
3107
+ } // $FlowFixMe[incompatible-type] stringify can return null
2040
3108
 
2041
- return {
2042
- message: message,
2043
- stack: stack
2044
- };
2045
- }
3109
+
3110
+ var json = stringify(model, replacer);
3111
+ request.pendingChunks++;
3112
+ var id = request.nextChunkId++;
3113
+ var row = id.toString(16) + ':' + json + '\n';
3114
+ var processedChunk = stringToChunk(row);
3115
+ request.completedRegularChunks.push(processedChunk);
3116
+ return id;
2046
3117
  }
2047
3118
 
2048
- function fatalError(request, error) {
2049
- // This is called outside error handling code such as if an error happens in React internals.
2050
- if (request.destination !== null) {
2051
- request.status = CLOSED;
2052
- closeWithError(request.destination, error);
2053
- } else {
2054
- request.status = CLOSING;
2055
- request.fatalError = error;
3119
+ function forwardDebugInfo(request, id, debugInfo) {
3120
+ for (var i = 0; i < debugInfo.length; i++) {
3121
+ request.pendingChunks++;
3122
+ emitDebugChunk(request, id, debugInfo[i]);
2056
3123
  }
2057
3124
  }
2058
3125
 
2059
- function emitErrorChunkProd(request, id, digest) {
2060
- var processedChunk = processErrorChunkProd();
2061
- request.completedErrorChunks.push(processedChunk);
2062
- }
3126
+ function emitChunk(request, task, value) {
3127
+ var id = task.id; // For certain types we have special types, we typically outlined them but
3128
+ // we can emit them directly for this row instead of through an indirection.
2063
3129
 
2064
- function emitErrorChunkDev(request, id, digest, message, stack) {
2065
- var processedChunk = processErrorChunkDev(request, id, digest, message, stack);
2066
- request.completedErrorChunks.push(processedChunk);
2067
- }
3130
+ if (typeof value === 'string') {
2068
3131
 
2069
- function emitImportChunk(request, id, clientReferenceMetadata) {
2070
- var processedChunk = processImportChunk(request, id, clientReferenceMetadata);
2071
- request.completedImportChunks.push(processedChunk);
2072
- }
3132
+ emitTextChunk(request, id, value);
3133
+ return;
3134
+ }
3135
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2073
3136
 
2074
- function emitHintChunk(request, code, model) {
2075
- var processedChunk = processHintChunk(request, request.nextChunkId++, code, model);
2076
- request.completedHintChunks.push(processedChunk);
2077
- }
2078
3137
 
2079
- function emitSymbolChunk(request, id, name) {
2080
- var symbolReference = serializeSymbolReference(name);
2081
- var processedChunk = processReferenceChunk(request, id, symbolReference);
2082
- request.completedImportChunks.push(processedChunk);
3138
+ var json = stringify(value, task.toJSON);
3139
+ emitModelChunk(request, task.id, json);
2083
3140
  }
2084
3141
 
2085
- function emitProviderChunk(request, id, contextName) {
2086
- var contextReference = serializeProviderReference(contextName);
2087
- var processedChunk = processReferenceChunk(request, id, contextReference);
2088
- request.completedJSONChunks.push(processedChunk);
2089
- }
3142
+ var emptyRoot = {};
2090
3143
 
2091
3144
  function retryTask(request, task) {
2092
3145
  if (task.status !== PENDING$1) {
@@ -2094,38 +3147,47 @@ function retryTask(request, task) {
2094
3147
  return;
2095
3148
  }
2096
3149
 
2097
- switchContext(task.context);
3150
+ var prevDebugID = debugID;
2098
3151
 
2099
3152
  try {
2100
- var value = task.model;
2101
-
2102
- if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2103
- // TODO: Concatenate keys of parents onto children.
2104
- var element = value; // When retrying a component, reuse the thenableState from the
2105
- // previous attempt.
2106
-
2107
- var prevThenableState = task.thenableState; // Attempt to render the Server Component.
2108
- // Doing this here lets us reuse this same task if the next component
2109
- // also suspends.
2110
-
2111
- task.model = value;
2112
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering
2113
- // using the same task, but we reset its thenable state before continuing.
2114
-
2115
- task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate
2116
- // from the render above because we don't need to reset the thenable state
2117
- // until the next time something suspends and retries.
2118
-
2119
- while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2120
- // TODO: Concatenate keys of parents onto children.
2121
- var nextElement = value;
2122
- task.model = value;
2123
- value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null);
2124
- }
3153
+ // Track the root so we know that we have to emit this object even though it
3154
+ // already has an ID. This is needed because we might see this object twice
3155
+ // in the same toJSON if it is cyclic.
3156
+ modelRoot = task.model;
3157
+
3158
+ if (true) {
3159
+ // Track the ID of the current task so we can assign debug info to this id.
3160
+ debugID = task.id;
3161
+ } // We call the destructive form that mutates this task. That way if something
3162
+ // suspends again, we can reuse the same task instead of spawning a new one.
3163
+
3164
+
3165
+ var resolvedModel = renderModelDestructive(request, task, emptyRoot, '', task.model);
3166
+
3167
+ if (true) {
3168
+ // We're now past rendering this task and future renders will spawn new tasks for their
3169
+ // debug info.
3170
+ debugID = null;
3171
+ } // Track the root again for the resolved object.
3172
+
3173
+
3174
+ modelRoot = resolvedModel; // The keyPath resets at any terminal child node.
3175
+
3176
+ task.keyPath = null;
3177
+ task.implicitSlot = false;
3178
+
3179
+ if (typeof resolvedModel === 'object' && resolvedModel !== null) {
3180
+ // Object might contain unresolved values like additional elements.
3181
+ // This is simulating what the JSON loop would do if this was part of it.
3182
+ emitChunk(request, task, resolvedModel);
3183
+ } else {
3184
+ // If the value is a string, it means it's a terminal value and we already escaped it
3185
+ // We don't need to escape it again so it's not passed the toJSON replacer.
3186
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
3187
+ var json = stringify(resolvedModel);
3188
+ emitModelChunk(request, task.id, json);
2125
3189
  }
2126
3190
 
2127
- var processedChunk = processModelChunk(request, task.id, value);
2128
- request.completedJSONChunks.push(processedChunk);
2129
3191
  request.abortableTasks.delete(task);
2130
3192
  task.status = COMPLETED;
2131
3193
  } catch (thrownValue) {
@@ -2134,33 +3196,33 @@ function retryTask(request, task) {
2134
3196
  // value to be a thenable, because before `use` existed that was the
2135
3197
  // (unstable) API for suspending. This implementation detail can change
2136
3198
  // later, once we deprecate the old API in favor of `use`.
2137
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
2138
-
2139
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
2140
- // Something suspended again, let's pick it back up later.
2141
- var ping = task.ping;
2142
- x.then(ping, ping);
2143
- task.thenableState = getThenableStateAfterSuspending();
2144
- return;
2145
- } else {
2146
- request.abortableTasks.delete(task);
2147
- task.status = ERRORED$1;
2148
- var digest = logRecoverableError(request, x);
2149
-
2150
- {
2151
- var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x),
2152
- message = _getErrorMessageAndSt5.message,
2153
- stack = _getErrorMessageAndSt5.stack;
3199
+ getSuspendedThenable() : thrownValue;
2154
3200
 
2155
- emitErrorChunkDev(request, task.id, digest, message, stack);
3201
+ if (typeof x === 'object' && x !== null) {
3202
+ // $FlowFixMe[method-unbinding]
3203
+ if (typeof x.then === 'function') {
3204
+ // Something suspended again, let's pick it back up later.
3205
+ var ping = task.ping;
3206
+ x.then(ping, ping);
3207
+ task.thenableState = getThenableStateAfterSuspending();
3208
+ return;
2156
3209
  }
2157
3210
  }
3211
+
3212
+ request.abortableTasks.delete(task);
3213
+ task.status = ERRORED$1;
3214
+ var digest = logRecoverableError(request, x);
3215
+ emitErrorChunk(request, task.id, digest, x);
3216
+ } finally {
3217
+ {
3218
+ debugID = prevDebugID;
3219
+ }
2158
3220
  }
2159
3221
  }
2160
3222
 
2161
3223
  function performWork(request) {
2162
- var prevDispatcher = ReactCurrentDispatcher.current;
2163
- ReactCurrentDispatcher.current = HooksDispatcher;
3224
+ var prevDispatcher = ReactSharedInternals.H;
3225
+ ReactSharedInternals.H = HooksDispatcher;
2164
3226
  var prevRequest = currentRequest;
2165
3227
  currentRequest = request;
2166
3228
  prepareToUseHooksForRequest(request);
@@ -2181,7 +3243,7 @@ function performWork(request) {
2181
3243
  logRecoverableError(request, error);
2182
3244
  fatalError(request, error);
2183
3245
  } finally {
2184
- ReactCurrentDispatcher.current = prevDispatcher;
3246
+ ReactSharedInternals.H = prevDispatcher;
2185
3247
  resetHooksForRequest();
2186
3248
  currentRequest = prevRequest;
2187
3249
  }
@@ -2192,7 +3254,7 @@ function abortTask(task, request, errorId) {
2192
3254
  // has a single value referencing the error.
2193
3255
 
2194
3256
  var ref = serializeByValueID(errorId);
2195
- var processedChunk = processReferenceChunk(request, task.id, ref);
3257
+ var processedChunk = encodeReferenceChunk(request, task.id, ref);
2196
3258
  request.completedErrorChunks.push(processedChunk);
2197
3259
  }
2198
3260
 
@@ -2236,12 +3298,12 @@ function flushCompletedChunks(request, destination) {
2236
3298
 
2237
3299
  hintChunks.splice(0, i); // Next comes model data.
2238
3300
 
2239
- var jsonChunks = request.completedJSONChunks;
3301
+ var regularChunks = request.completedRegularChunks;
2240
3302
  i = 0;
2241
3303
 
2242
- for (; i < jsonChunks.length; i++) {
3304
+ for (; i < regularChunks.length; i++) {
2243
3305
  request.pendingChunks--;
2244
- var _chunk2 = jsonChunks[i];
3306
+ var _chunk2 = regularChunks[i];
2245
3307
 
2246
3308
  var _keepWriting2 = writeChunkAndReturn(destination, _chunk2);
2247
3309
 
@@ -2252,7 +3314,7 @@ function flushCompletedChunks(request, destination) {
2252
3314
  }
2253
3315
  }
2254
3316
 
2255
- jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
3317
+ regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
2256
3318
  // any error messages and prioritize display of other parts of
2257
3319
  // the page.
2258
3320
 
@@ -2281,8 +3343,9 @@ function flushCompletedChunks(request, destination) {
2281
3343
  flushBuffered(destination);
2282
3344
 
2283
3345
  if (request.pendingChunks === 0) {
2284
- // We're done.
3346
+
2285
3347
  close$1(destination);
3348
+ request.destination = null;
2286
3349
  }
2287
3350
  }
2288
3351
 
@@ -2333,26 +3396,24 @@ function startFlowing(request, destination) {
2333
3396
  logRecoverableError(request, error);
2334
3397
  fatalError(request, error);
2335
3398
  }
3399
+ }
3400
+ function stopFlowing(request) {
3401
+ request.destination = null;
2336
3402
  } // This is called to early terminate a request. It creates an error at all pending tasks.
2337
3403
 
2338
3404
  function abort(request, reason) {
2339
3405
  try {
2340
- var abortableTasks = request.abortableTasks;
3406
+ var abortableTasks = request.abortableTasks; // We have tasks to abort. We'll emit one error row and then emit a reference
3407
+ // to that row from every row that's still remaining.
2341
3408
 
2342
3409
  if (abortableTasks.size > 0) {
2343
- // We have tasks to abort. We'll emit one error row and then emit a reference
2344
- // to that row from every row that's still remaining.
2345
- var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
2346
- var digest = logRecoverableError(request, error);
2347
3410
  request.pendingChunks++;
2348
3411
  var errorId = request.nextChunkId++;
2349
3412
 
2350
- if (true) {
2351
- var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error),
2352
- message = _getErrorMessageAndSt6.message,
2353
- stack = _getErrorMessageAndSt6.stack;
2354
-
2355
- emitErrorChunkDev(request, errorId, digest, message, stack);
3413
+ var postponeInstance; if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
3414
+ var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
3415
+ var digest = logRecoverableError(request, error);
3416
+ emitErrorChunk(request, errorId, digest, error);
2356
3417
  }
2357
3418
 
2358
3419
  abortableTasks.forEach(function (task) {
@@ -2361,6 +3422,21 @@ function abort(request, reason) {
2361
3422
  abortableTasks.clear();
2362
3423
  }
2363
3424
 
3425
+ var abortListeners = request.abortListeners;
3426
+
3427
+ if (abortListeners.size > 0) {
3428
+ var _error;
3429
+
3430
+ if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
3431
+ _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
3432
+ }
3433
+
3434
+ abortListeners.forEach(function (callback) {
3435
+ return callback(_error);
3436
+ });
3437
+ abortListeners.clear();
3438
+ }
3439
+
2364
3440
  if (request.destination !== null) {
2365
3441
  flushCompletedChunks(request, request.destination);
2366
3442
  }
@@ -2370,28 +3446,20 @@ function abort(request, reason) {
2370
3446
  }
2371
3447
  }
2372
3448
 
2373
- function importServerContexts(contexts) {
2374
- if (contexts) {
2375
- var prevContext = getActiveContext();
2376
- switchContext(rootContextSnapshot);
2377
-
2378
- for (var i = 0; i < contexts.length; i++) {
2379
- var _contexts$i = contexts[i],
2380
- name = _contexts$i[0],
2381
- value = _contexts$i[1];
2382
- var context = getOrCreateServerContext(name);
2383
- pushProvider(context, value);
2384
- }
2385
-
2386
- var importedContext = getActiveContext();
2387
- switchContext(prevContext);
2388
- return importedContext;
2389
- }
3449
+ // This is the parsed shape of the wire format which is why it is
3450
+ // condensed to only the essentialy information
3451
+ var ID = 0;
3452
+ var CHUNKS = 1;
3453
+ var NAME = 2; // export const ASYNC = 3;
3454
+ // This logic is correct because currently only include the 4th tuple member
3455
+ // when the module is async. If that changes we will need to actually assert
3456
+ // the value is true. We don't index into the 4th slot because flow does not
3457
+ // like the potential out of bounds access
2390
3458
 
2391
- return rootContextSnapshot;
3459
+ function isAsyncImport(metadata) {
3460
+ return metadata.length === 4;
2392
3461
  }
2393
3462
 
2394
- // eslint-disable-next-line no-unused-vars
2395
3463
  function resolveServerReference(bundlerConfig, id) {
2396
3464
  var name = '';
2397
3465
  var resolvedModuleData = bundlerConfig[id];
@@ -2417,19 +3485,38 @@ function resolveServerReference(bundlerConfig, id) {
2417
3485
  } // TODO: This needs to return async: true if it's an async module.
2418
3486
 
2419
3487
 
2420
- return {
2421
- id: resolvedModuleData.id,
2422
- chunks: resolvedModuleData.chunks,
2423
- name: name,
2424
- async: false
2425
- };
3488
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
2426
3489
  } // The chunk cache contains all the chunks we've preloaded so far.
2427
3490
  // If they're still pending they're a thenable. This map also exists
2428
3491
  // in Webpack but unfortunately it's not exposed so we have to
2429
3492
  // replicate it in user space. null means that it has already loaded.
2430
3493
 
2431
3494
  var chunkCache = new Map();
2432
- var asyncModuleCache = new Map();
3495
+
3496
+ function requireAsyncModule(id) {
3497
+ // We've already loaded all the chunks. We can require the module.
3498
+ var promise = __webpack_require__(id);
3499
+
3500
+ if (typeof promise.then !== 'function') {
3501
+ // This wasn't a promise after all.
3502
+ return null;
3503
+ } else if (promise.status === 'fulfilled') {
3504
+ // This module was already resolved earlier.
3505
+ return null;
3506
+ } else {
3507
+ // Instrument the Promise to stash the result.
3508
+ promise.then(function (value) {
3509
+ var fulfilledThenable = promise;
3510
+ fulfilledThenable.status = 'fulfilled';
3511
+ fulfilledThenable.value = value;
3512
+ }, function (reason) {
3513
+ var rejectedThenable = promise;
3514
+ rejectedThenable.status = 'rejected';
3515
+ rejectedThenable.reason = reason;
3516
+ });
3517
+ return promise;
3518
+ }
3519
+ }
2433
3520
 
2434
3521
  function ignoreReject() {// We rely on rejected promises to be handled by another listener.
2435
3522
  } // Start preloading the modules since we might need them soon.
@@ -2437,16 +3524,17 @@ function ignoreReject() {// We rely on rejected promises to be handled by anothe
2437
3524
 
2438
3525
 
2439
3526
  function preloadModule(metadata) {
2440
- var chunks = metadata.chunks;
3527
+ var chunks = metadata[CHUNKS];
2441
3528
  var promises = [];
3529
+ var i = 0;
2442
3530
 
2443
- for (var i = 0; i < chunks.length; i++) {
2444
- var chunkId = chunks[i];
3531
+ while (i < chunks.length) {
3532
+ var chunkId = chunks[i++];
3533
+ chunks[i++];
2445
3534
  var entry = chunkCache.get(chunkId);
2446
3535
 
2447
3536
  if (entry === undefined) {
2448
- var thenable = __webpack_chunk_load__(chunkId);
2449
-
3537
+ var thenable = loadChunk(chunkId);
2450
3538
  promises.push(thenable); // $FlowFixMe[method-unbinding]
2451
3539
 
2452
3540
  var resolve = chunkCache.set.bind(chunkCache, chunkId, null);
@@ -2457,30 +3545,13 @@ function preloadModule(metadata) {
2457
3545
  }
2458
3546
  }
2459
3547
 
2460
- if (metadata.async) {
2461
- var existingPromise = asyncModuleCache.get(metadata.id);
2462
-
2463
- if (existingPromise) {
2464
- if (existingPromise.status === 'fulfilled') {
2465
- return null;
2466
- }
2467
-
2468
- return existingPromise;
3548
+ if (isAsyncImport(metadata)) {
3549
+ if (promises.length === 0) {
3550
+ return requireAsyncModule(metadata[ID]);
2469
3551
  } else {
2470
- var modulePromise = Promise.all(promises).then(function () {
2471
- return __webpack_require__(metadata.id);
2472
- });
2473
- modulePromise.then(function (value) {
2474
- var fulfilledThenable = modulePromise;
2475
- fulfilledThenable.status = 'fulfilled';
2476
- fulfilledThenable.value = value;
2477
- }, function (reason) {
2478
- var rejectedThenable = modulePromise;
2479
- rejectedThenable.status = 'rejected';
2480
- rejectedThenable.reason = reason;
3552
+ return Promise.all(promises).then(function () {
3553
+ return requireAsyncModule(metadata[ID]);
2481
3554
  });
2482
- asyncModuleCache.set(metadata.id, modulePromise);
2483
- return modulePromise;
2484
3555
  }
2485
3556
  } else if (promises.length > 0) {
2486
3557
  return Promise.all(promises);
@@ -2491,35 +3562,34 @@ function preloadModule(metadata) {
2491
3562
  // Increase priority if necessary.
2492
3563
 
2493
3564
  function requireModule(metadata) {
2494
- var moduleExports;
3565
+ var moduleExports = __webpack_require__(metadata[ID]);
2495
3566
 
2496
- if (metadata.async) {
2497
- // We assume that preloadModule has been called before, which
2498
- // should have added something to the module cache.
2499
- var promise = asyncModuleCache.get(metadata.id);
2500
-
2501
- if (promise.status === 'fulfilled') {
2502
- moduleExports = promise.value;
3567
+ if (isAsyncImport(metadata)) {
3568
+ if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') {
3569
+ // This Promise should've been instrumented by preloadModule.
3570
+ moduleExports = moduleExports.value;
2503
3571
  } else {
2504
- throw promise.reason;
3572
+ throw moduleExports.reason;
2505
3573
  }
2506
- } else {
2507
- moduleExports = __webpack_require__(metadata.id);
2508
3574
  }
2509
3575
 
2510
- if (metadata.name === '*') {
3576
+ if (metadata[NAME] === '*') {
2511
3577
  // This is a placeholder value that represents that the caller imported this
2512
3578
  // as a CommonJS module as is.
2513
3579
  return moduleExports;
2514
3580
  }
2515
3581
 
2516
- if (metadata.name === '') {
3582
+ if (metadata[NAME] === '') {
2517
3583
  // This is a placeholder value that represents that the caller accessed the
2518
3584
  // default property of this if it was an ESM interop module.
2519
3585
  return moduleExports.__esModule ? moduleExports.default : moduleExports;
2520
3586
  }
2521
3587
 
2522
- return moduleExports[metadata.name];
3588
+ return moduleExports[metadata[NAME]];
3589
+ }
3590
+
3591
+ function loadChunk(chunkId, filename) {
3592
+ return __webpack_chunk_load__(chunkId);
2523
3593
  }
2524
3594
 
2525
3595
  // The server acts as a Client of itself when resolving Server References.
@@ -2662,11 +3732,11 @@ function resolveModelChunk(chunk, value) {
2662
3732
  }
2663
3733
  }
2664
3734
 
2665
- function bindArgs(fn, args) {
3735
+ function bindArgs$1(fn, args) {
2666
3736
  return fn.bind.apply(fn, [null].concat(args));
2667
3737
  }
2668
3738
 
2669
- function loadServerReference(response, id, bound, parentChunk, parentObject, key) {
3739
+ function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) {
2670
3740
  var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
2671
3741
  // the relevant modules already loaded but it allows for lazy loading of code
2672
3742
  // if needed.
@@ -2677,7 +3747,7 @@ function loadServerReference(response, id, bound, parentChunk, parentObject, key
2677
3747
  if (bound) {
2678
3748
  promise = Promise.all([bound, preloadPromise]).then(function (_ref) {
2679
3749
  var args = _ref[0];
2680
- return bindArgs(requireModule(serverReference), args);
3750
+ return bindArgs$1(requireModule(serverReference), args);
2681
3751
  });
2682
3752
  } else {
2683
3753
  if (preloadPromise) {
@@ -2807,7 +3877,22 @@ function createModelReject(chunk) {
2807
3877
  };
2808
3878
  }
2809
3879
 
2810
- function parseModelString(response, parentObject, key, value) {
3880
+ function getOutlinedModel(response, id) {
3881
+ var chunk = getChunk(response, id);
3882
+
3883
+ if (chunk.status === RESOLVED_MODEL) {
3884
+ initializeModelChunk(chunk);
3885
+ }
3886
+
3887
+ if (chunk.status !== INITIALIZED) {
3888
+ // We know that this is emitted earlier so otherwise it's an error.
3889
+ throw chunk.reason;
3890
+ }
3891
+
3892
+ return chunk.value;
3893
+ }
3894
+
3895
+ function parseModelString(response, obj, key, value) {
2811
3896
  if (value[0] === '$') {
2812
3897
  switch (value[1]) {
2813
3898
  case '$':
@@ -2819,36 +3904,46 @@ function parseModelString(response, parentObject, key, value) {
2819
3904
  case '@':
2820
3905
  {
2821
3906
  // Promise
2822
- var id = parseInt(value.slice(2), 16);
2823
- var chunk = getChunk(response, id);
2824
- return chunk;
2825
- }
3907
+ var _id = parseInt(value.slice(2), 16);
2826
3908
 
2827
- case 'S':
2828
- {
2829
- // Symbol
2830
- return Symbol.for(value.slice(2));
3909
+ var _chunk = getChunk(response, _id);
3910
+
3911
+ return _chunk;
2831
3912
  }
2832
3913
 
2833
3914
  case 'F':
2834
3915
  {
2835
3916
  // Server Reference
2836
- var _id = parseInt(value.slice(2), 16);
3917
+ var _id2 = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model.
2837
3918
 
2838
- var _chunk = getChunk(response, _id);
2839
3919
 
2840
- if (_chunk.status === RESOLVED_MODEL) {
2841
- initializeModelChunk(_chunk);
2842
- }
3920
+ var metaData = getOutlinedModel(response, _id2);
3921
+ return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, obj, key);
3922
+ }
3923
+
3924
+ case 'T':
3925
+ {
3926
+ // Temporary Reference
3927
+ return createTemporaryReference(value.slice(2));
3928
+ }
3929
+
3930
+ case 'Q':
3931
+ {
3932
+ // Map
3933
+ var _id3 = parseInt(value.slice(2), 16);
3934
+
3935
+ var data = getOutlinedModel(response, _id3);
3936
+ return new Map(data);
3937
+ }
2843
3938
 
2844
- if (_chunk.status !== INITIALIZED) {
2845
- // We know that this is emitted earlier so otherwise it's an error.
2846
- throw _chunk.reason;
2847
- } // TODO: Just encode this in the reference inline instead of as a model.
3939
+ case 'W':
3940
+ {
3941
+ // Set
3942
+ var _id4 = parseInt(value.slice(2), 16);
2848
3943
 
3944
+ var _data = getOutlinedModel(response, _id4);
2849
3945
 
2850
- var metaData = _chunk.value;
2851
- return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key);
3946
+ return new Set(_data);
2852
3947
  }
2853
3948
 
2854
3949
  case 'K':
@@ -2856,7 +3951,9 @@ function parseModelString(response, parentObject, key, value) {
2856
3951
  // FormData
2857
3952
  var stringId = value.slice(2);
2858
3953
  var formPrefix = response._prefix + stringId + '_';
2859
- var data = new FormData();
3954
+
3955
+ var _data2 = new FormData();
3956
+
2860
3957
  var backingFormData = response._formData; // We assume that the reference to FormData always comes after each
2861
3958
  // entry that it references so we can assume they all exist in the
2862
3959
  // backing store already.
@@ -2864,10 +3961,20 @@ function parseModelString(response, parentObject, key, value) {
2864
3961
 
2865
3962
  backingFormData.forEach(function (entry, entryKey) {
2866
3963
  if (entryKey.startsWith(formPrefix)) {
2867
- data.append(entryKey.slice(formPrefix.length), entry);
3964
+ _data2.append(entryKey.slice(formPrefix.length), entry);
2868
3965
  }
2869
3966
  });
2870
- return data;
3967
+ return _data2;
3968
+ }
3969
+
3970
+ case 'i':
3971
+ {
3972
+ // Iterator
3973
+ var _id5 = parseInt(value.slice(2), 16);
3974
+
3975
+ var _data3 = getOutlinedModel(response, _id5);
3976
+
3977
+ return _data3[Symbol.iterator]();
2871
3978
  }
2872
3979
 
2873
3980
  case 'I':
@@ -2910,37 +4017,31 @@ function parseModelString(response, parentObject, key, value) {
2910
4017
  // BigInt
2911
4018
  return BigInt(value.slice(2));
2912
4019
  }
4020
+ }
2913
4021
 
2914
- default:
2915
- {
2916
- // We assume that anything else is a reference ID.
2917
- var _id2 = parseInt(value.slice(1), 16);
2918
-
2919
- var _chunk2 = getChunk(response, _id2);
2920
-
2921
- switch (_chunk2.status) {
2922
- case RESOLVED_MODEL:
2923
- initializeModelChunk(_chunk2);
2924
- break;
2925
- } // The status might have changed after initialization.
2926
4022
 
4023
+ var id = parseInt(value.slice(1), 16);
4024
+ var chunk = getChunk(response, id);
2927
4025
 
2928
- switch (_chunk2.status) {
2929
- case INITIALIZED:
2930
- return _chunk2.value;
4026
+ switch (chunk.status) {
4027
+ case RESOLVED_MODEL:
4028
+ initializeModelChunk(chunk);
4029
+ break;
4030
+ } // The status might have changed after initialization.
2931
4031
 
2932
- case PENDING:
2933
- case BLOCKED:
2934
- var parentChunk = initializingChunk;
2935
4032
 
2936
- _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk));
4033
+ switch (chunk.status) {
4034
+ case INITIALIZED:
4035
+ return chunk.value;
2937
4036
 
2938
- return null;
4037
+ case PENDING:
4038
+ case BLOCKED:
4039
+ var parentChunk = initializingChunk;
4040
+ chunk.then(createModelResolver(parentChunk, obj, key), createModelReject(parentChunk));
4041
+ return null;
2939
4042
 
2940
- default:
2941
- throw _chunk2.reason;
2942
- }
2943
- }
4043
+ default:
4044
+ throw chunk.reason;
2944
4045
  }
2945
4046
  }
2946
4047
 
@@ -3012,14 +4113,144 @@ function close(response) {
3012
4113
  reportGlobalError(response, new Error('Connection closed.'));
3013
4114
  }
3014
4115
 
4116
+ function bindArgs(fn, args) {
4117
+ return fn.bind.apply(fn, [null].concat(args));
4118
+ }
4119
+
4120
+ function loadServerReference(bundlerConfig, id, bound) {
4121
+ var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
4122
+ // the relevant modules already loaded but it allows for lazy loading of code
4123
+ // if needed.
4124
+
4125
+ var preloadPromise = preloadModule(serverReference);
4126
+
4127
+ if (bound) {
4128
+ return Promise.all([bound, preloadPromise]).then(function (_ref) {
4129
+ var args = _ref[0];
4130
+ return bindArgs(requireModule(serverReference), args);
4131
+ });
4132
+ } else if (preloadPromise) {
4133
+ return Promise.resolve(preloadPromise).then(function () {
4134
+ return requireModule(serverReference);
4135
+ });
4136
+ } else {
4137
+ // Synchronously available
4138
+ return Promise.resolve(requireModule(serverReference));
4139
+ }
4140
+ }
4141
+
4142
+ function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) {
4143
+ // The data for this reference is encoded in multiple fields under this prefix.
4144
+ var actionResponse = createResponse(serverManifest, formFieldPrefix, body);
4145
+ close(actionResponse);
4146
+ var refPromise = getRoot(actionResponse); // Force it to initialize
4147
+ // $FlowFixMe
4148
+
4149
+ refPromise.then(function () {});
4150
+
4151
+ if (refPromise.status !== 'fulfilled') {
4152
+ // $FlowFixMe
4153
+ throw refPromise.reason;
4154
+ }
4155
+
4156
+ return refPromise.value;
4157
+ }
4158
+
4159
+ function decodeAction(body, serverManifest) {
4160
+ // We're going to create a new formData object that holds all the fields except
4161
+ // the implementation details of the action data.
4162
+ var formData = new FormData();
4163
+ var action = null; // $FlowFixMe[prop-missing]
4164
+
4165
+ body.forEach(function (value, key) {
4166
+ if (!key.startsWith('$ACTION_')) {
4167
+ formData.append(key, value);
4168
+ return;
4169
+ } // Later actions may override earlier actions if a button is used to override the default
4170
+ // form action.
4171
+
4172
+
4173
+ if (key.startsWith('$ACTION_REF_')) {
4174
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
4175
+ var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
4176
+ action = loadServerReference(serverManifest, metaData.id, metaData.bound);
4177
+ return;
4178
+ }
4179
+
4180
+ if (key.startsWith('$ACTION_ID_')) {
4181
+ var id = key.slice(11);
4182
+ action = loadServerReference(serverManifest, id, null);
4183
+ return;
4184
+ }
4185
+ });
4186
+
4187
+ if (action === null) {
4188
+ return null;
4189
+ } // Return the action with the remaining FormData bound to the first argument.
4190
+
4191
+
4192
+ return action.then(function (fn) {
4193
+ return fn.bind(null, formData);
4194
+ });
4195
+ }
4196
+ function decodeFormState(actionResult, body, serverManifest) {
4197
+ var keyPath = body.get('$ACTION_KEY');
4198
+
4199
+ if (typeof keyPath !== 'string') {
4200
+ // This form submission did not include any form state.
4201
+ return Promise.resolve(null);
4202
+ } // Search through the form data object to get the reference id and the number
4203
+ // of bound arguments. This repeats some of the work done in decodeAction.
4204
+
4205
+
4206
+ var metaData = null; // $FlowFixMe[prop-missing]
4207
+
4208
+ body.forEach(function (value, key) {
4209
+ if (key.startsWith('$ACTION_REF_')) {
4210
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
4211
+ metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
4212
+ } // We don't check for the simple $ACTION_ID_ case because form state actions
4213
+ // are always bound to the state argument.
4214
+
4215
+ });
4216
+
4217
+ if (metaData === null) {
4218
+ // Should be unreachable.
4219
+ return Promise.resolve(null);
4220
+ }
4221
+
4222
+ var referenceId = metaData.id;
4223
+ return Promise.resolve(metaData.bound).then(function (bound) {
4224
+ if (bound === null) {
4225
+ // Should be unreachable because form state actions are always bound to the
4226
+ // state argument.
4227
+ return null;
4228
+ } // The form action dispatch method is always bound to the initial state.
4229
+ // But when comparing signatures, we compare to the original unbound action.
4230
+ // Subtract one from the arity to account for this.
4231
+
4232
+
4233
+ var boundArity = bound.length - 1;
4234
+ return [actionResult, keyPath, referenceId, boundArity];
4235
+ });
4236
+ }
4237
+
3015
4238
  function createDrainHandler(destination, request) {
3016
4239
  return function () {
3017
4240
  return startFlowing(request, destination);
3018
4241
  };
3019
4242
  }
3020
4243
 
4244
+ function createCancelHandler(request, reason) {
4245
+ return function () {
4246
+ stopFlowing(request); // eslint-disable-next-line react-internal/prod-error-codes
4247
+
4248
+ abort(request, new Error(reason));
4249
+ };
4250
+ }
4251
+
3021
4252
  function renderToPipeableStream(model, webpackMap, options) {
3022
- var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined);
4253
+ var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, options ? options.environmentName : undefined);
3023
4254
  var hasStartedFlowing = false;
3024
4255
  startWork(request);
3025
4256
  return {
@@ -3031,6 +4262,8 @@ function renderToPipeableStream(model, webpackMap, options) {
3031
4262
  hasStartedFlowing = true;
3032
4263
  startFlowing(request, destination);
3033
4264
  destination.on('drain', createDrainHandler(destination, request));
4265
+ destination.on('error', createCancelHandler(request, 'The destination stream errored while writing data.'));
4266
+ destination.on('close', createCancelHandler(request, 'The destination stream closed early.'));
3034
4267
  return destination;
3035
4268
  },
3036
4269
  abort: function (reason) {
@@ -3085,7 +4318,8 @@ function decodeReplyFromBusboy(busboyStream, webpackMap) {
3085
4318
  close(response);
3086
4319
  });
3087
4320
  busboyStream.on('error', function (err) {
3088
- reportGlobalError(response, err);
4321
+ reportGlobalError(response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible
4322
+ err);
3089
4323
  });
3090
4324
  return getRoot(response);
3091
4325
  }
@@ -3098,12 +4332,18 @@ function decodeReply(body, webpackMap) {
3098
4332
  }
3099
4333
 
3100
4334
  var response = createResponse(webpackMap, '', body);
4335
+ var root = getRoot(response);
3101
4336
  close(response);
3102
- return getRoot(response);
4337
+ return root;
3103
4338
  }
3104
4339
 
4340
+ exports.createClientModuleProxy = createClientModuleProxy;
4341
+ exports.decodeAction = decodeAction;
4342
+ exports.decodeFormState = decodeFormState;
3105
4343
  exports.decodeReply = decodeReply;
3106
4344
  exports.decodeReplyFromBusboy = decodeReplyFromBusboy;
4345
+ exports.registerClientReference = registerClientReference;
4346
+ exports.registerServerReference = registerServerReference;
3107
4347
  exports.renderToPipeableStream = renderToPipeableStream;
3108
4348
  })();
3109
4349
  }