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
@@ -17,7 +17,27 @@ if (process.env.NODE_ENV !== "production") {
17
17
  var React = require('react');
18
18
  var ReactDOM = require('react-dom');
19
19
 
20
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
20
+ function _defineProperty(obj, key, value) {
21
+ if (key in obj) {
22
+ Object.defineProperty(obj, key, {
23
+ value: value,
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true
27
+ });
28
+ } else {
29
+ obj[key] = value;
30
+ }
31
+
32
+ return obj;
33
+ }
34
+
35
+ var ReactSharedInternalsServer = // $FlowFixMe: It's defined in the one we resolve to.
36
+ React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
37
+
38
+ if (!ReactSharedInternalsServer) {
39
+ 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.');
40
+ }
21
41
 
22
42
  function error(format) {
23
43
  {
@@ -35,8 +55,7 @@ function printWarning(level, format, args) {
35
55
  // When changing this logic, you might want to also
36
56
  // update consoleWithStackDev.www.js as well.
37
57
  {
38
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
39
- var stack = ReactDebugCurrentFrame.getStackAddendum();
58
+ var stack = ReactSharedInternalsServer.getStackAddendum();
40
59
 
41
60
  if (stack !== '') {
42
61
  format += '%s';
@@ -56,10 +75,13 @@ function printWarning(level, format, args) {
56
75
  }
57
76
  }
58
77
 
78
+ // -----------------------------------------------------------------------------
79
+ var enablePostpone = false;
80
+
59
81
  function scheduleWork(callback) {
60
82
  callback();
61
83
  }
62
- var VIEW_SIZE = 512;
84
+ var VIEW_SIZE = 2048;
63
85
  var currentView = null;
64
86
  var writtenBytes = 0;
65
87
  function beginWriting(destination) {
@@ -67,20 +89,14 @@ function beginWriting(destination) {
67
89
  writtenBytes = 0;
68
90
  }
69
91
  function writeChunk(destination, chunk) {
70
- if (chunk.length === 0) {
92
+ if (chunk.byteLength === 0) {
71
93
  return;
72
94
  }
73
95
 
74
- if (chunk.length > VIEW_SIZE) {
75
- {
76
- if (precomputedChunkSet.has(chunk)) {
77
- error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.');
78
- }
79
- } // this chunk may overflow a single view which implies it was not
96
+ if (chunk.byteLength > VIEW_SIZE) {
97
+ // this chunk may overflow a single view which implies it was not
80
98
  // one that is cached by the streaming renderer. We will enqueu
81
99
  // it directly and expect it is not re-used
82
-
83
-
84
100
  if (writtenBytes > 0) {
85
101
  destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
86
102
  currentView = new Uint8Array(VIEW_SIZE);
@@ -94,7 +110,7 @@ function writeChunk(destination, chunk) {
94
110
  var bytesToWrite = chunk;
95
111
  var allowableBytes = currentView.length - writtenBytes;
96
112
 
97
- if (allowableBytes < bytesToWrite.length) {
113
+ if (allowableBytes < bytesToWrite.byteLength) {
98
114
  // this chunk would overflow the current view. We enqueue a full view
99
115
  // and start a new view with the remaining chunk
100
116
  if (allowableBytes === 0) {
@@ -114,7 +130,7 @@ function writeChunk(destination, chunk) {
114
130
  }
115
131
 
116
132
  currentView.set(bytesToWrite, writtenBytes);
117
- writtenBytes += bytesToWrite.length;
133
+ writtenBytes += bytesToWrite.byteLength;
118
134
  }
119
135
  function writeChunkAndReturn(destination, chunk) {
120
136
  writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more
@@ -135,7 +151,9 @@ var textEncoder = new TextEncoder();
135
151
  function stringToChunk(content) {
136
152
  return textEncoder.encode(content);
137
153
  }
138
- var precomputedChunkSet = new Set() ;
154
+ function byteLengthOfChunk(chunk) {
155
+ return chunk.byteLength;
156
+ }
139
157
  function closeWithError(destination, error) {
140
158
  // $FlowFixMe[method-unbinding]
141
159
  if (typeof destination.error === 'function') {
@@ -152,65 +170,270 @@ function closeWithError(destination, error) {
152
170
  }
153
171
  }
154
172
 
155
- // This file is an intermediate layer to translate between Flight
156
- var stringify = JSON.stringify;
157
-
158
- function serializeRowHeader(tag, id) {
159
- return id.toString(16) + ':' + tag;
173
+ // eslint-disable-next-line no-unused-vars
174
+ var CLIENT_REFERENCE_TAG$1 = Symbol.for('react.client.reference');
175
+ var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
176
+ function isClientReference(reference) {
177
+ return reference.$$typeof === CLIENT_REFERENCE_TAG$1;
178
+ }
179
+ function isServerReference(reference) {
180
+ return reference.$$typeof === SERVER_REFERENCE_TAG;
181
+ }
182
+ function registerClientReference(proxyImplementation, id, exportName) {
183
+ return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false);
160
184
  }
161
185
 
162
- function processErrorChunkProd(request, id, digest) {
163
- {
164
- // These errors should never make it into a build so we don't need to encode them in codes.json
165
- // eslint-disable-next-line react-internal/prod-error-codes
166
- throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.');
186
+ function registerClientReferenceImpl(proxyImplementation, id, async) {
187
+ return Object.defineProperties(proxyImplementation, {
188
+ $$typeof: {
189
+ value: CLIENT_REFERENCE_TAG$1
190
+ },
191
+ $$id: {
192
+ value: id
193
+ },
194
+ $$async: {
195
+ value: async
196
+ }
197
+ });
198
+ } // $FlowFixMe[method-unbinding]
199
+
200
+
201
+ var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding]
202
+
203
+ var ArraySlice = Array.prototype.slice;
204
+
205
+ function bind() {
206
+ // $FlowFixMe[unsupported-syntax]
207
+ var newFn = FunctionBind.apply(this, arguments);
208
+
209
+ if (this.$$typeof === SERVER_REFERENCE_TAG) {
210
+ {
211
+ var thisBind = arguments[0];
212
+
213
+ if (thisBind != null) {
214
+ error('Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().');
215
+ }
216
+ }
217
+
218
+ var args = ArraySlice.call(arguments, 1);
219
+ return Object.defineProperties(newFn, {
220
+ $$typeof: {
221
+ value: SERVER_REFERENCE_TAG
222
+ },
223
+ $$id: {
224
+ value: this.$$id
225
+ },
226
+ $$bound: {
227
+ value: this.$$bound ? this.$$bound.concat(args) : args
228
+ },
229
+ bind: {
230
+ value: bind
231
+ }
232
+ });
167
233
  }
168
- }
169
- function processErrorChunkDev(request, id, digest, message, stack) {
170
234
 
171
- var errorInfo = {
172
- digest: digest,
173
- message: message,
174
- stack: stack
175
- };
176
- var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
177
- return stringToChunk(row);
178
- }
179
- function processModelChunk(request, id, model) {
180
- // $FlowFixMe[incompatible-type] stringify can return null
181
- var json = stringify(model, request.toJSON);
182
- var row = id.toString(16) + ':' + json + '\n';
183
- return stringToChunk(row);
235
+ return newFn;
184
236
  }
185
- function processReferenceChunk(request, id, reference) {
186
- var json = stringify(reference);
187
- var row = id.toString(16) + ':' + json + '\n';
188
- return stringToChunk(row);
237
+
238
+ function registerServerReference(reference, id, exportName) {
239
+ return Object.defineProperties(reference, {
240
+ $$typeof: {
241
+ value: SERVER_REFERENCE_TAG
242
+ },
243
+ $$id: {
244
+ value: exportName === null ? id : id + '#' + exportName,
245
+ configurable: true
246
+ },
247
+ $$bound: {
248
+ value: null,
249
+ configurable: true
250
+ },
251
+ bind: {
252
+ value: bind,
253
+ configurable: true
254
+ }
255
+ });
189
256
  }
190
- function processImportChunk(request, id, clientReferenceMetadata) {
191
- // $FlowFixMe[incompatible-type] stringify can return null
192
- var json = stringify(clientReferenceMetadata);
193
- var row = serializeRowHeader('I', id) + json + '\n';
194
- return stringToChunk(row);
257
+ var PROMISE_PROTOTYPE = Promise.prototype;
258
+ var deepProxyHandlers = {
259
+ get: function (target, name, receiver) {
260
+ switch (name) {
261
+ // These names are read by the Flight runtime if you end up using the exports object.
262
+ case '$$typeof':
263
+ // These names are a little too common. We should probably have a way to
264
+ // have the Flight runtime extract the inner target instead.
265
+ return target.$$typeof;
266
+
267
+ case '$$id':
268
+ return target.$$id;
269
+
270
+ case '$$async':
271
+ return target.$$async;
272
+
273
+ case 'name':
274
+ return target.name;
275
+
276
+ case 'displayName':
277
+ return undefined;
278
+ // We need to special case this because createElement reads it if we pass this
279
+ // reference.
280
+
281
+ case 'defaultProps':
282
+ return undefined;
283
+ // Avoid this attempting to be serialized.
284
+
285
+ case 'toJSON':
286
+ return undefined;
287
+
288
+ case Symbol.toPrimitive:
289
+ // $FlowFixMe[prop-missing]
290
+ return Object.prototype[Symbol.toPrimitive];
291
+
292
+ case Symbol.toStringTag:
293
+ // $FlowFixMe[prop-missing]
294
+ return Object.prototype[Symbol.toStringTag];
295
+
296
+ case 'Provider':
297
+ 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.");
298
+ } // eslint-disable-next-line react-internal/safe-string-coercion
299
+
300
+
301
+ var expression = String(target.name) + '.' + String(name);
302
+ 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.');
303
+ },
304
+ set: function () {
305
+ throw new Error('Cannot assign to a client module from a server module.');
306
+ }
307
+ };
308
+
309
+ function getReference(target, name) {
310
+ switch (name) {
311
+ // These names are read by the Flight runtime if you end up using the exports object.
312
+ case '$$typeof':
313
+ return target.$$typeof;
314
+
315
+ case '$$id':
316
+ return target.$$id;
317
+
318
+ case '$$async':
319
+ return target.$$async;
320
+
321
+ case 'name':
322
+ return target.name;
323
+ // We need to special case this because createElement reads it if we pass this
324
+ // reference.
325
+
326
+ case 'defaultProps':
327
+ return undefined;
328
+ // Avoid this attempting to be serialized.
329
+
330
+ case 'toJSON':
331
+ return undefined;
332
+
333
+ case Symbol.toPrimitive:
334
+ // $FlowFixMe[prop-missing]
335
+ return Object.prototype[Symbol.toPrimitive];
336
+
337
+ case Symbol.toStringTag:
338
+ // $FlowFixMe[prop-missing]
339
+ return Object.prototype[Symbol.toStringTag];
340
+
341
+ case '__esModule':
342
+ // Something is conditionally checking which export to use. We'll pretend to be
343
+ // an ESM compat module but then we'll check again on the client.
344
+ var moduleId = target.$$id;
345
+ target.default = registerClientReferenceImpl(function () {
346
+ 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.");
347
+ }, target.$$id + '#', target.$$async);
348
+ return true;
349
+
350
+ case 'then':
351
+ if (target.then) {
352
+ // Use a cached value
353
+ return target.then;
354
+ }
355
+
356
+ if (!target.$$async) {
357
+ // If this module is expected to return a Promise (such as an AsyncModule) then
358
+ // we should resolve that with a client reference that unwraps the Promise on
359
+ // the client.
360
+ var clientReference = registerClientReferenceImpl({}, target.$$id, true);
361
+ var proxy = new Proxy(clientReference, proxyHandlers$1); // Treat this as a resolved Promise for React's use()
362
+
363
+ target.status = 'fulfilled';
364
+ target.value = proxy;
365
+ var then = target.then = registerClientReferenceImpl(function then(resolve, reject) {
366
+ // Expose to React.
367
+ return Promise.resolve(resolve(proxy));
368
+ }, // If this is not used as a Promise but is treated as a reference to a `.then`
369
+ // export then we should treat it as a reference to that name.
370
+ target.$$id + '#then', false);
371
+ return then;
372
+ } else {
373
+ // Since typeof .then === 'function' is a feature test we'd continue recursing
374
+ // indefinitely if we return a function. Instead, we return an object reference
375
+ // if we check further.
376
+ return undefined;
377
+ }
378
+
379
+ }
380
+
381
+ if (typeof name === 'symbol') {
382
+ throw new Error('Cannot read Symbol exports. Only named exports are supported on a client module ' + 'imported on the server.');
383
+ }
384
+
385
+ var cachedReference = target[name];
386
+
387
+ if (!cachedReference) {
388
+ var reference = registerClientReferenceImpl(function () {
389
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
390
+ "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.");
391
+ }, target.$$id + '#' + name, target.$$async);
392
+ Object.defineProperty(reference, 'name', {
393
+ value: name
394
+ });
395
+ cachedReference = target[name] = new Proxy(reference, deepProxyHandlers);
396
+ }
397
+
398
+ return cachedReference;
195
399
  }
196
- function processHintChunk(request, id, code, model) {
197
- var json = stringify(model);
198
- var row = serializeRowHeader('H' + code, id) + json + '\n';
199
- return stringToChunk(row);
400
+
401
+ var proxyHandlers$1 = {
402
+ get: function (target, name, receiver) {
403
+ return getReference(target, name);
404
+ },
405
+ getOwnPropertyDescriptor: function (target, name) {
406
+ var descriptor = Object.getOwnPropertyDescriptor(target, name);
407
+
408
+ if (!descriptor) {
409
+ descriptor = {
410
+ value: getReference(target, name),
411
+ writable: false,
412
+ configurable: false,
413
+ enumerable: false
414
+ };
415
+ Object.defineProperty(target, name, descriptor);
416
+ }
417
+
418
+ return descriptor;
419
+ },
420
+ getPrototypeOf: function (target) {
421
+ // Pretend to be a Promise in case anyone asks.
422
+ return PROMISE_PROTOTYPE;
423
+ },
424
+ set: function () {
425
+ throw new Error('Cannot assign to a client module from a server module.');
426
+ }
427
+ };
428
+ function createClientModuleProxy(moduleId) {
429
+ var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import.
430
+ moduleId, false);
431
+ return new Proxy(clientReference, proxyHandlers$1);
200
432
  }
201
433
 
202
- // eslint-disable-next-line no-unused-vars
203
- var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
204
- var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
205
434
  function getClientReferenceKey(reference) {
206
435
  return reference.$$async ? reference.$$id + '#async' : reference.$$id;
207
436
  }
208
- function isClientReference(reference) {
209
- return reference.$$typeof === CLIENT_REFERENCE_TAG;
210
- }
211
- function isServerReference(reference) {
212
- return reference.$$typeof === SERVER_REFERENCE_TAG;
213
- }
214
437
  function resolveClientReferenceMetadata(config, clientReference) {
215
438
  var modulePath = clientReference.$$id;
216
439
  var name = '';
@@ -236,12 +459,11 @@ function resolveClientReferenceMetadata(config, clientReference) {
236
459
  }
237
460
  }
238
461
 
239
- return {
240
- id: resolvedModuleData.id,
241
- chunks: resolvedModuleData.chunks,
242
- name: name,
243
- async: !!clientReference.$$async
244
- };
462
+ if (clientReference.$$async === true) {
463
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1];
464
+ } else {
465
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
466
+ }
245
467
  }
246
468
  function getServerReferenceId(config, serverReference) {
247
469
  return serverReference.$$id;
@@ -250,339 +472,396 @@ function getServerReferenceBoundArguments(config, serverReference) {
250
472
  return serverReference.$$bound;
251
473
  }
252
474
 
253
- var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
254
-
255
- var ReactDOMFlightServerDispatcher = {
256
- prefetchDNS: prefetchDNS,
257
- preconnect: preconnect,
258
- preload: preload,
259
- preinit: preinit
475
+ var ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
476
+
477
+ var previousDispatcher = ReactDOMSharedInternals.d;
478
+ /* ReactDOMCurrentDispatcher */
479
+
480
+ ReactDOMSharedInternals.d
481
+ /* ReactDOMCurrentDispatcher */
482
+ = {
483
+ f
484
+ /* flushSyncWork */
485
+ : previousDispatcher.f
486
+ /* flushSyncWork */
487
+ ,
488
+ r
489
+ /* requestFormReset */
490
+ : previousDispatcher.r
491
+ /* requestFormReset */
492
+ ,
493
+ D
494
+ /* prefetchDNS */
495
+ : prefetchDNS,
496
+ C
497
+ /* preconnect */
498
+ : preconnect,
499
+ L
500
+ /* preload */
501
+ : preload,
502
+ m
503
+ /* preloadModule */
504
+ : preloadModule$1,
505
+ X
506
+ /* preinitScript */
507
+ : preinitScript,
508
+ S
509
+ /* preinitStyle */
510
+ : preinitStyle,
511
+ M
512
+ /* preinitModuleScript */
513
+ : preinitModuleScript
260
514
  };
261
515
 
262
- function prefetchDNS(href, options) {
263
- {
264
- if (typeof href === 'string') {
265
- var request = resolveRequest();
266
-
267
- if (request) {
268
- var hints = getHints(request);
269
- var key = 'D' + href;
270
-
271
- if (hints.has(key)) {
272
- // duplicate hint
273
- return;
274
- }
516
+ function prefetchDNS(href) {
517
+ if (typeof href === 'string' && href) {
518
+ var request = resolveRequest();
275
519
 
276
- hints.add(key);
520
+ if (request) {
521
+ var hints = getHints(request);
522
+ var key = 'D|' + href;
277
523
 
278
- if (options) {
279
- emitHint(request, 'D', [href, options]);
280
- } else {
281
- emitHint(request, 'D', href);
282
- }
524
+ if (hints.has(key)) {
525
+ // duplicate hint
526
+ return;
283
527
  }
528
+
529
+ hints.add(key);
530
+ emitHint(request, 'D', href);
531
+ } else {
532
+ previousDispatcher.D(
533
+ /* prefetchDNS */
534
+ href);
284
535
  }
285
536
  }
286
537
  }
287
538
 
288
- function preconnect(href, options) {
289
- {
290
- if (typeof href === 'string') {
291
- var request = resolveRequest();
539
+ function preconnect(href, crossOrigin) {
540
+ if (typeof href === 'string') {
541
+ var request = resolveRequest();
292
542
 
293
- if (request) {
294
- var hints = getHints(request);
295
- var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : '';
296
- var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href;
543
+ if (request) {
544
+ var hints = getHints(request);
545
+ var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href;
297
546
 
298
- if (hints.has(key)) {
299
- // duplicate hint
300
- return;
301
- }
547
+ if (hints.has(key)) {
548
+ // duplicate hint
549
+ return;
550
+ }
302
551
 
303
- hints.add(key);
552
+ hints.add(key);
304
553
 
305
- if (options) {
306
- emitHint(request, 'C', [href, options]);
307
- } else {
308
- emitHint(request, 'C', href);
309
- }
554
+ if (typeof crossOrigin === 'string') {
555
+ emitHint(request, 'C', [href, crossOrigin]);
556
+ } else {
557
+ emitHint(request, 'C', href);
310
558
  }
559
+ } else {
560
+ previousDispatcher.C(
561
+ /* preconnect */
562
+ href, crossOrigin);
311
563
  }
312
564
  }
313
565
  }
314
566
 
315
- function preload(href, options) {
316
- {
317
- if (typeof href === 'string') {
318
- var request = resolveRequest();
319
-
320
- if (request) {
321
- var hints = getHints(request);
322
- var key = 'L' + href;
567
+ function preload(href, as, options) {
568
+ if (typeof href === 'string') {
569
+ var request = resolveRequest();
323
570
 
324
- if (hints.has(key)) {
325
- // duplicate hint
326
- return;
327
- }
571
+ if (request) {
572
+ var hints = getHints(request);
573
+ var key = 'L';
328
574
 
329
- hints.add(key);
330
- emitHint(request, 'L', [href, options]);
575
+ if (as === 'image' && options) {
576
+ key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes);
577
+ } else {
578
+ key += "[" + as + "]" + href;
331
579
  }
332
- }
333
- }
334
- }
335
-
336
- function preinit(href, options) {
337
- {
338
- if (typeof href === 'string') {
339
- var request = resolveRequest();
340
580
 
341
- if (request) {
342
- var hints = getHints(request);
343
- var key = 'I' + href;
581
+ if (hints.has(key)) {
582
+ // duplicate hint
583
+ return;
584
+ }
344
585
 
345
- if (hints.has(key)) {
346
- // duplicate hint
347
- return;
348
- }
586
+ hints.add(key);
587
+ var trimmed = trimOptions(options);
349
588
 
350
- hints.add(key);
351
- emitHint(request, 'I', [href, options]);
589
+ if (trimmed) {
590
+ emitHint(request, 'L', [href, as, trimmed]);
591
+ } else {
592
+ emitHint(request, 'L', [href, as]);
352
593
  }
594
+ } else {
595
+ previousDispatcher.L(
596
+ /* preload */
597
+ href, as, options);
353
598
  }
354
599
  }
355
600
  }
356
601
 
357
- var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher;
358
- function prepareHostDispatcher() {
359
- ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher;
360
- } // Used to distinguish these contexts from ones used in other renderers.
361
- function createHints() {
362
- return new Set();
363
- }
602
+ function preloadModule$1(href, options) {
603
+ if (typeof href === 'string') {
604
+ var request = resolveRequest();
364
605
 
365
- // ATTENTION
366
- // When adding new symbols to this file,
367
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
368
- // The Symbol used to tag the ReactElement-like types.
369
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
370
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
371
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
372
- var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
373
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
374
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
375
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
376
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
377
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
378
- var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
379
- var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
380
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
381
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
382
- function getIteratorFn(maybeIterable) {
383
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
384
- return null;
385
- }
606
+ if (request) {
607
+ var hints = getHints(request);
608
+ var key = 'm|' + href;
386
609
 
387
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
610
+ if (hints.has(key)) {
611
+ // duplicate hint
612
+ return;
613
+ }
388
614
 
389
- if (typeof maybeIterator === 'function') {
390
- return maybeIterator;
391
- }
615
+ hints.add(key);
616
+ var trimmed = trimOptions(options);
392
617
 
393
- return null;
618
+ if (trimmed) {
619
+ return emitHint(request, 'm', [href, trimmed]);
620
+ } else {
621
+ return emitHint(request, 'm', href);
622
+ }
623
+ } else {
624
+ previousDispatcher.m(
625
+ /* preloadModule */
626
+ href, options);
627
+ }
628
+ }
394
629
  }
395
630
 
396
- var rendererSigil;
397
-
398
- {
399
- // Use this to detect multiple renderers using the same context
400
- rendererSigil = {};
401
- } // Used to store the parent path of all context overrides in a shared linked list.
402
- // Forming a reverse tree.
403
- // The structure of a context snapshot is an implementation of this file.
404
- // Currently, it's implemented as tracking the current active node.
631
+ function preinitStyle(href, precedence, options) {
632
+ if (typeof href === 'string') {
633
+ var request = resolveRequest();
405
634
 
635
+ if (request) {
636
+ var hints = getHints(request);
637
+ var key = 'S|' + href;
406
638
 
407
- var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
408
- // This global (actually thread local) state represents what state all those "current",
409
- // fields are currently in.
639
+ if (hints.has(key)) {
640
+ // duplicate hint
641
+ return;
642
+ }
410
643
 
411
- var currentActiveSnapshot = null;
644
+ hints.add(key);
645
+ var trimmed = trimOptions(options);
412
646
 
413
- function popNode(prev) {
414
- {
415
- prev.context._currentValue = prev.parentValue;
647
+ if (trimmed) {
648
+ return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]);
649
+ } else if (typeof precedence === 'string') {
650
+ return emitHint(request, 'S', [href, precedence]);
651
+ } else {
652
+ return emitHint(request, 'S', href);
653
+ }
654
+ } else {
655
+ previousDispatcher.S(
656
+ /* preinitStyle */
657
+ href, precedence, options);
658
+ }
416
659
  }
417
660
  }
418
661
 
419
- function pushNode(next) {
420
- {
421
- next.context._currentValue = next.value;
422
- }
423
- }
662
+ function preinitScript(src, options) {
663
+ if (typeof src === 'string') {
664
+ var request = resolveRequest();
424
665
 
425
- function popToNearestCommonAncestor(prev, next) {
426
- if (prev === next) ; else {
427
- popNode(prev);
428
- var parentPrev = prev.parent;
429
- var parentNext = next.parent;
666
+ if (request) {
667
+ var hints = getHints(request);
668
+ var key = 'X|' + src;
430
669
 
431
- if (parentPrev === null) {
432
- if (parentNext !== null) {
433
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
434
- }
435
- } else {
436
- if (parentNext === null) {
437
- throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
670
+ if (hints.has(key)) {
671
+ // duplicate hint
672
+ return;
438
673
  }
439
674
 
440
- popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common.
675
+ hints.add(key);
676
+ var trimmed = trimOptions(options);
441
677
 
442
- pushNode(next);
678
+ if (trimmed) {
679
+ return emitHint(request, 'X', [src, trimmed]);
680
+ } else {
681
+ return emitHint(request, 'X', src);
682
+ }
683
+ } else {
684
+ previousDispatcher.X(
685
+ /* preinitScript */
686
+ src, options);
443
687
  }
444
688
  }
445
689
  }
446
690
 
447
- function popAllPrevious(prev) {
448
- popNode(prev);
449
- var parentPrev = prev.parent;
691
+ function preinitModuleScript(src, options) {
692
+ if (typeof src === 'string') {
693
+ var request = resolveRequest();
450
694
 
451
- if (parentPrev !== null) {
452
- popAllPrevious(parentPrev);
453
- }
454
- }
695
+ if (request) {
696
+ var hints = getHints(request);
697
+ var key = 'M|' + src;
455
698
 
456
- function pushAllNext(next) {
457
- var parentNext = next.parent;
699
+ if (hints.has(key)) {
700
+ // duplicate hint
701
+ return;
702
+ }
458
703
 
459
- if (parentNext !== null) {
460
- pushAllNext(parentNext);
704
+ hints.add(key);
705
+ var trimmed = trimOptions(options);
706
+
707
+ if (trimmed) {
708
+ return emitHint(request, 'M', [src, trimmed]);
709
+ } else {
710
+ return emitHint(request, 'M', src);
711
+ }
712
+ } else {
713
+ previousDispatcher.M(
714
+ /* preinitModuleScript */
715
+ src, options);
716
+ }
717
+ }
718
+ } // Flight normally encodes undefined as a special character however for directive option
719
+ // arguments we don't want to send unnecessary keys and bloat the payload so we create a
720
+ // trimmed object which omits any keys with null or undefined values.
721
+ // This is only typesafe because these option objects have entirely optional fields where
722
+ // null and undefined represent the same thing as no property.
723
+
724
+
725
+ function trimOptions(options) {
726
+ if (options == null) return null;
727
+ var hasProperties = false;
728
+ var trimmed = {};
729
+
730
+ for (var key in options) {
731
+ if (options[key] != null) {
732
+ hasProperties = true;
733
+ trimmed[key] = options[key];
734
+ }
461
735
  }
462
736
 
463
- pushNode(next);
737
+ return hasProperties ? trimmed : null;
464
738
  }
465
739
 
466
- function popPreviousToCommonLevel(prev, next) {
467
- popNode(prev);
468
- var parentPrev = prev.parent;
740
+ function getImagePreloadKey(href, imageSrcSet, imageSizes) {
741
+ var uniquePart = '';
469
742
 
470
- if (parentPrev === null) {
471
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
472
- }
743
+ if (typeof imageSrcSet === 'string' && imageSrcSet !== '') {
744
+ uniquePart += '[' + imageSrcSet + ']';
473
745
 
474
- if (parentPrev.depth === next.depth) {
475
- // We found the same level. Now we just need to find a shared ancestor.
476
- popToNearestCommonAncestor(parentPrev, next);
746
+ if (typeof imageSizes === 'string') {
747
+ uniquePart += '[' + imageSizes + ']';
748
+ }
477
749
  } else {
478
- // We must still be deeper.
479
- popPreviousToCommonLevel(parentPrev, next);
750
+ uniquePart += '[][]' + href;
480
751
  }
481
- }
482
752
 
483
- function popNextToCommonLevel(prev, next) {
484
- var parentNext = next.parent;
485
-
486
- if (parentNext === null) {
487
- throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
488
- }
753
+ return "[image]" + uniquePart;
754
+ }
489
755
 
490
- if (prev.depth === parentNext.depth) {
491
- // We found the same level. Now we just need to find a shared ancestor.
492
- popToNearestCommonAncestor(prev, parentNext);
493
- } else {
494
- // We must still be deeper.
495
- popNextToCommonLevel(prev, parentNext);
496
- }
497
-
498
- pushNode(next);
499
- } // Perform context switching to the new snapshot.
500
- // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
501
- // updating all the context's current values. That way reads, always just read the current value.
502
- // At the cost of updating contexts even if they're never read by this subtree.
503
-
504
-
505
- function switchContext(newSnapshot) {
506
- // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
507
- // We also need to update any new contexts that are now on the stack with the deepest value.
508
- // The easiest way to update new contexts is to just reapply them in reverse order from the
509
- // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
510
- // for that. Therefore this algorithm is recursive.
511
- // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
512
- // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
513
- // 3) Then we reapply new contexts on the way back up the stack.
514
- var prev = currentActiveSnapshot;
515
- var next = newSnapshot;
516
-
517
- if (prev !== next) {
518
- if (prev === null) {
519
- // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev.
520
- pushAllNext(next);
521
- } else if (next === null) {
522
- popAllPrevious(prev);
523
- } else if (prev.depth === next.depth) {
524
- popToNearestCommonAncestor(prev, next);
525
- } else if (prev.depth > next.depth) {
526
- popPreviousToCommonLevel(prev, next);
527
- } else {
528
- popNextToCommonLevel(prev, next);
529
- }
756
+ // This module registers the host dispatcher so it needs to be imported
757
+ // small, smaller than how we encode undefined, and is unambiguous. We could use
758
+ // a different tuple structure to encode this instead but this makes the runtime
759
+ // cost cheaper by eliminating a type checks in more positions.
760
+ // prettier-ignore
530
761
 
531
- currentActiveSnapshot = next;
532
- }
762
+ function createHints() {
763
+ return new Set();
533
764
  }
534
- function pushProvider(context, nextValue) {
535
- var prevValue;
536
765
 
537
- {
538
- prevValue = context._currentValue;
539
- context._currentValue = nextValue;
766
+ var supportsRequestStorage = false;
767
+ var requestStorage = null;
540
768
 
541
- {
542
- if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
543
- error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
544
- }
769
+ var TEMPORARY_REFERENCE_TAG = Symbol.for('react.temporary.reference'); // eslint-disable-next-line no-unused-vars
545
770
 
546
- context._currentRenderer = rendererSigil;
771
+ function isTemporaryReference(reference) {
772
+ return reference.$$typeof === TEMPORARY_REFERENCE_TAG;
773
+ }
774
+ function resolveTemporaryReferenceID(temporaryReference) {
775
+ return temporaryReference.$$id;
776
+ }
777
+ var proxyHandlers = {
778
+ get: function (target, name, receiver) {
779
+ switch (name) {
780
+ // These names are read by the Flight runtime if you end up using the exports object.
781
+ case '$$typeof':
782
+ // These names are a little too common. We should probably have a way to
783
+ // have the Flight runtime extract the inner target instead.
784
+ return target.$$typeof;
785
+
786
+ case '$$id':
787
+ return target.$$id;
788
+
789
+ case '$$async':
790
+ return target.$$async;
791
+
792
+ case 'name':
793
+ return undefined;
794
+
795
+ case 'displayName':
796
+ return undefined;
797
+ // We need to special case this because createElement reads it if we pass this
798
+ // reference.
799
+
800
+ case 'defaultProps':
801
+ return undefined;
802
+ // Avoid this attempting to be serialized.
803
+
804
+ case 'toJSON':
805
+ return undefined;
806
+
807
+ case Symbol.toPrimitive:
808
+ // $FlowFixMe[prop-missing]
809
+ return Object.prototype[Symbol.toPrimitive];
810
+
811
+ case Symbol.toStringTag:
812
+ // $FlowFixMe[prop-missing]
813
+ return Object.prototype[Symbol.toStringTag];
814
+
815
+ case 'Provider':
816
+ 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.");
547
817
  }
548
- }
549
818
 
550
- var prevNode = currentActiveSnapshot;
551
- var newNode = {
552
- parent: prevNode,
553
- depth: prevNode === null ? 0 : prevNode.depth + 1,
554
- context: context,
555
- parentValue: prevValue,
556
- value: nextValue
557
- };
558
- currentActiveSnapshot = newNode;
559
- return newNode;
819
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
820
+ "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.');
821
+ },
822
+ set: function () {
823
+ throw new Error('Cannot assign to a temporary client reference from a server module.');
824
+ }
825
+ };
826
+ function createTemporaryReference(id) {
827
+ var reference = Object.defineProperties(function () {
828
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
829
+ "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.");
830
+ }, {
831
+ $$typeof: {
832
+ value: TEMPORARY_REFERENCE_TAG
833
+ },
834
+ $$id: {
835
+ value: id
836
+ }
837
+ });
838
+ return new Proxy(reference, proxyHandlers);
560
839
  }
561
- function popProvider() {
562
- var prevSnapshot = currentActiveSnapshot;
563
840
 
564
- if (prevSnapshot === null) {
565
- throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
841
+ var REACT_ELEMENT_TYPE = Symbol.for('react.transitional.element') ;
842
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
843
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
844
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
845
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
846
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
847
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
848
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
849
+ var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
850
+ var REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
851
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
852
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
853
+ function getIteratorFn(maybeIterable) {
854
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
855
+ return null;
566
856
  }
567
857
 
568
- {
569
- var value = prevSnapshot.parentValue;
858
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
570
859
 
571
- if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
572
- prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
573
- } else {
574
- prevSnapshot.context._currentValue = value;
575
- }
860
+ if (typeof maybeIterator === 'function') {
861
+ return maybeIterator;
576
862
  }
577
863
 
578
- return currentActiveSnapshot = prevSnapshot.parent;
579
- }
580
- function getActiveContext() {
581
- return currentActiveSnapshot;
582
- }
583
- function readContext$1(context) {
584
- var value = context._currentValue ;
585
- return value;
864
+ return null;
586
865
  }
587
866
 
588
867
  // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
@@ -637,11 +916,18 @@ function trackUsedThenable(thenableState, thenable, index) {
637
916
 
638
917
  default:
639
918
  {
640
- if (typeof thenable.status === 'string') ; else {
641
- var pendingThenable = thenable;
642
- pendingThenable.status = 'pending';
643
- pendingThenable.then(function (fulfilledValue) {
644
- if (thenable.status === 'pending') {
919
+ if (typeof thenable.status === 'string') {
920
+ // Only instrument the thenable if the status if not defined. If
921
+ // it's defined, but an unknown value, assume it's been instrumented by
922
+ // some custom userspace implementation. We treat it as "pending".
923
+ // Attach a dummy listener, to ensure that any lazy initialization can
924
+ // happen. Flight lazily parses JSON when the value is actually awaited.
925
+ thenable.then(noop, noop);
926
+ } else {
927
+ var pendingThenable = thenable;
928
+ pendingThenable.status = 'pending';
929
+ pendingThenable.then(function (fulfilledValue) {
930
+ if (thenable.status === 'pending') {
645
931
  var fulfilledThenable = thenable;
646
932
  fulfilledThenable.status = 'fulfilled';
647
933
  fulfilledThenable.value = fulfilledValue;
@@ -652,21 +938,22 @@ function trackUsedThenable(thenableState, thenable, index) {
652
938
  rejectedThenable.status = 'rejected';
653
939
  rejectedThenable.reason = error;
654
940
  }
655
- }); // Check one more time in case the thenable resolved synchronously
941
+ });
942
+ } // Check one more time in case the thenable resolved synchronously
656
943
 
657
- switch (thenable.status) {
658
- case 'fulfilled':
659
- {
660
- var fulfilledThenable = thenable;
661
- return fulfilledThenable.value;
662
- }
663
944
 
664
- case 'rejected':
665
- {
666
- var rejectedThenable = thenable;
667
- throw rejectedThenable.reason;
668
- }
669
- }
945
+ switch (thenable.status) {
946
+ case 'fulfilled':
947
+ {
948
+ var fulfilledThenable = thenable;
949
+ return fulfilledThenable.value;
950
+ }
951
+
952
+ case 'rejected':
953
+ {
954
+ var rejectedThenable = thenable;
955
+ throw rejectedThenable.reason;
956
+ }
670
957
  } // Suspend.
671
958
  //
672
959
  // Throwing here is an implementation detail that allows us to unwind the
@@ -702,40 +989,37 @@ function getSuspendedThenable() {
702
989
  var currentRequest$1 = null;
703
990
  var thenableIndexCounter = 0;
704
991
  var thenableState = null;
992
+ var currentComponentDebugInfo = null;
705
993
  function prepareToUseHooksForRequest(request) {
706
994
  currentRequest$1 = request;
707
995
  }
708
996
  function resetHooksForRequest() {
709
997
  currentRequest$1 = null;
710
998
  }
711
- function prepareToUseHooksForComponent(prevThenableState) {
999
+ function prepareToUseHooksForComponent(prevThenableState, componentDebugInfo) {
712
1000
  thenableIndexCounter = 0;
713
1001
  thenableState = prevThenableState;
1002
+
1003
+ {
1004
+ currentComponentDebugInfo = componentDebugInfo;
1005
+ }
714
1006
  }
715
1007
  function getThenableStateAfterSuspending() {
716
- var state = thenableState;
717
- thenableState = null;
718
- return state;
719
- }
1008
+ // If you use() to Suspend this should always exist but if you throw a Promise instead,
1009
+ // which is not really supported anymore, it will be empty. We use the empty set as a
1010
+ // marker to know if this was a replay of the same component or first attempt.
1011
+ var state = thenableState || createThenableState();
720
1012
 
721
- function readContext(context) {
722
1013
  {
723
- if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) {
724
- if (isClientReference(context)) {
725
- error('Cannot read a Client Context from a Server Component.');
726
- } else {
727
- error('Only createServerContext is supported in Server Components.');
728
- }
729
- }
730
-
731
- if (currentRequest$1 === null) {
732
- 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().');
733
- }
1014
+ // This is a hack but we stash the debug info here so that we don't need a completely
1015
+ // different data structure just for this in DEV. Not too happy about it.
1016
+ state._componentDebugInfo = currentComponentDebugInfo;
1017
+ currentComponentDebugInfo = null;
734
1018
  }
735
1019
 
736
- return readContext$1(context);
1020
+ thenableState = null;
1021
+ return state;
737
1022
  }
738
-
739
1023
  var HooksDispatcher = {
740
1024
  useMemo: function (nextCreate) {
741
1025
  return nextCreate();
@@ -746,8 +1030,8 @@ var HooksDispatcher = {
746
1030
  useDebugValue: function () {},
747
1031
  useDeferredValue: unsupportedHook,
748
1032
  useTransition: unsupportedHook,
749
- readContext: readContext,
750
- useContext: readContext,
1033
+ readContext: unsupportedContext,
1034
+ useContext: unsupportedContext,
751
1035
  useReducer: unsupportedHook,
752
1036
  useRef: unsupportedHook,
753
1037
  useState: unsupportedHook,
@@ -756,7 +1040,6 @@ var HooksDispatcher = {
756
1040
  useImperativeHandle: unsupportedHook,
757
1041
  useEffect: unsupportedHook,
758
1042
  useId: useId,
759
- useMutableSource: unsupportedHook,
760
1043
  useSyncExternalStore: unsupportedHook,
761
1044
  useCacheRefresh: function () {
762
1045
  return unsupportedRefresh;
@@ -781,6 +1064,10 @@ function unsupportedRefresh() {
781
1064
  throw new Error('Refreshing the cache is not supported in Server Components.');
782
1065
  }
783
1066
 
1067
+ function unsupportedContext() {
1068
+ throw new Error('Cannot read a Client Context from a Server Component.');
1069
+ }
1070
+
784
1071
  function useId() {
785
1072
  if (currentRequest$1 === null) {
786
1073
  throw new Error('useId can only be used while React is rendering');
@@ -806,24 +1093,22 @@ function use(usable) {
806
1093
  }
807
1094
 
808
1095
  return trackUsedThenable(thenableState, thenable, index);
809
- } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
810
- var context = usable;
811
- return readContext(context);
1096
+ } else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
1097
+ unsupportedContext();
812
1098
  }
813
1099
  }
814
1100
 
815
- {
816
- if (isClientReference(usable)) {
817
- error('Cannot use() an already resolved Client Reference.');
1101
+ if (isClientReference(usable)) {
1102
+ if (usable.value != null && usable.value.$$typeof === REACT_CONTEXT_TYPE) {
1103
+ // Show a more specific message since it's a common mistake.
1104
+ throw new Error('Cannot read a Client Context from a Server Component.');
1105
+ } else {
1106
+ throw new Error('Cannot use() an already resolved Client Reference.');
818
1107
  }
819
- } // eslint-disable-next-line react-internal/safe-string-coercion
820
-
821
-
822
- throw new Error('An unsupported type was passed to use(): ' + String(usable));
823
- }
824
-
825
- function createSignal() {
826
- return new AbortController().signal;
1108
+ } else {
1109
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
1110
+ 'An unsupported type was passed to use(): ' + String(usable));
1111
+ }
827
1112
  }
828
1113
 
829
1114
  function resolveCache() {
@@ -836,18 +1121,7 @@ function resolveCache() {
836
1121
  return new Map();
837
1122
  }
838
1123
 
839
- var DefaultCacheDispatcher = {
840
- getCacheSignal: function () {
841
- var cache = resolveCache();
842
- var entry = cache.get(createSignal);
843
-
844
- if (entry === undefined) {
845
- entry = createSignal();
846
- cache.set(createSignal, entry);
847
- }
848
-
849
- return entry;
850
- },
1124
+ var DefaultAsyncDispatcher = {
851
1125
  getCacheForType: function (resourceType) {
852
1126
  var cache = resolveCache();
853
1127
  var entry = cache.get(resourceType);
@@ -861,6 +1135,17 @@ var DefaultCacheDispatcher = {
861
1135
  return entry;
862
1136
  }
863
1137
  };
1138
+ var currentOwner = null;
1139
+
1140
+ {
1141
+ DefaultAsyncDispatcher.getOwner = function () {
1142
+ return currentOwner;
1143
+ };
1144
+ }
1145
+
1146
+ function setCurrentOwner(componentInfo) {
1147
+ currentOwner = componentInfo;
1148
+ }
864
1149
 
865
1150
  var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
866
1151
 
@@ -868,6 +1153,8 @@ function isArray(a) {
868
1153
  return isArrayImpl(a);
869
1154
  }
870
1155
 
1156
+ var getPrototypeOf = Object.getPrototypeOf;
1157
+
871
1158
  // in case they error.
872
1159
 
873
1160
  var jsxPropsParents = new WeakMap();
@@ -886,7 +1173,7 @@ function isObjectPrototype(object) {
886
1173
  // still just a plain simple object.
887
1174
 
888
1175
 
889
- if (Object.getPrototypeOf(object)) {
1176
+ if (getPrototypeOf(object)) {
890
1177
  return false;
891
1178
  }
892
1179
 
@@ -902,7 +1189,7 @@ function isObjectPrototype(object) {
902
1189
  }
903
1190
 
904
1191
  function isSimpleObject(object) {
905
- if (!isObjectPrototype(Object.getPrototypeOf(object))) {
1192
+ if (!isObjectPrototype(getPrototypeOf(object))) {
906
1193
  return false;
907
1194
  }
908
1195
 
@@ -955,6 +1242,10 @@ function describeValueForErrorMessage(value) {
955
1242
  return '[...]';
956
1243
  }
957
1244
 
1245
+ if (value !== null && value.$$typeof === CLIENT_REFERENCE_TAG) {
1246
+ return describeClientReference();
1247
+ }
1248
+
958
1249
  var name = objectName(value);
959
1250
 
960
1251
  if (name === 'Object') {
@@ -965,7 +1256,15 @@ function describeValueForErrorMessage(value) {
965
1256
  }
966
1257
 
967
1258
  case 'function':
968
- return 'function';
1259
+ {
1260
+ if (value.$$typeof === CLIENT_REFERENCE_TAG) {
1261
+ return describeClientReference();
1262
+ }
1263
+
1264
+ var _name = value.displayName || value.name;
1265
+
1266
+ return _name ? 'function ' + _name : 'function';
1267
+ }
969
1268
 
970
1269
  default:
971
1270
  // eslint-disable-next-line react-internal/safe-string-coercion
@@ -1011,6 +1310,12 @@ function describeElementType(type) {
1011
1310
  return '';
1012
1311
  }
1013
1312
 
1313
+ var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
1314
+
1315
+ function describeClientReference(ref) {
1316
+ return 'client';
1317
+ }
1318
+
1014
1319
  function describeObjectForErrorMessage(objectOrArray, expandedName) {
1015
1320
  var objKind = objectName(objectOrArray);
1016
1321
 
@@ -1036,7 +1341,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1036
1341
  if (typeof value === 'string') {
1037
1342
  substr = value;
1038
1343
  } else if (typeof value === 'object' && value !== null) {
1039
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1040
1344
  substr = '{' + describeObjectForErrorMessage(value) + '}';
1041
1345
  } else {
1042
1346
  substr = '{' + describeValueForErrorMessage(value) + '}';
@@ -1069,7 +1373,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1069
1373
  var _substr = void 0;
1070
1374
 
1071
1375
  if (typeof _value === 'object' && _value !== null) {
1072
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1073
1376
  _substr = describeObjectForErrorMessage(_value);
1074
1377
  } else {
1075
1378
  _substr = describeValueForErrorMessage(_value);
@@ -1091,6 +1394,8 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1091
1394
  } else {
1092
1395
  if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) {
1093
1396
  str = '<' + describeElementType(objectOrArray.type) + '/>';
1397
+ } else if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) {
1398
+ return describeClientReference();
1094
1399
  } else if (jsxPropsParents.has(objectOrArray)) {
1095
1400
  // Print JSX
1096
1401
  var _type = jsxPropsParents.get(objectOrArray);
@@ -1108,7 +1413,6 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1108
1413
  var _substr2 = void 0;
1109
1414
 
1110
1415
  if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) {
1111
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1112
1416
  _substr2 = describeObjectForErrorMessage(_value2);
1113
1417
  } else {
1114
1418
  _substr2 = describeValueForErrorMessage(_value2);
@@ -1142,20 +1446,19 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1142
1446
  str += ', ';
1143
1447
  }
1144
1448
 
1145
- var _name = _names[_i3];
1146
- str += describeKeyForErrorMessage(_name) + ': ';
1147
- var _value3 = _object[_name];
1449
+ var _name2 = _names[_i3];
1450
+ str += describeKeyForErrorMessage(_name2) + ': ';
1451
+ var _value3 = _object[_name2];
1148
1452
 
1149
1453
  var _substr3 = void 0;
1150
1454
 
1151
1455
  if (typeof _value3 === 'object' && _value3 !== null) {
1152
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1153
1456
  _substr3 = describeObjectForErrorMessage(_value3);
1154
1457
  } else {
1155
1458
  _substr3 = describeValueForErrorMessage(_value3);
1156
1459
  }
1157
1460
 
1158
- if (_name === expandedName) {
1461
+ if (_name2 === expandedName) {
1159
1462
  start = str.length;
1160
1463
  length = _substr3.length;
1161
1464
  str += _substr3;
@@ -1182,41 +1485,41 @@ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1182
1485
  return '\n ' + str;
1183
1486
  }
1184
1487
 
1185
- var ContextRegistry = ReactSharedInternals.ContextRegistry;
1186
- function getOrCreateServerContext(globalName) {
1187
- if (!ContextRegistry[globalName]) {
1188
- ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value
1189
- REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED);
1190
- }
1191
-
1192
- return ContextRegistry[globalName];
1193
- }
1488
+ var ReactSharedInternals = ReactSharedInternalsServer;
1194
1489
 
1490
+ var ObjectPrototype = Object.prototype;
1491
+ var stringify = JSON.stringify; // Serializable values
1195
1492
  // Thenable<ReactClientValue>
1493
+ // task status
1196
1494
 
1197
1495
  var PENDING$1 = 0;
1198
1496
  var COMPLETED = 1;
1199
1497
  var ABORTED = 3;
1200
- var ERRORED$1 = 4;
1201
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1202
- var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache;
1498
+ var ERRORED$1 = 4; // object reference status
1499
+
1500
+ var SEEN_BUT_NOT_YET_OUTLINED = -1;
1501
+ var NEVER_OUTLINED = -2;
1203
1502
 
1204
1503
  function defaultErrorHandler(error) {
1205
1504
  console['error'](error); // Don't transform to our wrapper
1206
1505
  }
1207
1506
 
1507
+ function defaultPostponeHandler(reason) {// Noop
1508
+ }
1509
+
1208
1510
  var OPEN = 0;
1209
1511
  var CLOSING = 1;
1210
1512
  var CLOSED = 2;
1211
- function createRequest(model, bundlerConfig, onError, context, identifierPrefix) {
1212
- if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) {
1513
+ function createRequest(model, bundlerConfig, onError, identifierPrefix, onPostpone, environmentName) {
1514
+ if (ReactSharedInternals.A !== null && ReactSharedInternals.A !== DefaultAsyncDispatcher) {
1213
1515
  throw new Error('Currently React only supports one RSC renderer at a time.');
1214
1516
  }
1215
1517
 
1216
- prepareHostDispatcher();
1217
- ReactCurrentCache.current = DefaultCacheDispatcher;
1518
+ ReactSharedInternals.A = DefaultAsyncDispatcher;
1218
1519
  var abortSet = new Set();
1219
1520
  var pingedTasks = [];
1521
+ var cleanupQueue = [];
1522
+
1220
1523
  var hints = createHints();
1221
1524
  var request = {
1222
1525
  status: OPEN,
@@ -1228,27 +1531,29 @@ function createRequest(model, bundlerConfig, onError, context, identifierPrefix)
1228
1531
  nextChunkId: 0,
1229
1532
  pendingChunks: 0,
1230
1533
  hints: hints,
1534
+ abortListeners: new Set(),
1231
1535
  abortableTasks: abortSet,
1232
1536
  pingedTasks: pingedTasks,
1233
1537
  completedImportChunks: [],
1234
1538
  completedHintChunks: [],
1235
- completedJSONChunks: [],
1539
+ completedRegularChunks: [],
1236
1540
  completedErrorChunks: [],
1237
1541
  writtenSymbols: new Map(),
1238
1542
  writtenClientReferences: new Map(),
1239
1543
  writtenServerReferences: new Map(),
1240
- writtenProviders: new Map(),
1544
+ writtenObjects: new WeakMap(),
1241
1545
  identifierPrefix: identifierPrefix || '',
1242
1546
  identifierCount: 1,
1547
+ taintCleanupQueue: cleanupQueue,
1243
1548
  onError: onError === undefined ? defaultErrorHandler : onError,
1244
- // $FlowFixMe[missing-this-annot]
1245
- toJSON: function (key, value) {
1246
- return resolveModelToJSON(request, this, key, value);
1247
- }
1549
+ onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone
1248
1550
  };
1249
- request.pendingChunks++;
1250
- var rootContext = createRootContext(context);
1251
- var rootTask = createTask(request, model, rootContext, abortSet);
1551
+
1552
+ {
1553
+ request.environmentName = environmentName === undefined ? 'Server' : environmentName;
1554
+ }
1555
+
1556
+ var rootTask = createTask(request, model, null, false, abortSet);
1252
1557
  pingedTasks.push(rootTask);
1253
1558
  return request;
1254
1559
  }
@@ -1259,15 +1564,18 @@ function resolveRequest() {
1259
1564
  return null;
1260
1565
  }
1261
1566
 
1262
- function createRootContext(reqContext) {
1263
- return importServerContexts(reqContext);
1264
- }
1567
+ function serializeThenable(request, task, thenable) {
1568
+ var newTask = createTask(request, null, task.keyPath, // the server component sequence continues through Promise-as-a-child.
1569
+ task.implicitSlot, request.abortableTasks);
1265
1570
 
1266
- var POP = {};
1571
+ {
1572
+ // If this came from Flight, forward any debug info into this new row.
1573
+ var debugInfo = thenable._debugInfo;
1267
1574
 
1268
- function serializeThenable(request, thenable) {
1269
- request.pendingChunks++;
1270
- var newTask = createTask(request, null, getActiveContext(), request.abortableTasks);
1575
+ if (debugInfo) {
1576
+ forwardDebugInfo(request, newTask.id, debugInfo);
1577
+ }
1578
+ }
1271
1579
 
1272
1580
  switch (thenable.status) {
1273
1581
  case 'fulfilled':
@@ -1281,14 +1589,10 @@ function serializeThenable(request, thenable) {
1281
1589
  case 'rejected':
1282
1590
  {
1283
1591
  var x = thenable.reason;
1284
- var digest = logRecoverableError(request, x);
1285
1592
 
1286
1593
  {
1287
- var _getErrorMessageAndSt = getErrorMessageAndStackDev(x),
1288
- message = _getErrorMessageAndSt.message,
1289
- stack = _getErrorMessageAndSt.stack;
1290
-
1291
- emitErrorChunkDev(request, newTask.id, digest, message, stack);
1594
+ var digest = logRecoverableError(request, x);
1595
+ emitErrorChunk(request, newTask.id, digest, x);
1292
1596
  }
1293
1597
 
1294
1598
  return newTask.id;
@@ -1326,21 +1630,16 @@ function serializeThenable(request, thenable) {
1326
1630
  newTask.model = value;
1327
1631
  pingTask(request, newTask);
1328
1632
  }, function (reason) {
1329
- newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled
1330
-
1331
- var digest = logRecoverableError(request, reason);
1332
-
1333
1633
  {
1334
- var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason),
1335
- _message = _getErrorMessageAndSt2.message,
1336
- _stack = _getErrorMessageAndSt2.stack;
1634
+ newTask.status = ERRORED$1;
1337
1635
 
1338
- emitErrorChunkDev(request, newTask.id, digest, _message, _stack);
1339
- }
1636
+ var _digest = logRecoverableError(request, reason);
1340
1637
 
1341
- if (request.destination !== null) {
1342
- flushCompletedChunks(request, request.destination);
1638
+ emitErrorChunk(request, newTask.id, _digest, reason);
1343
1639
  }
1640
+
1641
+ request.abortableTasks.delete(newTask);
1642
+ enqueueFlush(request);
1344
1643
  });
1345
1644
  return newTask.id;
1346
1645
  }
@@ -1409,36 +1708,68 @@ function createLazyWrapperAroundWakeable(wakeable) {
1409
1708
  _payload: thenable,
1410
1709
  _init: readThenable
1411
1710
  };
1711
+
1712
+ {
1713
+ // If this came from React, transfer the debug info.
1714
+ lazyType._debugInfo = thenable._debugInfo || [];
1715
+ }
1716
+
1412
1717
  return lazyType;
1413
1718
  }
1414
1719
 
1415
- function attemptResolveElement(request, type, key, ref, props, prevThenableState) {
1416
- if (ref !== null && ref !== undefined) {
1417
- // When the ref moves to the regular props object this will implicitly
1418
- // throw for functions. We could probably relax it to a DEV warning for other
1419
- // cases.
1420
- throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
1421
- }
1720
+ function renderFunctionComponent(request, task, key, Component, props, owner) {
1721
+ // Reset the task's thenable state before continuing, so that if a later
1722
+ // component suspends we can reuse the same task object. If the same
1723
+ // component suspends again, the thenable state will be restored.
1724
+ var prevThenableState = task.thenableState;
1725
+ task.thenableState = null;
1726
+ var componentDebugInfo = null;
1422
1727
 
1423
1728
  {
1424
- jsxPropsParents.set(props, type);
1425
-
1426
- if (typeof props.children === 'object' && props.children !== null) {
1427
- jsxChildrenParents.set(props.children, type);
1729
+ if (debugID === null) {
1730
+ // We don't have a chunk to assign debug info. We need to outline this
1731
+ // component to assign it an ID.
1732
+ return outlineTask(request, task);
1733
+ } else if (prevThenableState !== null) {
1734
+ // This is a replay and we've already emitted the debug info of this component
1735
+ // in the first pass. We skip emitting a duplicate line.
1736
+ // As a hack we stashed the previous component debug info on this object in DEV.
1737
+ componentDebugInfo = prevThenableState._componentDebugInfo;
1738
+ } else {
1739
+ // This is a new component in the same task so we can emit more debug info.
1740
+ var componentName = Component.displayName || Component.name || '';
1741
+ request.pendingChunks++;
1742
+ var componentDebugID = debugID;
1743
+ componentDebugInfo = {
1744
+ name: componentName,
1745
+ env: request.environmentName,
1746
+ owner: owner
1747
+ }; // We outline this model eagerly so that we can refer to by reference as an owner.
1748
+ // If we had a smarter way to dedupe we might not have to do this if there ends up
1749
+ // being no references to this as an owner.
1750
+
1751
+ outlineModel(request, componentDebugInfo);
1752
+ emitDebugChunk(request, componentDebugID, componentDebugInfo);
1428
1753
  }
1429
1754
  }
1430
1755
 
1431
- if (typeof type === 'function') {
1432
- if (isClientReference(type)) {
1433
- // This is a reference to a Client Component.
1434
- return [REACT_ELEMENT_TYPE, type, key, props];
1435
- } // This is a server-side component.
1756
+ prepareToUseHooksForComponent(prevThenableState, componentDebugInfo); // The secondArg is always undefined in Server Components since refs error early.
1757
+
1758
+ var secondArg = undefined;
1759
+ var result;
1436
1760
 
1761
+ {
1762
+ setCurrentOwner(componentDebugInfo);
1437
1763
 
1438
- prepareToUseHooksForComponent(prevThenableState);
1439
- var result = type(props);
1764
+ try {
1765
+ result = Component(props, secondArg);
1766
+ } finally {
1767
+ setCurrentOwner(null);
1768
+ }
1769
+ }
1440
1770
 
1441
- if (typeof result === 'object' && result !== null && typeof result.then === 'function') {
1771
+ if (typeof result === 'object' && result !== null) {
1772
+ if (typeof result.then === 'function') {
1442
1773
  // When the return value is in children position we can resolve it immediately,
1443
1774
  // to its value without a wrapper if it's synchronously available.
1444
1775
  var thenable = result;
@@ -1449,29 +1780,228 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1449
1780
  // the thenable here.
1450
1781
 
1451
1782
 
1452
- return createLazyWrapperAroundWakeable(result);
1783
+ result = createLazyWrapperAroundWakeable(result);
1784
+ } // Normally we'd serialize an Iterator/AsyncIterator as a single-shot which is not compatible
1785
+ // to be rendered as a React Child. However, because we have the function to recreate
1786
+ // an iterable from rendering the element again, we can effectively treat it as multi-
1787
+ // shot. Therefore we treat this as an Iterable/AsyncIterable, whether it was one or not, by
1788
+ // adding a wrapper so that this component effectively renders down to an AsyncIterable.
1789
+
1790
+
1791
+ var iteratorFn = getIteratorFn(result);
1792
+
1793
+ if (iteratorFn) {
1794
+ var iterableChild = result;
1795
+ result = _defineProperty({}, Symbol.iterator, function () {
1796
+ var iterator = iteratorFn.call(iterableChild);
1797
+
1798
+ {
1799
+ // If this was an Iterator but not a GeneratorFunction we warn because
1800
+ // it might have been a mistake. Technically you can make this mistake with
1801
+ // GeneratorFunctions and even single-shot Iterables too but it's extra
1802
+ // tempting to try to return the value from a generator.
1803
+ if (iterator === iterableChild) {
1804
+ var isGeneratorComponent = // $FlowIgnore[method-unbinding]
1805
+ Object.prototype.toString.call(Component) === '[object GeneratorFunction]' && // $FlowIgnore[method-unbinding]
1806
+ Object.prototype.toString.call(iterableChild) === '[object Generator]';
1807
+
1808
+ if (!isGeneratorComponent) {
1809
+ error('Returning an Iterator from a Server Component is not supported ' + 'since it cannot be looped over more than once. ');
1810
+ }
1811
+ }
1812
+ }
1813
+
1814
+ return iterator;
1815
+ });
1816
+
1817
+ {
1818
+ result._debugInfo = iterableChild._debugInfo;
1819
+ }
1820
+ }
1821
+ } // Track this element's key on the Server Component on the keyPath context..
1822
+
1823
+
1824
+ var prevKeyPath = task.keyPath;
1825
+ var prevImplicitSlot = task.implicitSlot;
1826
+
1827
+ if (key !== null) {
1828
+ // Append the key to the path. Technically a null key should really add the child
1829
+ // index. We don't do that to hold the payload small and implementation simple.
1830
+ task.keyPath = prevKeyPath === null ? key : prevKeyPath + ',' + key;
1831
+ } else if (prevKeyPath === null) {
1832
+ // This sequence of Server Components has no keys. This means that it was rendered
1833
+ // in a slot that needs to assign an implicit key. Even if children below have
1834
+ // explicit keys, they should not be used for the outer most key since it might
1835
+ // collide with other slots in that set.
1836
+ task.implicitSlot = true;
1837
+ }
1838
+
1839
+ var json = renderModelDestructive(request, task, emptyRoot, '', result);
1840
+ task.keyPath = prevKeyPath;
1841
+ task.implicitSlot = prevImplicitSlot;
1842
+ return json;
1843
+ }
1844
+
1845
+ function renderFragment(request, task, children) {
1846
+ if (task.keyPath !== null) {
1847
+ // We have a Server Component that specifies a key but we're now splitting
1848
+ // the tree using a fragment.
1849
+ var fragment = [REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, task.keyPath, {
1850
+ children: children
1851
+ }];
1852
+
1853
+ if (!task.implicitSlot) {
1854
+ // If this was keyed inside a set. I.e. the outer Server Component was keyed
1855
+ // then we need to handle reorders of the whole set. To do this we need to wrap
1856
+ // this array in a keyed Fragment.
1857
+ return fragment;
1858
+ } // If the outer Server Component was implicit but then an inner one had a key
1859
+ // we don't actually need to be able to move the whole set around. It'll always be
1860
+ // in an implicit slot. The key only exists to be able to reset the state of the
1861
+ // children. We could achieve the same effect by passing on the keyPath to the next
1862
+ // set of components inside the fragment. This would also allow a keyless fragment
1863
+ // reconcile against a single child.
1864
+ // Unfortunately because of JSON.stringify, we can't call the recursive loop for
1865
+ // each child within this context because we can't return a set with already resolved
1866
+ // values. E.g. a string would get double encoded. Returning would pop the context.
1867
+ // So instead, we wrap it with an unkeyed fragment and inner keyed fragment.
1868
+
1869
+
1870
+ return [fragment];
1871
+ } // Since we're yielding here, that implicitly resets the keyPath context on the
1872
+ // way up. Which is what we want since we've consumed it. If this changes to
1873
+ // be recursive serialization, we need to reset the keyPath and implicitSlot,
1874
+ // before recursing here.
1875
+
1876
+
1877
+ {
1878
+ var debugInfo = children._debugInfo;
1879
+
1880
+ if (debugInfo) {
1881
+ // If this came from Flight, forward any debug info into this new row.
1882
+ if (debugID === null) {
1883
+ // We don't have a chunk to assign debug info. We need to outline this
1884
+ // component to assign it an ID.
1885
+ return outlineTask(request, task);
1886
+ } else {
1887
+ // Forward any debug info we have the first time we see it.
1888
+ // We do this after init so that we have received all the debug info
1889
+ // from the server by the time we emit it.
1890
+ forwardDebugInfo(request, debugID, debugInfo);
1891
+ } // Since we're rendering this array again, create a copy that doesn't
1892
+ // have the debug info so we avoid outlining or emitting debug info again.
1893
+
1894
+
1895
+ children = Array.from(children);
1896
+ }
1897
+ }
1898
+
1899
+ return children;
1900
+ }
1901
+
1902
+ function renderClientElement(task, type, key, props, owner) // DEV-only
1903
+ {
1904
+ // the keys of any Server Components which are not serialized.
1905
+
1906
+
1907
+ var keyPath = task.keyPath;
1908
+
1909
+ if (key === null) {
1910
+ key = keyPath;
1911
+ } else if (keyPath !== null) {
1912
+ key = keyPath + ',' + key;
1913
+ }
1914
+
1915
+ var element = [REACT_ELEMENT_TYPE, type, key, props, owner] ;
1916
+
1917
+ if (task.implicitSlot && key !== null) {
1918
+ // The root Server Component had no key so it was in an implicit slot.
1919
+ // If we had a key lower, it would end up in that slot with an explicit key.
1920
+ // We wrap the element in a fragment to give it an implicit key slot with
1921
+ // an inner explicit key.
1922
+ return [element];
1923
+ } // Since we're yielding here, that implicitly resets the keyPath context on the
1924
+ // way up. Which is what we want since we've consumed it. If this changes to
1925
+ // be recursive serialization, we need to reset the keyPath and implicitSlot,
1926
+ // before recursing here. We also need to reset it once we render into an array
1927
+ // or anything else too which we also get implicitly.
1928
+
1929
+
1930
+ return element;
1931
+ } // The chunk ID we're currently rendering that we can assign debug data to.
1932
+
1933
+
1934
+ var debugID = null;
1935
+
1936
+ function outlineTask(request, task) {
1937
+ var newTask = createTask(request, task.model, // the currently rendering element
1938
+ task.keyPath, // unlike outlineModel this one carries along context
1939
+ task.implicitSlot, request.abortableTasks);
1940
+ retryTask(request, newTask);
1941
+
1942
+ if (newTask.status === COMPLETED) {
1943
+ // We completed synchronously so we can refer to this by reference. This
1944
+ // makes it behaves the same as prod during deserialization.
1945
+ return serializeByValueID(newTask.id);
1946
+ } // This didn't complete synchronously so it wouldn't have even if we didn't
1947
+ // outline it, so this would reduce to a lazy reference even in prod.
1948
+
1949
+
1950
+ return serializeLazyID(newTask.id);
1951
+ }
1952
+
1953
+ function renderElement(request, task, type, key, ref, props, owner) // DEV only
1954
+ {
1955
+ if (ref !== null && ref !== undefined) {
1956
+ // When the ref moves to the regular props object this will implicitly
1957
+ // throw for functions. We could probably relax it to a DEV warning for other
1958
+ // cases.
1959
+ // TODO: `ref` is now just a prop when `enableRefAsProp` is on. Should we
1960
+ // do what the above comment says?
1961
+ throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
1962
+ }
1963
+
1964
+ {
1965
+ jsxPropsParents.set(props, type);
1966
+
1967
+ if (typeof props.children === 'object' && props.children !== null) {
1968
+ jsxChildrenParents.set(props.children, type);
1453
1969
  }
1970
+ }
1454
1971
 
1455
- return result;
1972
+ if (typeof type === 'function') {
1973
+ if (isClientReference(type) || isTemporaryReference(type)) {
1974
+ // This is a reference to a Client Component.
1975
+ return renderClientElement(task, type, key, props, owner);
1976
+ } // This is a Server Component.
1977
+
1978
+
1979
+ return renderFunctionComponent(request, task, key, type, props, owner);
1456
1980
  } else if (typeof type === 'string') {
1457
1981
  // This is a host element. E.g. HTML.
1458
- return [REACT_ELEMENT_TYPE, type, key, props];
1982
+ return renderClientElement(task, type, key, props, owner);
1459
1983
  } else if (typeof type === 'symbol') {
1460
- if (type === REACT_FRAGMENT_TYPE) {
1984
+ if (type === REACT_FRAGMENT_TYPE && key === null) {
1461
1985
  // For key-less fragments, we add a small optimization to avoid serializing
1462
1986
  // it as a wrapper.
1463
- // TODO: If a key is specified, we should propagate its key to any children.
1464
- // Same as if a Server Component has a key.
1465
- return props.children;
1987
+ var prevImplicitSlot = task.implicitSlot;
1988
+
1989
+ if (task.keyPath === null) {
1990
+ task.implicitSlot = true;
1991
+ }
1992
+
1993
+ var json = renderModelDestructive(request, task, emptyRoot, '', props.children);
1994
+ task.implicitSlot = prevImplicitSlot;
1995
+ return json;
1466
1996
  } // This might be a built-in React component. We'll let the client decide.
1467
1997
  // Any built-in works as long as its props are serializable.
1468
1998
 
1469
1999
 
1470
- return [REACT_ELEMENT_TYPE, type, key, props];
2000
+ return renderClientElement(task, type, key, props, owner);
1471
2001
  } else if (type != null && typeof type === 'object') {
1472
2002
  if (isClientReference(type)) {
1473
2003
  // This is a reference to a Client Component.
1474
- return [REACT_ELEMENT_TYPE, type, key, props];
2004
+ return renderClientElement(task, type, key, props, owner);
1475
2005
  }
1476
2006
 
1477
2007
  switch (type.$$typeof) {
@@ -1480,45 +2010,17 @@ function attemptResolveElement(request, type, key, ref, props, prevThenableState
1480
2010
  var payload = type._payload;
1481
2011
  var init = type._init;
1482
2012
  var wrappedType = init(payload);
1483
- return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState);
2013
+ return renderElement(request, task, wrappedType, key, ref, props, owner);
1484
2014
  }
1485
2015
 
1486
2016
  case REACT_FORWARD_REF_TYPE:
1487
2017
  {
1488
- var render = type.render;
1489
- prepareToUseHooksForComponent(prevThenableState);
1490
- return render(props, undefined);
2018
+ return renderFunctionComponent(request, task, key, type.render, props, owner);
1491
2019
  }
1492
2020
 
1493
2021
  case REACT_MEMO_TYPE:
1494
2022
  {
1495
- return attemptResolveElement(request, type.type, key, ref, props, prevThenableState);
1496
- }
1497
-
1498
- case REACT_PROVIDER_TYPE:
1499
- {
1500
- pushProvider(type._context, props.value);
1501
-
1502
- {
1503
- var extraKeys = Object.keys(props).filter(function (value) {
1504
- if (value === 'children' || value === 'value') {
1505
- return false;
1506
- }
1507
-
1508
- return true;
1509
- });
1510
-
1511
- if (extraKeys.length !== 0) {
1512
- error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys));
1513
- }
1514
- }
1515
-
1516
- return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider.
1517
- {
1518
- value: props.value,
1519
- children: props.children,
1520
- __pop: POP
1521
- }];
2023
+ return renderElement(request, task, type.type, key, ref, props, owner);
1522
2024
  }
1523
2025
  }
1524
2026
  }
@@ -1538,16 +2040,51 @@ function pingTask(request, task) {
1538
2040
  }
1539
2041
  }
1540
2042
 
1541
- function createTask(request, model, context, abortSet) {
2043
+ function createTask(request, model, keyPath, implicitSlot, abortSet) {
2044
+ request.pendingChunks++;
1542
2045
  var id = request.nextChunkId++;
2046
+
2047
+ if (typeof model === 'object' && model !== null) {
2048
+ // If we're about to write this into a new task we can assign it an ID early so that
2049
+ // any other references can refer to the value we're about to write.
2050
+ if ((keyPath !== null || implicitSlot)) ; else {
2051
+ request.writtenObjects.set(model, id);
2052
+ }
2053
+ }
2054
+
1543
2055
  var task = {
1544
2056
  id: id,
1545
2057
  status: PENDING$1,
1546
2058
  model: model,
1547
- context: context,
2059
+ keyPath: keyPath,
2060
+ implicitSlot: implicitSlot,
1548
2061
  ping: function () {
1549
2062
  return pingTask(request, task);
1550
2063
  },
2064
+ toJSON: function (parentPropertyName, value) {
2065
+ var parent = this; // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
2066
+
2067
+ {
2068
+ // $FlowFixMe[incompatible-use]
2069
+ var originalValue = parent[parentPropertyName];
2070
+
2071
+ if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
2072
+ if (objectName(originalValue) !== 'Object') {
2073
+ var jsxParentType = jsxChildrenParents.get(parent);
2074
+
2075
+ if (typeof jsxParentType === 'string') {
2076
+ error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
2077
+ } else {
2078
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, parentPropertyName));
2079
+ }
2080
+ } else {
2081
+ 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));
2082
+ }
2083
+ }
2084
+ }
2085
+
2086
+ return renderModel(request, task, parent, parentPropertyName, value);
2087
+ },
1551
2088
  thenableState: null
1552
2089
  };
1553
2090
  abortSet.add(task);
@@ -1562,6 +2099,10 @@ function serializeLazyID(id) {
1562
2099
  return '$L' + id.toString(16);
1563
2100
  }
1564
2101
 
2102
+ function serializeInfinitePromise() {
2103
+ return '$@';
2104
+ }
2105
+
1565
2106
  function serializePromiseID(id) {
1566
2107
  return '$@' + id.toString(16);
1567
2108
  }
@@ -1570,12 +2111,12 @@ function serializeServerReferenceID(id) {
1570
2111
  return '$F' + id.toString(16);
1571
2112
  }
1572
2113
 
1573
- function serializeSymbolReference(name) {
1574
- return '$S' + name;
2114
+ function serializeTemporaryReferenceID(id) {
2115
+ return '$T' + id;
1575
2116
  }
1576
2117
 
1577
- function serializeProviderReference(name) {
1578
- return '$P' + name;
2118
+ function serializeSymbolReference(name) {
2119
+ return '$S' + name;
1579
2120
  }
1580
2121
 
1581
2122
  function serializeNumber(number) {
@@ -1610,13 +2151,23 @@ function serializeBigInt(n) {
1610
2151
  return '$n' + n.toString(10);
1611
2152
  }
1612
2153
 
1613
- function serializeClientReference(request, parent, key, clientReference) {
2154
+ function serializeRowHeader(tag, id) {
2155
+ return id.toString(16) + ':' + tag;
2156
+ }
2157
+
2158
+ function encodeReferenceChunk(request, id, reference) {
2159
+ var json = stringify(reference);
2160
+ var row = id.toString(16) + ':' + json + '\n';
2161
+ return stringToChunk(row);
2162
+ }
2163
+
2164
+ function serializeClientReference(request, parent, parentPropertyName, clientReference) {
1614
2165
  var clientReferenceKey = getClientReferenceKey(clientReference);
1615
2166
  var writtenClientReferences = request.writtenClientReferences;
1616
2167
  var existingId = writtenClientReferences.get(clientReferenceKey);
1617
2168
 
1618
2169
  if (existingId !== undefined) {
1619
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
2170
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1620
2171
  // If we're encoding the "type" of an element, we can refer
1621
2172
  // to that by a lazy reference instead of directly since React
1622
2173
  // knows how to deal with lazy values. This lets us suspend
@@ -1635,7 +2186,7 @@ function serializeClientReference(request, parent, key, clientReference) {
1635
2186
  emitImportChunk(request, importId, clientReferenceMetadata);
1636
2187
  writtenClientReferences.set(clientReferenceKey, importId);
1637
2188
 
1638
- if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
2189
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1639
2190
  // If we're encoding the "type" of an element, we can refer
1640
2191
  // to that by a lazy reference instead of directly since React
1641
2192
  // knows how to deal with lazy values. This lets us suspend
@@ -1649,20 +2200,20 @@ function serializeClientReference(request, parent, key, clientReference) {
1649
2200
  request.pendingChunks++;
1650
2201
  var errorId = request.nextChunkId++;
1651
2202
  var digest = logRecoverableError(request, x);
1652
-
1653
- {
1654
- var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x),
1655
- message = _getErrorMessageAndSt3.message,
1656
- stack = _getErrorMessageAndSt3.stack;
1657
-
1658
- emitErrorChunkDev(request, errorId, digest, message, stack);
1659
- }
1660
-
2203
+ emitErrorChunk(request, errorId, digest, x);
1661
2204
  return serializeByValueID(errorId);
1662
2205
  }
1663
2206
  }
1664
2207
 
1665
- function serializeServerReference(request, parent, key, serverReference) {
2208
+ function outlineModel(request, value) {
2209
+ var newTask = createTask(request, value, null, // The way we use outlining is for reusing an object.
2210
+ false, // It makes no sense for that use case to be contextual.
2211
+ request.abortableTasks);
2212
+ retryTask(request, newTask);
2213
+ return newTask.id;
2214
+ }
2215
+
2216
+ function serializeServerReference(request, serverReference) {
1666
2217
  var writtenServerReferences = request.writtenServerReferences;
1667
2218
  var existingId = writtenServerReferences.get(serverReference);
1668
2219
 
@@ -1675,126 +2226,154 @@ function serializeServerReference(request, parent, key, serverReference) {
1675
2226
  id: getServerReferenceId(request.bundlerConfig, serverReference),
1676
2227
  bound: bound ? Promise.resolve(bound) : null
1677
2228
  };
1678
- request.pendingChunks++;
1679
- var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend.
1680
-
1681
- var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata);
1682
- request.completedJSONChunks.push(processedChunk);
2229
+ var metadataId = outlineModel(request, serverReferenceMetadata);
1683
2230
  writtenServerReferences.set(serverReference, metadataId);
1684
2231
  return serializeServerReferenceID(metadataId);
1685
2232
  }
1686
2233
 
1687
- function escapeStringValue(value) {
1688
- if (value[0] === '$') {
1689
- // We need to escape $ prefixed strings since we use those to encode
1690
- // references to IDs and as special symbol values.
1691
- return '$' + value;
1692
- } else {
1693
- return value;
1694
- }
2234
+ function serializeTemporaryReference(request, temporaryReference) {
2235
+ var id = resolveTemporaryReferenceID(temporaryReference);
2236
+ return serializeTemporaryReferenceID(id);
1695
2237
  }
1696
2238
 
1697
- var insideContextProps = null;
1698
- var isInsideContextValue = false;
1699
- function resolveModelToJSON(request, parent, key, value) {
1700
- // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us
1701
- {
1702
- // $FlowFixMe[incompatible-use]
1703
- var originalValue = parent[key];
2239
+ function serializeLargeTextString(request, text) {
2240
+ request.pendingChunks++;
2241
+ var textId = request.nextChunkId++;
2242
+ emitTextChunk(request, textId, text);
2243
+ return serializeByValueID(textId);
2244
+ }
1704
2245
 
1705
- if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) {
1706
- if (objectName(originalValue) !== 'Object') {
1707
- var jsxParentType = jsxChildrenParents.get(parent);
2246
+ function serializeMap(request, map) {
2247
+ var entries = Array.from(map);
1708
2248
 
1709
- if (typeof jsxParentType === 'string') {
1710
- error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
1711
- } else {
1712
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key));
1713
- }
1714
- } else {
1715
- 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));
2249
+ for (var i = 0; i < entries.length; i++) {
2250
+ var key = entries[i][0];
2251
+
2252
+ if (typeof key === 'object' && key !== null) {
2253
+ var writtenObjects = request.writtenObjects;
2254
+ var existingId = writtenObjects.get(key);
2255
+
2256
+ if (existingId === undefined) {
2257
+ writtenObjects.set(key, SEEN_BUT_NOT_YET_OUTLINED);
1716
2258
  }
1717
2259
  }
1718
- } // Special Symbols
2260
+ }
1719
2261
 
2262
+ var id = outlineModel(request, entries);
2263
+ return '$Q' + id.toString(16);
2264
+ }
1720
2265
 
1721
- switch (value) {
1722
- case REACT_ELEMENT_TYPE:
1723
- return '$';
1724
- }
2266
+ function serializeFormData(request, formData) {
2267
+ var entries = Array.from(formData.entries());
2268
+ var id = outlineModel(request, entries);
2269
+ return '$K' + id.toString(16);
2270
+ }
1725
2271
 
1726
- {
1727
- if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') {
1728
- insideContextProps = value;
1729
- } else if (insideContextProps === parent && key === 'value') {
1730
- isInsideContextValue = true;
1731
- } else if (insideContextProps === parent && key === 'children') {
1732
- isInsideContextValue = false;
1733
- }
1734
- } // Resolve Server Components.
2272
+ function serializeSet(request, set) {
2273
+ var entries = Array.from(set);
1735
2274
 
2275
+ for (var i = 0; i < entries.length; i++) {
2276
+ var key = entries[i];
1736
2277
 
1737
- while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) {
1738
- {
1739
- if (isInsideContextValue) {
1740
- error('React elements are not allowed in ServerContext');
2278
+ if (typeof key === 'object' && key !== null) {
2279
+ var writtenObjects = request.writtenObjects;
2280
+ var existingId = writtenObjects.get(key);
2281
+
2282
+ if (existingId === undefined) {
2283
+ writtenObjects.set(key, SEEN_BUT_NOT_YET_OUTLINED);
1741
2284
  }
1742
2285
  }
2286
+ }
1743
2287
 
1744
- try {
1745
- switch (value.$$typeof) {
1746
- case REACT_ELEMENT_TYPE:
1747
- {
1748
- // TODO: Concatenate keys of parents onto children.
1749
- var element = value; // Attempt to render the Server Component.
2288
+ var id = outlineModel(request, entries);
2289
+ return '$W' + id.toString(16);
2290
+ }
1750
2291
 
1751
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null);
1752
- break;
1753
- }
2292
+ function serializeIterator(request, iterator) {
2293
+ var id = outlineModel(request, Array.from(iterator));
2294
+ return '$i' + id.toString(16);
2295
+ }
1754
2296
 
1755
- case REACT_LAZY_TYPE:
1756
- {
1757
- var payload = value._payload;
1758
- var init = value._init;
1759
- value = init(payload);
1760
- break;
1761
- }
1762
- }
1763
- } catch (thrownValue) {
1764
- var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
1765
- // reasons, the rest of the Suspense implementation expects the thrown
1766
- // value to be a thenable, because before `use` existed that was the
1767
- // (unstable) API for suspending. This implementation detail can change
1768
- // later, once we deprecate the old API in favor of `use`.
1769
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
1770
-
1771
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
2297
+ function escapeStringValue(value) {
2298
+ if (value[0] === '$') {
2299
+ // We need to escape $ prefixed strings since we use those to encode
2300
+ // references to IDs and as special symbol values.
2301
+ return '$' + value;
2302
+ } else {
2303
+ return value;
2304
+ }
2305
+ }
2306
+
2307
+ var modelRoot = false;
2308
+
2309
+ function renderModel(request, task, parent, key, value) {
2310
+ var prevKeyPath = task.keyPath;
2311
+ var prevImplicitSlot = task.implicitSlot;
2312
+
2313
+ try {
2314
+ return renderModelDestructive(request, task, parent, key, value);
2315
+ } catch (thrownValue) {
2316
+ var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
2317
+ // reasons, the rest of the Suspense implementation expects the thrown
2318
+ // value to be a thenable, because before `use` existed that was the
2319
+ // (unstable) API for suspending. This implementation detail can change
2320
+ // later, once we deprecate the old API in favor of `use`.
2321
+ getSuspendedThenable() : thrownValue; // If the suspended/errored value was an element or lazy it can be reduced
2322
+ // to a lazy reference, so that it doesn't error the parent.
2323
+
2324
+ var model = task.model;
2325
+ var wasReactNode = typeof model === 'object' && model !== null && (model.$$typeof === REACT_ELEMENT_TYPE || model.$$typeof === REACT_LAZY_TYPE);
2326
+
2327
+ if (typeof x === 'object' && x !== null) {
2328
+ // $FlowFixMe[method-unbinding]
2329
+ if (typeof x.then === 'function') {
1772
2330
  // Something suspended, we'll need to create a new task and resolve it later.
1773
- request.pendingChunks++;
1774
- var newTask = createTask(request, value, getActiveContext(), request.abortableTasks);
2331
+ var newTask = createTask(request, task.model, task.keyPath, task.implicitSlot, request.abortableTasks);
1775
2332
  var ping = newTask.ping;
1776
2333
  x.then(ping, ping);
1777
- newTask.thenableState = getThenableStateAfterSuspending();
1778
- return serializeLazyID(newTask.id);
1779
- } else {
1780
- // Something errored. We'll still send everything we have up until this point.
1781
- // We'll replace this element with a lazy reference that throws on the client
1782
- // once it gets rendered.
1783
- request.pendingChunks++;
1784
- var errorId = request.nextChunkId++;
1785
- var digest = logRecoverableError(request, x);
2334
+ newTask.thenableState = getThenableStateAfterSuspending(); // Restore the context. We assume that this will be restored by the inner
2335
+ // functions in case nothing throws so we don't use "finally" here.
1786
2336
 
1787
- {
1788
- var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x),
1789
- message = _getErrorMessageAndSt4.message,
1790
- stack = _getErrorMessageAndSt4.stack;
2337
+ task.keyPath = prevKeyPath;
2338
+ task.implicitSlot = prevImplicitSlot;
1791
2339
 
1792
- emitErrorChunkDev(request, errorId, digest, message, stack);
2340
+ if (wasReactNode) {
2341
+ return serializeLazyID(newTask.id);
1793
2342
  }
1794
2343
 
1795
- return serializeLazyID(errorId);
2344
+ return serializeByValueID(newTask.id);
1796
2345
  }
1797
- }
2346
+ } // Restore the context. We assume that this will be restored by the inner
2347
+ // functions in case nothing throws so we don't use "finally" here.
2348
+
2349
+
2350
+ task.keyPath = prevKeyPath;
2351
+ task.implicitSlot = prevImplicitSlot;
2352
+
2353
+ if (wasReactNode) {
2354
+ // Something errored. We'll still send everything we have up until this point.
2355
+ // We'll replace this element with a lazy reference that throws on the client
2356
+ // once it gets rendered.
2357
+ request.pendingChunks++;
2358
+ var errorId = request.nextChunkId++;
2359
+ var digest = logRecoverableError(request, x);
2360
+ emitErrorChunk(request, errorId, digest, x);
2361
+ return serializeLazyID(errorId);
2362
+ } // Something errored but it was not in a React Node. There's no need to serialize
2363
+ // it by value because it'll just error the whole parent row anyway so we can
2364
+ // just stop any siblings and error the whole parent row.
2365
+
2366
+
2367
+ throw x;
2368
+ }
2369
+ }
2370
+
2371
+ function renderModelDestructive(request, task, parent, parentPropertyName, value) {
2372
+ // Set the currently rendering model
2373
+ task.model = value; // Special Symbol, that's very common.
2374
+
2375
+ if (value === REACT_ELEMENT_TYPE) {
2376
+ return '$';
1798
2377
  }
1799
2378
 
1800
2379
  if (value === null) {
@@ -1802,60 +2381,572 @@ function resolveModelToJSON(request, parent, key, value) {
1802
2381
  }
1803
2382
 
1804
2383
  if (typeof value === 'object') {
2384
+ switch (value.$$typeof) {
2385
+ case REACT_ELEMENT_TYPE:
2386
+ {
2387
+ var _writtenObjects = request.writtenObjects;
2388
+
2389
+ var _existingId = _writtenObjects.get(value);
2390
+
2391
+ if (_existingId !== undefined) {
2392
+ if ((task.keyPath !== null || task.implicitSlot)) ; else if (modelRoot === value) {
2393
+ // This is the ID we're currently emitting so we need to write it
2394
+ // once but if we discover it again, we refer to it by id.
2395
+ modelRoot = null;
2396
+ } else if (_existingId === SEEN_BUT_NOT_YET_OUTLINED) {
2397
+ // TODO: If we throw here we can treat this as suspending which causes an outline
2398
+ // but that is able to reuse the same task if we're already in one but then that
2399
+ // will be a lazy future value rather than guaranteed to exist but maybe that's good.
2400
+ var newId = outlineModel(request, value);
2401
+ return serializeByValueID(newId);
2402
+ } else {
2403
+ // We've already emitted this as an outlined object, so we can refer to that by its
2404
+ // existing ID. TODO: We should use a lazy reference since, unlike plain objects,
2405
+ // elements might suspend so it might not have emitted yet even if we have the ID for
2406
+ // it. However, this creates an extra wrapper when it's not needed. We should really
2407
+ // detect whether this already was emitted and synchronously available. In that
2408
+ // case we can refer to it synchronously and only make it lazy otherwise.
2409
+ // We currently don't have a data structure that lets us see that though.
2410
+ return serializeByValueID(_existingId);
2411
+ }
2412
+ } else {
2413
+ // This is the first time we've seen this object. We may never see it again
2414
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2415
+ _writtenObjects.set(value, SEEN_BUT_NOT_YET_OUTLINED); // The element's props are marked as "never outlined" so that they are inlined into
2416
+ // the same row as the element itself.
2417
+
2418
+
2419
+ _writtenObjects.set(value.props, NEVER_OUTLINED);
2420
+ }
2421
+
2422
+ var element = value;
2423
+
2424
+ {
2425
+ var debugInfo = value._debugInfo;
2426
+
2427
+ if (debugInfo) {
2428
+ // If this came from Flight, forward any debug info into this new row.
2429
+ if (debugID === null) {
2430
+ // We don't have a chunk to assign debug info. We need to outline this
2431
+ // component to assign it an ID.
2432
+ return outlineTask(request, task);
2433
+ } else {
2434
+ // Forward any debug info we have the first time we see it.
2435
+ forwardDebugInfo(request, debugID, debugInfo);
2436
+ }
2437
+ }
2438
+ }
2439
+
2440
+ var props = element.props;
2441
+ var ref;
2442
+
2443
+ {
2444
+ // TODO: This is a temporary, intermediate step. Once the feature
2445
+ // flag is removed, we should get the ref off the props object right
2446
+ // before using it.
2447
+ var refProp = props.ref;
2448
+ ref = refProp !== undefined ? refProp : null;
2449
+ } // Attempt to render the Server Component.
2450
+
2451
+
2452
+ return renderElement(request, task, element.type, // $FlowFixMe[incompatible-call] the key of an element is null | string
2453
+ element.key, ref, props, element._owner );
2454
+ }
2455
+
2456
+ case REACT_LAZY_TYPE:
2457
+ {
2458
+ // Reset the task's thenable state before continuing. If there was one, it was
2459
+ // from suspending the lazy before.
2460
+ task.thenableState = null;
2461
+ var lazy = value;
2462
+ var payload = lazy._payload;
2463
+ var init = lazy._init;
2464
+ var resolvedModel = init(payload);
2465
+
2466
+ {
2467
+ var _debugInfo = lazy._debugInfo;
2468
+
2469
+ if (_debugInfo) {
2470
+ // If this came from Flight, forward any debug info into this new row.
2471
+ if (debugID === null) {
2472
+ // We don't have a chunk to assign debug info. We need to outline this
2473
+ // component to assign it an ID.
2474
+ return outlineTask(request, task);
2475
+ } else {
2476
+ // Forward any debug info we have the first time we see it.
2477
+ // We do this after init so that we have received all the debug info
2478
+ // from the server by the time we emit it.
2479
+ forwardDebugInfo(request, debugID, _debugInfo);
2480
+ }
2481
+ }
2482
+ }
2483
+
2484
+ return renderModelDestructive(request, task, emptyRoot, '', resolvedModel);
2485
+ }
2486
+ }
2487
+
1805
2488
  if (isClientReference(value)) {
1806
- return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding]
1807
- } else if (typeof value.then === 'function') {
1808
- // We assume that any object with a .then property is a "Thenable" type,
2489
+ return serializeClientReference(request, parent, parentPropertyName, value);
2490
+ }
2491
+
2492
+ var writtenObjects = request.writtenObjects;
2493
+ var existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
2494
+
2495
+ if (typeof value.then === 'function') {
2496
+ if (existingId !== undefined) {
2497
+ if ((task.keyPath !== null || task.implicitSlot)) {
2498
+ // If we're in some kind of context we can't reuse the result of this render or
2499
+ // previous renders of this element. We only reuse Promises if they're not wrapped
2500
+ // by another Server Component.
2501
+ var _promiseId = serializeThenable(request, task, value);
2502
+
2503
+ return serializePromiseID(_promiseId);
2504
+ } else if (modelRoot === value) {
2505
+ // This is the ID we're currently emitting so we need to write it
2506
+ // once but if we discover it again, we refer to it by id.
2507
+ modelRoot = null;
2508
+ } else {
2509
+ // We've seen this promise before, so we can just refer to the same result.
2510
+ return serializePromiseID(existingId);
2511
+ }
2512
+ } // We assume that any object with a .then property is a "Thenable" type,
1809
2513
  // or a Promise type. Either of which can be represented by a Promise.
1810
- var promiseId = serializeThenable(request, value);
2514
+
2515
+
2516
+ var promiseId = serializeThenable(request, task, value);
2517
+ writtenObjects.set(value, promiseId);
1811
2518
  return serializePromiseID(promiseId);
1812
- } else if (value.$$typeof === REACT_PROVIDER_TYPE) {
1813
- var providerKey = value._context._globalName;
1814
- var writtenProviders = request.writtenProviders;
1815
- var providerId = writtenProviders.get(key);
1816
-
1817
- if (providerId === undefined) {
1818
- request.pendingChunks++;
1819
- providerId = request.nextChunkId++;
1820
- writtenProviders.set(providerKey, providerId);
1821
- emitProviderChunk(request, providerId, providerKey);
2519
+ }
2520
+
2521
+ if (existingId !== undefined) {
2522
+ if (modelRoot === value) {
2523
+ // This is the ID we're currently emitting so we need to write it
2524
+ // once but if we discover it again, we refer to it by id.
2525
+ modelRoot = null;
2526
+ } else if (existingId === SEEN_BUT_NOT_YET_OUTLINED) {
2527
+ var _newId = outlineModel(request, value);
2528
+
2529
+ return serializeByValueID(_newId);
2530
+ } else if (existingId !== NEVER_OUTLINED) {
2531
+ // We've already emitted this as an outlined object, so we can
2532
+ // just refer to that by its existing ID.
2533
+ return serializeByValueID(existingId);
2534
+ }
2535
+ } else {
2536
+ // This is the first time we've seen this object. We may never see it again
2537
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2538
+ writtenObjects.set(value, SEEN_BUT_NOT_YET_OUTLINED);
2539
+ }
2540
+
2541
+ if (isArray(value)) {
2542
+ return renderFragment(request, task, value);
2543
+ }
2544
+
2545
+ if (value instanceof Map) {
2546
+ return serializeMap(request, value);
2547
+ }
2548
+
2549
+ if (value instanceof Set) {
2550
+ return serializeSet(request, value);
2551
+ } // TODO: FormData is not available in old Node. Remove the typeof later.
2552
+
2553
+
2554
+ if (typeof FormData === 'function' && value instanceof FormData) {
2555
+ return serializeFormData(request, value);
2556
+ }
2557
+
2558
+ var iteratorFn = getIteratorFn(value);
2559
+
2560
+ if (iteratorFn) {
2561
+ // TODO: Should we serialize the return value as well like we do for AsyncIterables?
2562
+ var iterator = iteratorFn.call(value);
2563
+
2564
+ if (iterator === value) {
2565
+ // Iterator, not Iterable
2566
+ return serializeIterator(request, iterator);
2567
+ }
2568
+
2569
+ return renderFragment(request, task, Array.from(iterator));
2570
+ }
2571
+
2572
+
2573
+ var proto = getPrototypeOf(value);
2574
+
2575
+ if (proto !== ObjectPrototype && (proto === null || getPrototypeOf(proto) !== null)) {
2576
+ 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.');
2577
+ }
2578
+
2579
+ {
2580
+ if (objectName(value) !== 'Object') {
2581
+ error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, parentPropertyName));
2582
+ } else if (!isSimpleObject(value)) {
2583
+ 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));
2584
+ } else if (Object.getOwnPropertySymbols) {
2585
+ var symbols = Object.getOwnPropertySymbols(value);
2586
+
2587
+ if (symbols.length > 0) {
2588
+ 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));
2589
+ }
2590
+ }
2591
+ } // $FlowFixMe[incompatible-return]
2592
+
2593
+
2594
+ return value;
2595
+ }
2596
+
2597
+ if (typeof value === 'string') {
2598
+
2599
+
2600
+ if (value[value.length - 1] === 'Z') {
2601
+ // Possibly a Date, whose toJSON automatically calls toISOString
2602
+ // $FlowFixMe[incompatible-use]
2603
+ var originalValue = parent[parentPropertyName];
2604
+
2605
+ if (originalValue instanceof Date) {
2606
+ return serializeDateFromDateJSON(value);
2607
+ }
2608
+ }
2609
+
2610
+ if (value.length >= 1024) {
2611
+ // For large strings, we encode them outside the JSON payload so that we
2612
+ // don't have to double encode and double parse the strings. This can also
2613
+ // be more compact in case the string has a lot of escaped characters.
2614
+ return serializeLargeTextString(request, value);
2615
+ }
2616
+
2617
+ return escapeStringValue(value);
2618
+ }
2619
+
2620
+ if (typeof value === 'boolean') {
2621
+ return value;
2622
+ }
2623
+
2624
+ if (typeof value === 'number') {
2625
+ return serializeNumber(value);
2626
+ }
2627
+
2628
+ if (typeof value === 'undefined') {
2629
+ return serializeUndefined();
2630
+ }
2631
+
2632
+ if (typeof value === 'function') {
2633
+ if (isClientReference(value)) {
2634
+ return serializeClientReference(request, parent, parentPropertyName, value);
2635
+ }
2636
+
2637
+ if (isServerReference(value)) {
2638
+ return serializeServerReference(request, value);
2639
+ }
2640
+
2641
+ if (isTemporaryReference(value)) {
2642
+ return serializeTemporaryReference(request, value);
2643
+ }
2644
+
2645
+ if (/^on[A-Z]/.test(parentPropertyName)) {
2646
+ 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.');
2647
+ } else if ((jsxChildrenParents.has(parent) || jsxPropsParents.has(parent) && parentPropertyName === 'children')) {
2648
+ var componentName = value.displayName || value.name || 'Component';
2649
+ 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));
2650
+ } else {
2651
+ 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));
2652
+ }
2653
+ }
2654
+
2655
+ if (typeof value === 'symbol') {
2656
+ var writtenSymbols = request.writtenSymbols;
2657
+
2658
+ var _existingId2 = writtenSymbols.get(value);
2659
+
2660
+ if (_existingId2 !== undefined) {
2661
+ return serializeByValueID(_existingId2);
2662
+ } // $FlowFixMe[incompatible-type] `description` might be undefined
2663
+
2664
+
2665
+ var name = value.description;
2666
+
2667
+ if (Symbol.for(name) !== value) {
2668
+ 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
2669
+ value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, parentPropertyName));
2670
+ }
2671
+
2672
+ request.pendingChunks++;
2673
+ var symbolId = request.nextChunkId++;
2674
+ emitSymbolChunk(request, symbolId, name);
2675
+ writtenSymbols.set(value, symbolId);
2676
+ return serializeByValueID(symbolId);
2677
+ }
2678
+
2679
+ if (typeof value === 'bigint') {
2680
+
2681
+ return serializeBigInt(value);
2682
+ }
2683
+
2684
+ throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName));
2685
+ }
2686
+
2687
+ function logPostpone(request, reason) {
2688
+ var prevRequest = currentRequest;
2689
+ currentRequest = null;
2690
+
2691
+ try {
2692
+ var onPostpone = request.onPostpone;
2693
+
2694
+ if (supportsRequestStorage) ; else {
2695
+ onPostpone(reason);
2696
+ }
2697
+ } finally {
2698
+ currentRequest = prevRequest;
2699
+ }
2700
+ }
2701
+
2702
+ function logRecoverableError(request, error) {
2703
+ var prevRequest = currentRequest;
2704
+ currentRequest = null;
2705
+ var errorDigest;
2706
+
2707
+ try {
2708
+ var onError = request.onError;
2709
+
2710
+ if (supportsRequestStorage) ; else {
2711
+ errorDigest = onError(error);
2712
+ }
2713
+ } finally {
2714
+ currentRequest = prevRequest;
2715
+ }
2716
+
2717
+ if (errorDigest != null && typeof errorDigest !== 'string') {
2718
+ // eslint-disable-next-line react-internal/prod-error-codes
2719
+ 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");
2720
+ }
2721
+
2722
+ return errorDigest || '';
2723
+ }
2724
+
2725
+ function fatalError(request, error) {
2726
+
2727
+
2728
+ if (request.destination !== null) {
2729
+ request.status = CLOSED;
2730
+ closeWithError(request.destination, error);
2731
+ } else {
2732
+ request.status = CLOSING;
2733
+ request.fatalError = error;
2734
+ }
2735
+ }
2736
+
2737
+ function emitPostponeChunk(request, id, postponeInstance) {
2738
+ var row;
2739
+
2740
+ {
2741
+ var reason = '';
2742
+ var stack = '';
2743
+
2744
+ try {
2745
+ // eslint-disable-next-line react-internal/safe-string-coercion
2746
+ reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion
2747
+
2748
+ stack = String(postponeInstance.stack);
2749
+ } catch (x) {}
2750
+
2751
+ row = serializeRowHeader('P', id) + stringify({
2752
+ reason: reason,
2753
+ stack: stack
2754
+ }) + '\n';
2755
+ }
2756
+
2757
+ var processedChunk = stringToChunk(row);
2758
+ request.completedErrorChunks.push(processedChunk);
2759
+ }
2760
+
2761
+ function emitErrorChunk(request, id, digest, error) {
2762
+ var errorInfo;
2763
+
2764
+ {
2765
+ var message;
2766
+ var stack = '';
2767
+
2768
+ try {
2769
+ if (error instanceof Error) {
2770
+ // eslint-disable-next-line react-internal/safe-string-coercion
2771
+ message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
2772
+
2773
+ stack = String(error.stack);
2774
+ } else if (typeof error === 'object' && error !== null) {
2775
+ message = describeObjectForErrorMessage(error);
2776
+ } else {
2777
+ // eslint-disable-next-line react-internal/safe-string-coercion
2778
+ message = String(error);
1822
2779
  }
2780
+ } catch (x) {
2781
+ message = 'An error occurred but serializing the error message failed.';
2782
+ }
2783
+
2784
+ errorInfo = {
2785
+ digest: digest,
2786
+ message: message,
2787
+ stack: stack
2788
+ };
2789
+ }
2790
+
2791
+ var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
2792
+ var processedChunk = stringToChunk(row);
2793
+ request.completedErrorChunks.push(processedChunk);
2794
+ }
2795
+
2796
+ function emitImportChunk(request, id, clientReferenceMetadata) {
2797
+ // $FlowFixMe[incompatible-type] stringify can return null
2798
+ var json = stringify(clientReferenceMetadata);
2799
+ var row = serializeRowHeader('I', id) + json + '\n';
2800
+ var processedChunk = stringToChunk(row);
2801
+ request.completedImportChunks.push(processedChunk);
2802
+ }
2803
+
2804
+ function emitHintChunk(request, code, model) {
2805
+ var json = stringify(model);
2806
+ var id = request.nextChunkId++;
2807
+ var row = serializeRowHeader('H' + code, id) + json + '\n';
2808
+ var processedChunk = stringToChunk(row);
2809
+ request.completedHintChunks.push(processedChunk);
2810
+ }
2811
+
2812
+ function emitSymbolChunk(request, id, name) {
2813
+ var symbolReference = serializeSymbolReference(name);
2814
+ var processedChunk = encodeReferenceChunk(request, id, symbolReference);
2815
+ request.completedImportChunks.push(processedChunk);
2816
+ }
2817
+
2818
+ function emitModelChunk(request, id, json) {
2819
+ var row = id.toString(16) + ':' + json + '\n';
2820
+ var processedChunk = stringToChunk(row);
2821
+ request.completedRegularChunks.push(processedChunk);
2822
+ }
2823
+
2824
+ function emitDebugChunk(request, id, debugInfo) {
2825
+ // use the full serialization that requires a task.
2826
+
2827
+
2828
+ var counter = {
2829
+ objectCount: 0
2830
+ };
2831
+
2832
+ function replacer(parentPropertyName, value) {
2833
+ return renderConsoleValue(request, counter, this, parentPropertyName, value);
2834
+ } // $FlowFixMe[incompatible-type] stringify can return null
2835
+
2836
+
2837
+ var json = stringify(debugInfo, replacer);
2838
+ var row = serializeRowHeader('D', id) + json + '\n';
2839
+ var processedChunk = stringToChunk(row);
2840
+ request.completedRegularChunks.push(processedChunk);
2841
+ }
2842
+
2843
+ function emitTextChunk(request, id, text) {
2844
+ request.pendingChunks++; // Extra chunk for the header.
2845
+
2846
+ var textChunk = stringToChunk(text);
2847
+ var binaryLength = byteLengthOfChunk(textChunk);
2848
+ var row = id.toString(16) + ':T' + binaryLength.toString(16) + ',';
2849
+ var headerChunk = stringToChunk(row);
2850
+ request.completedRegularChunks.push(headerChunk, textChunk);
2851
+ }
2852
+
2853
+ function serializeEval(source) {
2854
+
2855
+ return '$E' + source;
2856
+ } // This is a forked version of renderModel which should never error, never suspend and is limited
2857
+ // in the depth it can encode.
2858
+
2859
+
2860
+ function renderConsoleValue(request, counter, parent, parentPropertyName, value) {
2861
+ // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
2862
+ // $FlowFixMe[incompatible-use]
2863
+ var originalValue = parent[parentPropertyName];
2864
+
2865
+ if (value === null) {
2866
+ return null;
2867
+ }
2868
+
2869
+ if (typeof value === 'object') {
2870
+ if (isClientReference(value)) {
2871
+ // We actually have this value on the client so we could import it.
2872
+ // This might be confusing though because on the Server it won't actually
2873
+ // be this value, so if you're debugging client references maybe you'd be
2874
+ // better with a place holder.
2875
+ return serializeClientReference(request, parent, parentPropertyName, value);
2876
+ }
2877
+
2878
+ if (counter.objectCount > 20) {
2879
+ // We've reached our max number of objects to serialize across the wire so we serialize this
2880
+ // object but no properties inside of it, as a place holder.
2881
+ return Array.isArray(value) ? [] : {};
2882
+ }
2883
+
2884
+ counter.objectCount++;
2885
+ var writtenObjects = request.writtenObjects;
2886
+ var existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
2887
+
2888
+ if (typeof value.then === 'function') {
2889
+ if (existingId !== undefined) {
2890
+ // We've seen this promise before, so we can just refer to the same result.
2891
+ return serializePromiseID(existingId);
2892
+ }
2893
+
2894
+ var thenable = value;
2895
+
2896
+ switch (thenable.status) {
2897
+ case 'fulfilled':
2898
+ {
2899
+ return serializePromiseID(outlineConsoleValue(request, counter, thenable.value));
2900
+ }
2901
+
2902
+ case 'rejected':
2903
+ {
2904
+ var x = thenable.reason;
2905
+ request.pendingChunks++;
2906
+ var errorId = request.nextChunkId++;
2907
+
2908
+ {
2909
+ // We don't log these errors since they didn't actually throw into Flight.
2910
+ var digest = '';
2911
+ emitErrorChunk(request, errorId, digest, x);
2912
+ }
2913
+
2914
+ return serializePromiseID(errorId);
2915
+ }
2916
+ } // If it hasn't already resolved (and been instrumented) we just encode an infinite
2917
+ // promise that will never resolve.
2918
+
1823
2919
 
1824
- return serializeByValueID(providerId);
1825
- } else if (value === POP) {
1826
- popProvider();
2920
+ return serializeInfinitePromise();
2921
+ }
1827
2922
 
1828
- {
1829
- insideContextProps = null;
1830
- isInsideContextValue = false;
1831
- }
2923
+ if (existingId !== undefined && existingId >= 0) {
2924
+ // We've already emitted this as a real object, so we can
2925
+ // just refer to that by its existing ID.
2926
+ return serializeByValueID(existingId);
2927
+ }
1832
2928
 
1833
- return undefined;
2929
+ if (isArray(value)) {
2930
+ return value;
2931
+ }
2932
+
2933
+ if (value instanceof Map) {
2934
+ return serializeMap(request, value);
1834
2935
  }
1835
2936
 
1836
- if (!isArray(value)) {
1837
- var iteratorFn = getIteratorFn(value);
2937
+ if (value instanceof Set) {
2938
+ return serializeSet(request, value);
2939
+ } // TODO: FormData is not available in old Node. Remove the typeof later.
1838
2940
 
1839
- if (iteratorFn) {
1840
- return Array.from(value);
1841
- }
2941
+
2942
+ if (typeof FormData === 'function' && value instanceof FormData) {
2943
+ return serializeFormData(request, value);
1842
2944
  }
1843
2945
 
1844
- {
1845
- if (value !== null && !isArray(value)) {
1846
- // Verify that this is a simple plain object.
1847
- if (objectName(value) !== 'Object') {
1848
- error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key));
1849
- } else if (!isSimpleObject(value)) {
1850
- 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));
1851
- } else if (Object.getOwnPropertySymbols) {
1852
- var symbols = Object.getOwnPropertySymbols(value);
1853
-
1854
- if (symbols.length > 0) {
1855
- 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));
1856
- }
1857
- }
1858
- }
2946
+ var iteratorFn = getIteratorFn(value);
2947
+
2948
+ if (iteratorFn) {
2949
+ return Array.from(value);
1859
2950
  } // $FlowFixMe[incompatible-return]
1860
2951
 
1861
2952
 
@@ -1863,17 +2954,20 @@ function resolveModelToJSON(request, parent, key, value) {
1863
2954
  }
1864
2955
 
1865
2956
  if (typeof value === 'string') {
1866
- // TODO: Maybe too clever. If we support URL there's no similar trick.
1867
2957
  if (value[value.length - 1] === 'Z') {
1868
2958
  // Possibly a Date, whose toJSON automatically calls toISOString
1869
- // $FlowFixMe[incompatible-use]
1870
- var _originalValue = parent[key]; // $FlowFixMe[method-unbinding]
1871
-
1872
- if (_originalValue instanceof Date) {
2959
+ if (originalValue instanceof Date) {
1873
2960
  return serializeDateFromDateJSON(value);
1874
2961
  }
1875
2962
  }
1876
2963
 
2964
+ if (value.length >= 1024) {
2965
+ // For large strings, we encode them outside the JSON payload so that we
2966
+ // don't have to double encode and double parse the strings. This can also
2967
+ // be more compact in case the string has a lot of escaped characters.
2968
+ return serializeLargeTextString(request, value);
2969
+ }
2970
+
1877
2971
  return escapeStringValue(value);
1878
2972
  }
1879
2973
 
@@ -1891,40 +2985,33 @@ function resolveModelToJSON(request, parent, key, value) {
1891
2985
 
1892
2986
  if (typeof value === 'function') {
1893
2987
  if (isClientReference(value)) {
1894
- return serializeClientReference(request, parent, key, value);
2988
+ return serializeClientReference(request, parent, parentPropertyName, value);
1895
2989
  }
1896
2990
 
1897
- if (isServerReference(value)) {
1898
- return serializeServerReference(request, parent, key, value);
1899
- }
2991
+ if (isTemporaryReference(value)) {
2992
+ return serializeTemporaryReference(request, value);
2993
+ } // Serialize the body of the function as an eval so it can be printed.
2994
+ // $FlowFixMe[method-unbinding]
1900
2995
 
1901
- if (/^on[A-Z]/.test(key)) {
1902
- 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.');
1903
- } else {
1904
- 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));
1905
- }
2996
+
2997
+ return serializeEval('(' + Function.prototype.toString.call(value) + ')');
1906
2998
  }
1907
2999
 
1908
3000
  if (typeof value === 'symbol') {
1909
3001
  var writtenSymbols = request.writtenSymbols;
1910
- var existingId = writtenSymbols.get(value);
1911
3002
 
1912
- if (existingId !== undefined) {
1913
- return serializeByValueID(existingId);
1914
- } // $FlowFixMe[incompatible-type] `description` might be undefined
3003
+ var _existingId3 = writtenSymbols.get(value);
1915
3004
 
3005
+ if (_existingId3 !== undefined) {
3006
+ return serializeByValueID(_existingId3);
3007
+ } // $FlowFixMe[incompatible-type] `description` might be undefined
1916
3008
 
1917
- var name = value.description;
1918
3009
 
1919
- if (Symbol.for(name) !== value) {
1920
- 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
1921
- value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key));
1922
- }
3010
+ var name = value.description; // We use the Symbol.for version if it's not a global symbol. Close enough.
1923
3011
 
1924
3012
  request.pendingChunks++;
1925
3013
  var symbolId = request.nextChunkId++;
1926
3014
  emitSymbolChunk(request, symbolId, name);
1927
- writtenSymbols.set(value, symbolId);
1928
3015
  return serializeByValueID(symbolId);
1929
3016
  }
1930
3017
 
@@ -1932,88 +3019,53 @@ function resolveModelToJSON(request, parent, key, value) {
1932
3019
  return serializeBigInt(value);
1933
3020
  }
1934
3021
 
1935
- throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key));
1936
- }
1937
-
1938
- function logRecoverableError(request, error) {
1939
- var onError = request.onError;
1940
- var errorDigest = onError(error);
1941
-
1942
- if (errorDigest != null && typeof errorDigest !== 'string') {
1943
- // eslint-disable-next-line react-internal/prod-error-codes
1944
- 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");
1945
- }
1946
-
1947
- return errorDigest || '';
3022
+ return 'unknown type ' + typeof value;
1948
3023
  }
1949
3024
 
1950
- function getErrorMessageAndStackDev(error) {
1951
- {
1952
- var message;
1953
- var stack = '';
3025
+ function outlineConsoleValue(request, counter, model) {
1954
3026
 
3027
+ function replacer(parentPropertyName, value) {
1955
3028
  try {
1956
- if (error instanceof Error) {
1957
- // eslint-disable-next-line react-internal/safe-string-coercion
1958
- message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
1959
-
1960
- stack = String(error.stack);
1961
- } else {
1962
- message = 'Error: ' + error;
1963
- }
3029
+ return renderConsoleValue(request, counter, this, parentPropertyName, value);
1964
3030
  } catch (x) {
1965
- message = 'An error occurred but serializing the error message failed.';
3031
+ return 'unknown value';
1966
3032
  }
3033
+ } // $FlowFixMe[incompatible-type] stringify can return null
1967
3034
 
1968
- return {
1969
- message: message,
1970
- stack: stack
1971
- };
1972
- }
3035
+
3036
+ var json = stringify(model, replacer);
3037
+ request.pendingChunks++;
3038
+ var id = request.nextChunkId++;
3039
+ var row = id.toString(16) + ':' + json + '\n';
3040
+ var processedChunk = stringToChunk(row);
3041
+ request.completedRegularChunks.push(processedChunk);
3042
+ return id;
1973
3043
  }
1974
3044
 
1975
- function fatalError(request, error) {
1976
- // This is called outside error handling code such as if an error happens in React internals.
1977
- if (request.destination !== null) {
1978
- request.status = CLOSED;
1979
- closeWithError(request.destination, error);
1980
- } else {
1981
- request.status = CLOSING;
1982
- request.fatalError = error;
3045
+ function forwardDebugInfo(request, id, debugInfo) {
3046
+ for (var i = 0; i < debugInfo.length; i++) {
3047
+ request.pendingChunks++;
3048
+ emitDebugChunk(request, id, debugInfo[i]);
1983
3049
  }
1984
3050
  }
1985
3051
 
1986
- function emitErrorChunkProd(request, id, digest) {
1987
- var processedChunk = processErrorChunkProd();
1988
- request.completedErrorChunks.push(processedChunk);
1989
- }
3052
+ function emitChunk(request, task, value) {
3053
+ var id = task.id; // For certain types we have special types, we typically outlined them but
3054
+ // we can emit them directly for this row instead of through an indirection.
1990
3055
 
1991
- function emitErrorChunkDev(request, id, digest, message, stack) {
1992
- var processedChunk = processErrorChunkDev(request, id, digest, message, stack);
1993
- request.completedErrorChunks.push(processedChunk);
1994
- }
3056
+ if (typeof value === 'string') {
1995
3057
 
1996
- function emitImportChunk(request, id, clientReferenceMetadata) {
1997
- var processedChunk = processImportChunk(request, id, clientReferenceMetadata);
1998
- request.completedImportChunks.push(processedChunk);
1999
- }
3058
+ emitTextChunk(request, id, value);
3059
+ return;
3060
+ }
3061
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2000
3062
 
2001
- function emitHintChunk(request, code, model) {
2002
- var processedChunk = processHintChunk(request, request.nextChunkId++, code, model);
2003
- request.completedHintChunks.push(processedChunk);
2004
- }
2005
3063
 
2006
- function emitSymbolChunk(request, id, name) {
2007
- var symbolReference = serializeSymbolReference(name);
2008
- var processedChunk = processReferenceChunk(request, id, symbolReference);
2009
- request.completedImportChunks.push(processedChunk);
3064
+ var json = stringify(value, task.toJSON);
3065
+ emitModelChunk(request, task.id, json);
2010
3066
  }
2011
3067
 
2012
- function emitProviderChunk(request, id, contextName) {
2013
- var contextReference = serializeProviderReference(contextName);
2014
- var processedChunk = processReferenceChunk(request, id, contextReference);
2015
- request.completedJSONChunks.push(processedChunk);
2016
- }
3068
+ var emptyRoot = {};
2017
3069
 
2018
3070
  function retryTask(request, task) {
2019
3071
  if (task.status !== PENDING$1) {
@@ -2021,38 +3073,47 @@ function retryTask(request, task) {
2021
3073
  return;
2022
3074
  }
2023
3075
 
2024
- switchContext(task.context);
3076
+ var prevDebugID = debugID;
2025
3077
 
2026
3078
  try {
2027
- var value = task.model;
2028
-
2029
- if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2030
- // TODO: Concatenate keys of parents onto children.
2031
- var element = value; // When retrying a component, reuse the thenableState from the
2032
- // previous attempt.
2033
-
2034
- var prevThenableState = task.thenableState; // Attempt to render the Server Component.
2035
- // Doing this here lets us reuse this same task if the next component
2036
- // also suspends.
2037
-
2038
- task.model = value;
2039
- value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering
2040
- // using the same task, but we reset its thenable state before continuing.
2041
-
2042
- task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate
2043
- // from the render above because we don't need to reset the thenable state
2044
- // until the next time something suspends and retries.
2045
-
2046
- while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) {
2047
- // TODO: Concatenate keys of parents onto children.
2048
- var nextElement = value;
2049
- task.model = value;
2050
- value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null);
2051
- }
3079
+ // Track the root so we know that we have to emit this object even though it
3080
+ // already has an ID. This is needed because we might see this object twice
3081
+ // in the same toJSON if it is cyclic.
3082
+ modelRoot = task.model;
3083
+
3084
+ if (true) {
3085
+ // Track the ID of the current task so we can assign debug info to this id.
3086
+ debugID = task.id;
3087
+ } // We call the destructive form that mutates this task. That way if something
3088
+ // suspends again, we can reuse the same task instead of spawning a new one.
3089
+
3090
+
3091
+ var resolvedModel = renderModelDestructive(request, task, emptyRoot, '', task.model);
3092
+
3093
+ if (true) {
3094
+ // We're now past rendering this task and future renders will spawn new tasks for their
3095
+ // debug info.
3096
+ debugID = null;
3097
+ } // Track the root again for the resolved object.
3098
+
3099
+
3100
+ modelRoot = resolvedModel; // The keyPath resets at any terminal child node.
3101
+
3102
+ task.keyPath = null;
3103
+ task.implicitSlot = false;
3104
+
3105
+ if (typeof resolvedModel === 'object' && resolvedModel !== null) {
3106
+ // Object might contain unresolved values like additional elements.
3107
+ // This is simulating what the JSON loop would do if this was part of it.
3108
+ emitChunk(request, task, resolvedModel);
3109
+ } else {
3110
+ // If the value is a string, it means it's a terminal value and we already escaped it
3111
+ // We don't need to escape it again so it's not passed the toJSON replacer.
3112
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
3113
+ var json = stringify(resolvedModel);
3114
+ emitModelChunk(request, task.id, json);
2052
3115
  }
2053
3116
 
2054
- var processedChunk = processModelChunk(request, task.id, value);
2055
- request.completedJSONChunks.push(processedChunk);
2056
3117
  request.abortableTasks.delete(task);
2057
3118
  task.status = COMPLETED;
2058
3119
  } catch (thrownValue) {
@@ -2061,33 +3122,33 @@ function retryTask(request, task) {
2061
3122
  // value to be a thenable, because before `use` existed that was the
2062
3123
  // (unstable) API for suspending. This implementation detail can change
2063
3124
  // later, once we deprecate the old API in favor of `use`.
2064
- getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding]
2065
-
2066
- if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
2067
- // Something suspended again, let's pick it back up later.
2068
- var ping = task.ping;
2069
- x.then(ping, ping);
2070
- task.thenableState = getThenableStateAfterSuspending();
2071
- return;
2072
- } else {
2073
- request.abortableTasks.delete(task);
2074
- task.status = ERRORED$1;
2075
- var digest = logRecoverableError(request, x);
2076
-
2077
- {
2078
- var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x),
2079
- message = _getErrorMessageAndSt5.message,
2080
- stack = _getErrorMessageAndSt5.stack;
3125
+ getSuspendedThenable() : thrownValue;
2081
3126
 
2082
- emitErrorChunkDev(request, task.id, digest, message, stack);
3127
+ if (typeof x === 'object' && x !== null) {
3128
+ // $FlowFixMe[method-unbinding]
3129
+ if (typeof x.then === 'function') {
3130
+ // Something suspended again, let's pick it back up later.
3131
+ var ping = task.ping;
3132
+ x.then(ping, ping);
3133
+ task.thenableState = getThenableStateAfterSuspending();
3134
+ return;
2083
3135
  }
2084
3136
  }
3137
+
3138
+ request.abortableTasks.delete(task);
3139
+ task.status = ERRORED$1;
3140
+ var digest = logRecoverableError(request, x);
3141
+ emitErrorChunk(request, task.id, digest, x);
3142
+ } finally {
3143
+ {
3144
+ debugID = prevDebugID;
3145
+ }
2085
3146
  }
2086
3147
  }
2087
3148
 
2088
3149
  function performWork(request) {
2089
- var prevDispatcher = ReactCurrentDispatcher.current;
2090
- ReactCurrentDispatcher.current = HooksDispatcher;
3150
+ var prevDispatcher = ReactSharedInternals.H;
3151
+ ReactSharedInternals.H = HooksDispatcher;
2091
3152
  var prevRequest = currentRequest;
2092
3153
  currentRequest = request;
2093
3154
  prepareToUseHooksForRequest(request);
@@ -2108,7 +3169,7 @@ function performWork(request) {
2108
3169
  logRecoverableError(request, error);
2109
3170
  fatalError(request, error);
2110
3171
  } finally {
2111
- ReactCurrentDispatcher.current = prevDispatcher;
3172
+ ReactSharedInternals.H = prevDispatcher;
2112
3173
  resetHooksForRequest();
2113
3174
  currentRequest = prevRequest;
2114
3175
  }
@@ -2119,7 +3180,7 @@ function abortTask(task, request, errorId) {
2119
3180
  // has a single value referencing the error.
2120
3181
 
2121
3182
  var ref = serializeByValueID(errorId);
2122
- var processedChunk = processReferenceChunk(request, task.id, ref);
3183
+ var processedChunk = encodeReferenceChunk(request, task.id, ref);
2123
3184
  request.completedErrorChunks.push(processedChunk);
2124
3185
  }
2125
3186
 
@@ -2163,12 +3224,12 @@ function flushCompletedChunks(request, destination) {
2163
3224
 
2164
3225
  hintChunks.splice(0, i); // Next comes model data.
2165
3226
 
2166
- var jsonChunks = request.completedJSONChunks;
3227
+ var regularChunks = request.completedRegularChunks;
2167
3228
  i = 0;
2168
3229
 
2169
- for (; i < jsonChunks.length; i++) {
3230
+ for (; i < regularChunks.length; i++) {
2170
3231
  request.pendingChunks--;
2171
- var _chunk2 = jsonChunks[i];
3232
+ var _chunk2 = regularChunks[i];
2172
3233
 
2173
3234
  var _keepWriting2 = writeChunkAndReturn(destination, _chunk2);
2174
3235
 
@@ -2179,7 +3240,7 @@ function flushCompletedChunks(request, destination) {
2179
3240
  }
2180
3241
  }
2181
3242
 
2182
- jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
3243
+ regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
2183
3244
  // any error messages and prioritize display of other parts of
2184
3245
  // the page.
2185
3246
 
@@ -2206,8 +3267,9 @@ function flushCompletedChunks(request, destination) {
2206
3267
  }
2207
3268
 
2208
3269
  if (request.pendingChunks === 0) {
2209
- // We're done.
3270
+
2210
3271
  close$1(destination);
3272
+ request.destination = null;
2211
3273
  }
2212
3274
  }
2213
3275
 
@@ -2258,26 +3320,24 @@ function startFlowing(request, destination) {
2258
3320
  logRecoverableError(request, error);
2259
3321
  fatalError(request, error);
2260
3322
  }
3323
+ }
3324
+ function stopFlowing(request) {
3325
+ request.destination = null;
2261
3326
  } // This is called to early terminate a request. It creates an error at all pending tasks.
2262
3327
 
2263
3328
  function abort(request, reason) {
2264
3329
  try {
2265
- var abortableTasks = request.abortableTasks;
3330
+ var abortableTasks = request.abortableTasks; // We have tasks to abort. We'll emit one error row and then emit a reference
3331
+ // to that row from every row that's still remaining.
2266
3332
 
2267
3333
  if (abortableTasks.size > 0) {
2268
- // We have tasks to abort. We'll emit one error row and then emit a reference
2269
- // to that row from every row that's still remaining.
2270
- var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
2271
- var digest = logRecoverableError(request, error);
2272
3334
  request.pendingChunks++;
2273
3335
  var errorId = request.nextChunkId++;
2274
3336
 
2275
- if (true) {
2276
- var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error),
2277
- message = _getErrorMessageAndSt6.message,
2278
- stack = _getErrorMessageAndSt6.stack;
2279
-
2280
- emitErrorChunkDev(request, errorId, digest, message, stack);
3337
+ var postponeInstance; if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
3338
+ var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
3339
+ var digest = logRecoverableError(request, error);
3340
+ emitErrorChunk(request, errorId, digest, error);
2281
3341
  }
2282
3342
 
2283
3343
  abortableTasks.forEach(function (task) {
@@ -2286,6 +3346,21 @@ function abort(request, reason) {
2286
3346
  abortableTasks.clear();
2287
3347
  }
2288
3348
 
3349
+ var abortListeners = request.abortListeners;
3350
+
3351
+ if (abortListeners.size > 0) {
3352
+ var _error;
3353
+
3354
+ if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
3355
+ _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
3356
+ }
3357
+
3358
+ abortListeners.forEach(function (callback) {
3359
+ return callback(_error);
3360
+ });
3361
+ abortListeners.clear();
3362
+ }
3363
+
2289
3364
  if (request.destination !== null) {
2290
3365
  flushCompletedChunks(request, request.destination);
2291
3366
  }
@@ -2295,28 +3370,20 @@ function abort(request, reason) {
2295
3370
  }
2296
3371
  }
2297
3372
 
2298
- function importServerContexts(contexts) {
2299
- if (contexts) {
2300
- var prevContext = getActiveContext();
2301
- switchContext(rootContextSnapshot);
2302
-
2303
- for (var i = 0; i < contexts.length; i++) {
2304
- var _contexts$i = contexts[i],
2305
- name = _contexts$i[0],
2306
- value = _contexts$i[1];
2307
- var context = getOrCreateServerContext(name);
2308
- pushProvider(context, value);
2309
- }
2310
-
2311
- var importedContext = getActiveContext();
2312
- switchContext(prevContext);
2313
- return importedContext;
2314
- }
2315
-
2316
- return rootContextSnapshot;
3373
+ // This is the parsed shape of the wire format which is why it is
3374
+ // condensed to only the essentialy information
3375
+ var ID = 0;
3376
+ var CHUNKS = 1;
3377
+ var NAME = 2; // export const ASYNC = 3;
3378
+ // This logic is correct because currently only include the 4th tuple member
3379
+ // when the module is async. If that changes we will need to actually assert
3380
+ // the value is true. We don't index into the 4th slot because flow does not
3381
+ // like the potential out of bounds access
3382
+
3383
+ function isAsyncImport(metadata) {
3384
+ return metadata.length === 4;
2317
3385
  }
2318
3386
 
2319
- // eslint-disable-next-line no-unused-vars
2320
3387
  function resolveServerReference(bundlerConfig, id) {
2321
3388
  var name = '';
2322
3389
  var resolvedModuleData = bundlerConfig[id];
@@ -2342,19 +3409,38 @@ function resolveServerReference(bundlerConfig, id) {
2342
3409
  } // TODO: This needs to return async: true if it's an async module.
2343
3410
 
2344
3411
 
2345
- return {
2346
- id: resolvedModuleData.id,
2347
- chunks: resolvedModuleData.chunks,
2348
- name: name,
2349
- async: false
2350
- };
3412
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
2351
3413
  } // The chunk cache contains all the chunks we've preloaded so far.
2352
3414
  // If they're still pending they're a thenable. This map also exists
2353
3415
  // in Webpack but unfortunately it's not exposed so we have to
2354
3416
  // replicate it in user space. null means that it has already loaded.
2355
3417
 
2356
3418
  var chunkCache = new Map();
2357
- var asyncModuleCache = new Map();
3419
+
3420
+ function requireAsyncModule(id) {
3421
+ // We've already loaded all the chunks. We can require the module.
3422
+ var promise = __webpack_require__(id);
3423
+
3424
+ if (typeof promise.then !== 'function') {
3425
+ // This wasn't a promise after all.
3426
+ return null;
3427
+ } else if (promise.status === 'fulfilled') {
3428
+ // This module was already resolved earlier.
3429
+ return null;
3430
+ } else {
3431
+ // Instrument the Promise to stash the result.
3432
+ promise.then(function (value) {
3433
+ var fulfilledThenable = promise;
3434
+ fulfilledThenable.status = 'fulfilled';
3435
+ fulfilledThenable.value = value;
3436
+ }, function (reason) {
3437
+ var rejectedThenable = promise;
3438
+ rejectedThenable.status = 'rejected';
3439
+ rejectedThenable.reason = reason;
3440
+ });
3441
+ return promise;
3442
+ }
3443
+ }
2358
3444
 
2359
3445
  function ignoreReject() {// We rely on rejected promises to be handled by another listener.
2360
3446
  } // Start preloading the modules since we might need them soon.
@@ -2362,16 +3448,17 @@ function ignoreReject() {// We rely on rejected promises to be handled by anothe
2362
3448
 
2363
3449
 
2364
3450
  function preloadModule(metadata) {
2365
- var chunks = metadata.chunks;
3451
+ var chunks = metadata[CHUNKS];
2366
3452
  var promises = [];
3453
+ var i = 0;
2367
3454
 
2368
- for (var i = 0; i < chunks.length; i++) {
2369
- var chunkId = chunks[i];
3455
+ while (i < chunks.length) {
3456
+ var chunkId = chunks[i++];
3457
+ var chunkFilename = chunks[i++];
2370
3458
  var entry = chunkCache.get(chunkId);
2371
3459
 
2372
3460
  if (entry === undefined) {
2373
- var thenable = __webpack_chunk_load__(chunkId);
2374
-
3461
+ var thenable = loadChunk(chunkId, chunkFilename);
2375
3462
  promises.push(thenable); // $FlowFixMe[method-unbinding]
2376
3463
 
2377
3464
  var resolve = chunkCache.set.bind(chunkCache, chunkId, null);
@@ -2382,30 +3469,13 @@ function preloadModule(metadata) {
2382
3469
  }
2383
3470
  }
2384
3471
 
2385
- if (metadata.async) {
2386
- var existingPromise = asyncModuleCache.get(metadata.id);
2387
-
2388
- if (existingPromise) {
2389
- if (existingPromise.status === 'fulfilled') {
2390
- return null;
2391
- }
2392
-
2393
- return existingPromise;
3472
+ if (isAsyncImport(metadata)) {
3473
+ if (promises.length === 0) {
3474
+ return requireAsyncModule(metadata[ID]);
2394
3475
  } else {
2395
- var modulePromise = Promise.all(promises).then(function () {
2396
- return __webpack_require__(metadata.id);
2397
- });
2398
- modulePromise.then(function (value) {
2399
- var fulfilledThenable = modulePromise;
2400
- fulfilledThenable.status = 'fulfilled';
2401
- fulfilledThenable.value = value;
2402
- }, function (reason) {
2403
- var rejectedThenable = modulePromise;
2404
- rejectedThenable.status = 'rejected';
2405
- rejectedThenable.reason = reason;
3476
+ return Promise.all(promises).then(function () {
3477
+ return requireAsyncModule(metadata[ID]);
2406
3478
  });
2407
- asyncModuleCache.set(metadata.id, modulePromise);
2408
- return modulePromise;
2409
3479
  }
2410
3480
  } else if (promises.length > 0) {
2411
3481
  return Promise.all(promises);
@@ -2416,35 +3486,53 @@ function preloadModule(metadata) {
2416
3486
  // Increase priority if necessary.
2417
3487
 
2418
3488
  function requireModule(metadata) {
2419
- var moduleExports;
3489
+ var moduleExports = __webpack_require__(metadata[ID]);
2420
3490
 
2421
- if (metadata.async) {
2422
- // We assume that preloadModule has been called before, which
2423
- // should have added something to the module cache.
2424
- var promise = asyncModuleCache.get(metadata.id);
2425
-
2426
- if (promise.status === 'fulfilled') {
2427
- moduleExports = promise.value;
3491
+ if (isAsyncImport(metadata)) {
3492
+ if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') {
3493
+ // This Promise should've been instrumented by preloadModule.
3494
+ moduleExports = moduleExports.value;
2428
3495
  } else {
2429
- throw promise.reason;
3496
+ throw moduleExports.reason;
2430
3497
  }
2431
- } else {
2432
- moduleExports = __webpack_require__(metadata.id);
2433
3498
  }
2434
3499
 
2435
- if (metadata.name === '*') {
3500
+ if (metadata[NAME] === '*') {
2436
3501
  // This is a placeholder value that represents that the caller imported this
2437
3502
  // as a CommonJS module as is.
2438
3503
  return moduleExports;
2439
3504
  }
2440
3505
 
2441
- if (metadata.name === '') {
3506
+ if (metadata[NAME] === '') {
2442
3507
  // This is a placeholder value that represents that the caller accessed the
2443
3508
  // default property of this if it was an ESM interop module.
2444
3509
  return moduleExports.__esModule ? moduleExports.default : moduleExports;
2445
3510
  }
2446
3511
 
2447
- return moduleExports[metadata.name];
3512
+ return moduleExports[metadata[NAME]];
3513
+ }
3514
+
3515
+ var chunkMap = new Map();
3516
+ /**
3517
+ * We patch the chunk filename function in webpack to insert our own resolution
3518
+ * of chunks that come from Flight and may not be known to the webpack runtime
3519
+ */
3520
+
3521
+ var webpackGetChunkFilename = __webpack_require__.u;
3522
+
3523
+ __webpack_require__.u = function (chunkId) {
3524
+ var flightChunk = chunkMap.get(chunkId);
3525
+
3526
+ if (flightChunk !== undefined) {
3527
+ return flightChunk;
3528
+ }
3529
+
3530
+ return webpackGetChunkFilename(chunkId);
3531
+ };
3532
+
3533
+ function loadChunk(chunkId, filename) {
3534
+ chunkMap.set(chunkId, filename);
3535
+ return __webpack_chunk_load__(chunkId);
2448
3536
  }
2449
3537
 
2450
3538
  // The server acts as a Client of itself when resolving Server References.
@@ -2544,11 +3632,11 @@ function createResolvedModelChunk(response, value) {
2544
3632
  return new Chunk(RESOLVED_MODEL, value, null, response);
2545
3633
  }
2546
3634
 
2547
- function bindArgs(fn, args) {
3635
+ function bindArgs$1(fn, args) {
2548
3636
  return fn.bind.apply(fn, [null].concat(args));
2549
3637
  }
2550
3638
 
2551
- function loadServerReference(response, id, bound, parentChunk, parentObject, key) {
3639
+ function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) {
2552
3640
  var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
2553
3641
  // the relevant modules already loaded but it allows for lazy loading of code
2554
3642
  // if needed.
@@ -2559,7 +3647,7 @@ function loadServerReference(response, id, bound, parentChunk, parentObject, key
2559
3647
  if (bound) {
2560
3648
  promise = Promise.all([bound, preloadPromise]).then(function (_ref) {
2561
3649
  var args = _ref[0];
2562
- return bindArgs(requireModule(serverReference), args);
3650
+ return bindArgs$1(requireModule(serverReference), args);
2563
3651
  });
2564
3652
  } else {
2565
3653
  if (preloadPromise) {
@@ -2689,7 +3777,22 @@ function createModelReject(chunk) {
2689
3777
  };
2690
3778
  }
2691
3779
 
2692
- function parseModelString(response, parentObject, key, value) {
3780
+ function getOutlinedModel(response, id) {
3781
+ var chunk = getChunk(response, id);
3782
+
3783
+ if (chunk.status === RESOLVED_MODEL) {
3784
+ initializeModelChunk(chunk);
3785
+ }
3786
+
3787
+ if (chunk.status !== INITIALIZED) {
3788
+ // We know that this is emitted earlier so otherwise it's an error.
3789
+ throw chunk.reason;
3790
+ }
3791
+
3792
+ return chunk.value;
3793
+ }
3794
+
3795
+ function parseModelString(response, obj, key, value) {
2693
3796
  if (value[0] === '$') {
2694
3797
  switch (value[1]) {
2695
3798
  case '$':
@@ -2701,36 +3804,46 @@ function parseModelString(response, parentObject, key, value) {
2701
3804
  case '@':
2702
3805
  {
2703
3806
  // Promise
2704
- var id = parseInt(value.slice(2), 16);
2705
- var chunk = getChunk(response, id);
2706
- return chunk;
2707
- }
3807
+ var _id = parseInt(value.slice(2), 16);
2708
3808
 
2709
- case 'S':
2710
- {
2711
- // Symbol
2712
- return Symbol.for(value.slice(2));
3809
+ var _chunk = getChunk(response, _id);
3810
+
3811
+ return _chunk;
2713
3812
  }
2714
3813
 
2715
3814
  case 'F':
2716
3815
  {
2717
3816
  // Server Reference
2718
- var _id = parseInt(value.slice(2), 16);
3817
+ var _id2 = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model.
2719
3818
 
2720
- var _chunk = getChunk(response, _id);
2721
3819
 
2722
- if (_chunk.status === RESOLVED_MODEL) {
2723
- initializeModelChunk(_chunk);
2724
- }
3820
+ var metaData = getOutlinedModel(response, _id2);
3821
+ return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, obj, key);
3822
+ }
3823
+
3824
+ case 'T':
3825
+ {
3826
+ // Temporary Reference
3827
+ return createTemporaryReference(value.slice(2));
3828
+ }
3829
+
3830
+ case 'Q':
3831
+ {
3832
+ // Map
3833
+ var _id3 = parseInt(value.slice(2), 16);
2725
3834
 
2726
- if (_chunk.status !== INITIALIZED) {
2727
- // We know that this is emitted earlier so otherwise it's an error.
2728
- throw _chunk.reason;
2729
- } // TODO: Just encode this in the reference inline instead of as a model.
3835
+ var data = getOutlinedModel(response, _id3);
3836
+ return new Map(data);
3837
+ }
3838
+
3839
+ case 'W':
3840
+ {
3841
+ // Set
3842
+ var _id4 = parseInt(value.slice(2), 16);
2730
3843
 
3844
+ var _data = getOutlinedModel(response, _id4);
2731
3845
 
2732
- var metaData = _chunk.value;
2733
- return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key);
3846
+ return new Set(_data);
2734
3847
  }
2735
3848
 
2736
3849
  case 'K':
@@ -2738,7 +3851,9 @@ function parseModelString(response, parentObject, key, value) {
2738
3851
  // FormData
2739
3852
  var stringId = value.slice(2);
2740
3853
  var formPrefix = response._prefix + stringId + '_';
2741
- var data = new FormData();
3854
+
3855
+ var _data2 = new FormData();
3856
+
2742
3857
  var backingFormData = response._formData; // We assume that the reference to FormData always comes after each
2743
3858
  // entry that it references so we can assume they all exist in the
2744
3859
  // backing store already.
@@ -2746,10 +3861,20 @@ function parseModelString(response, parentObject, key, value) {
2746
3861
 
2747
3862
  backingFormData.forEach(function (entry, entryKey) {
2748
3863
  if (entryKey.startsWith(formPrefix)) {
2749
- data.append(entryKey.slice(formPrefix.length), entry);
3864
+ _data2.append(entryKey.slice(formPrefix.length), entry);
2750
3865
  }
2751
3866
  });
2752
- return data;
3867
+ return _data2;
3868
+ }
3869
+
3870
+ case 'i':
3871
+ {
3872
+ // Iterator
3873
+ var _id5 = parseInt(value.slice(2), 16);
3874
+
3875
+ var _data3 = getOutlinedModel(response, _id5);
3876
+
3877
+ return _data3[Symbol.iterator]();
2753
3878
  }
2754
3879
 
2755
3880
  case 'I':
@@ -2792,37 +3917,31 @@ function parseModelString(response, parentObject, key, value) {
2792
3917
  // BigInt
2793
3918
  return BigInt(value.slice(2));
2794
3919
  }
3920
+ }
2795
3921
 
2796
- default:
2797
- {
2798
- // We assume that anything else is a reference ID.
2799
- var _id2 = parseInt(value.slice(1), 16);
2800
-
2801
- var _chunk2 = getChunk(response, _id2);
2802
-
2803
- switch (_chunk2.status) {
2804
- case RESOLVED_MODEL:
2805
- initializeModelChunk(_chunk2);
2806
- break;
2807
- } // The status might have changed after initialization.
2808
3922
 
3923
+ var id = parseInt(value.slice(1), 16);
3924
+ var chunk = getChunk(response, id);
2809
3925
 
2810
- switch (_chunk2.status) {
2811
- case INITIALIZED:
2812
- return _chunk2.value;
3926
+ switch (chunk.status) {
3927
+ case RESOLVED_MODEL:
3928
+ initializeModelChunk(chunk);
3929
+ break;
3930
+ } // The status might have changed after initialization.
2813
3931
 
2814
- case PENDING:
2815
- case BLOCKED:
2816
- var parentChunk = initializingChunk;
2817
3932
 
2818
- _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk));
3933
+ switch (chunk.status) {
3934
+ case INITIALIZED:
3935
+ return chunk.value;
2819
3936
 
2820
- return null;
3937
+ case PENDING:
3938
+ case BLOCKED:
3939
+ var parentChunk = initializingChunk;
3940
+ chunk.then(createModelResolver(parentChunk, obj, key), createModelReject(parentChunk));
3941
+ return null;
2821
3942
 
2822
- default:
2823
- throw _chunk2.reason;
2824
- }
2825
- }
3943
+ default:
3944
+ throw chunk.reason;
2826
3945
  }
2827
3946
  }
2828
3947
 
@@ -2856,8 +3975,130 @@ function close(response) {
2856
3975
  reportGlobalError(response, new Error('Connection closed.'));
2857
3976
  }
2858
3977
 
3978
+ function bindArgs(fn, args) {
3979
+ return fn.bind.apply(fn, [null].concat(args));
3980
+ }
3981
+
3982
+ function loadServerReference(bundlerConfig, id, bound) {
3983
+ var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
3984
+ // the relevant modules already loaded but it allows for lazy loading of code
3985
+ // if needed.
3986
+
3987
+ var preloadPromise = preloadModule(serverReference);
3988
+
3989
+ if (bound) {
3990
+ return Promise.all([bound, preloadPromise]).then(function (_ref) {
3991
+ var args = _ref[0];
3992
+ return bindArgs(requireModule(serverReference), args);
3993
+ });
3994
+ } else if (preloadPromise) {
3995
+ return Promise.resolve(preloadPromise).then(function () {
3996
+ return requireModule(serverReference);
3997
+ });
3998
+ } else {
3999
+ // Synchronously available
4000
+ return Promise.resolve(requireModule(serverReference));
4001
+ }
4002
+ }
4003
+
4004
+ function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) {
4005
+ // The data for this reference is encoded in multiple fields under this prefix.
4006
+ var actionResponse = createResponse(serverManifest, formFieldPrefix, body);
4007
+ close(actionResponse);
4008
+ var refPromise = getRoot(actionResponse); // Force it to initialize
4009
+ // $FlowFixMe
4010
+
4011
+ refPromise.then(function () {});
4012
+
4013
+ if (refPromise.status !== 'fulfilled') {
4014
+ // $FlowFixMe
4015
+ throw refPromise.reason;
4016
+ }
4017
+
4018
+ return refPromise.value;
4019
+ }
4020
+
4021
+ function decodeAction(body, serverManifest) {
4022
+ // We're going to create a new formData object that holds all the fields except
4023
+ // the implementation details of the action data.
4024
+ var formData = new FormData();
4025
+ var action = null; // $FlowFixMe[prop-missing]
4026
+
4027
+ body.forEach(function (value, key) {
4028
+ if (!key.startsWith('$ACTION_')) {
4029
+ formData.append(key, value);
4030
+ return;
4031
+ } // Later actions may override earlier actions if a button is used to override the default
4032
+ // form action.
4033
+
4034
+
4035
+ if (key.startsWith('$ACTION_REF_')) {
4036
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
4037
+ var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
4038
+ action = loadServerReference(serverManifest, metaData.id, metaData.bound);
4039
+ return;
4040
+ }
4041
+
4042
+ if (key.startsWith('$ACTION_ID_')) {
4043
+ var id = key.slice(11);
4044
+ action = loadServerReference(serverManifest, id, null);
4045
+ return;
4046
+ }
4047
+ });
4048
+
4049
+ if (action === null) {
4050
+ return null;
4051
+ } // Return the action with the remaining FormData bound to the first argument.
4052
+
4053
+
4054
+ return action.then(function (fn) {
4055
+ return fn.bind(null, formData);
4056
+ });
4057
+ }
4058
+ function decodeFormState(actionResult, body, serverManifest) {
4059
+ var keyPath = body.get('$ACTION_KEY');
4060
+
4061
+ if (typeof keyPath !== 'string') {
4062
+ // This form submission did not include any form state.
4063
+ return Promise.resolve(null);
4064
+ } // Search through the form data object to get the reference id and the number
4065
+ // of bound arguments. This repeats some of the work done in decodeAction.
4066
+
4067
+
4068
+ var metaData = null; // $FlowFixMe[prop-missing]
4069
+
4070
+ body.forEach(function (value, key) {
4071
+ if (key.startsWith('$ACTION_REF_')) {
4072
+ var formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
4073
+ metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
4074
+ } // We don't check for the simple $ACTION_ID_ case because form state actions
4075
+ // are always bound to the state argument.
4076
+
4077
+ });
4078
+
4079
+ if (metaData === null) {
4080
+ // Should be unreachable.
4081
+ return Promise.resolve(null);
4082
+ }
4083
+
4084
+ var referenceId = metaData.id;
4085
+ return Promise.resolve(metaData.bound).then(function (bound) {
4086
+ if (bound === null) {
4087
+ // Should be unreachable because form state actions are always bound to the
4088
+ // state argument.
4089
+ return null;
4090
+ } // The form action dispatch method is always bound to the initial state.
4091
+ // But when comparing signatures, we compare to the original unbound action.
4092
+ // Subtract one from the arity to account for this.
4093
+
4094
+
4095
+ var boundArity = bound.length - 1;
4096
+ return [actionResult, keyPath, referenceId, boundArity];
4097
+ });
4098
+ }
4099
+
2859
4100
  function renderToReadableStream(model, webpackMap, options) {
2860
- var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined);
4101
+ var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, options ? options.environmentName : undefined);
2861
4102
 
2862
4103
  if (options && options.signal) {
2863
4104
  var signal = options.signal;
@@ -2882,7 +4123,10 @@ function renderToReadableStream(model, webpackMap, options) {
2882
4123
  pull: function (controller) {
2883
4124
  startFlowing(request, controller);
2884
4125
  },
2885
- cancel: function (reason) {}
4126
+ cancel: function (reason) {
4127
+ stopFlowing(request);
4128
+ abort(request, reason);
4129
+ }
2886
4130
  }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams.
2887
4131
  {
2888
4132
  highWaterMark: 0
@@ -2898,11 +4142,17 @@ function decodeReply(body, webpackMap) {
2898
4142
  }
2899
4143
 
2900
4144
  var response = createResponse(webpackMap, '', body);
4145
+ var root = getRoot(response);
2901
4146
  close(response);
2902
- return getRoot(response);
4147
+ return root;
2903
4148
  }
2904
4149
 
4150
+ exports.createClientModuleProxy = createClientModuleProxy;
4151
+ exports.decodeAction = decodeAction;
4152
+ exports.decodeFormState = decodeFormState;
2905
4153
  exports.decodeReply = decodeReply;
4154
+ exports.registerClientReference = registerClientReference;
4155
+ exports.registerServerReference = registerServerReference;
2906
4156
  exports.renderToReadableStream = renderToReadableStream;
2907
4157
  })();
2908
4158
  }