relay-runtime 8.0.0 → 10.0.1

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 (135) hide show
  1. package/handlers/RelayDefaultHandlerProvider.js.flow +41 -0
  2. package/handlers/connection/ConnectionHandler.js.flow +549 -0
  3. package/handlers/connection/ConnectionInterface.js.flow +92 -0
  4. package/handlers/connection/MutationHandlers.js.flow +88 -0
  5. package/index.js +1 -1
  6. package/index.js.flow +320 -0
  7. package/lib/handlers/RelayDefaultHandlerProvider.js +13 -2
  8. package/lib/handlers/connection/{RelayConnectionHandler.js → ConnectionHandler.js} +33 -35
  9. package/lib/handlers/connection/{RelayConnectionInterface.js → ConnectionInterface.js} +2 -2
  10. package/lib/handlers/connection/MutationHandlers.js +86 -0
  11. package/lib/index.js +15 -19
  12. package/lib/mutations/RelayDeclarativeMutationConfig.js +29 -52
  13. package/lib/mutations/RelayRecordProxy.js +1 -3
  14. package/lib/mutations/RelayRecordSourceMutator.js +2 -9
  15. package/lib/mutations/RelayRecordSourceProxy.js +2 -4
  16. package/lib/mutations/RelayRecordSourceSelectorProxy.js +1 -13
  17. package/lib/mutations/commitMutation.js +13 -3
  18. package/lib/mutations/validateMutation.js +16 -9
  19. package/lib/network/RelayObservable.js +9 -9
  20. package/lib/network/RelayQueryResponseCache.js +8 -6
  21. package/lib/query/PreloadableQueryRegistry.js +70 -0
  22. package/lib/query/fetchQueryInternal.js +31 -23
  23. package/lib/store/DataChecker.js +122 -110
  24. package/lib/store/RelayConcreteVariables.js +6 -2
  25. package/lib/store/RelayModernEnvironment.js +121 -67
  26. package/lib/store/RelayModernFragmentSpecResolver.js +12 -16
  27. package/lib/store/RelayModernQueryExecutor.js +389 -314
  28. package/lib/store/RelayModernRecord.js +14 -9
  29. package/lib/store/RelayModernSelector.js +7 -3
  30. package/lib/store/RelayModernStore.js +289 -484
  31. package/lib/store/RelayOperationTracker.js +35 -78
  32. package/lib/store/RelayOptimisticRecordSource.js +7 -5
  33. package/lib/store/RelayPublishQueue.js +6 -33
  34. package/lib/store/RelayReader.js +113 -45
  35. package/lib/store/RelayRecordSource.js +2 -9
  36. package/lib/store/RelayRecordSourceMapImpl.js +13 -18
  37. package/lib/store/RelayReferenceMarker.js +40 -60
  38. package/lib/store/RelayResponseNormalizer.js +158 -193
  39. package/lib/store/RelayStoreUtils.js +1 -0
  40. package/lib/store/StoreInspector.js +8 -8
  41. package/lib/store/TypeID.js +28 -0
  42. package/lib/store/cloneRelayScalarHandleSourceField.js +44 -0
  43. package/lib/store/normalizeRelayPayload.js +6 -2
  44. package/lib/store/readInlineData.js +1 -1
  45. package/lib/subscription/requestSubscription.js +5 -3
  46. package/lib/util/RelayConcreteNode.js +9 -6
  47. package/lib/util/RelayError.js +39 -9
  48. package/lib/util/RelayFeatureFlags.js +2 -5
  49. package/lib/util/RelayReplaySubject.js +3 -3
  50. package/lib/util/createPayloadFor3DField.js +7 -2
  51. package/lib/util/getRequestIdentifier.js +2 -2
  52. package/lib/util/recycleNodesInto.js +2 -6
  53. package/mutations/RelayDeclarativeMutationConfig.js.flow +380 -0
  54. package/mutations/RelayRecordProxy.js.flow +165 -0
  55. package/mutations/RelayRecordSourceMutator.js.flow +238 -0
  56. package/mutations/RelayRecordSourceProxy.js.flow +164 -0
  57. package/mutations/RelayRecordSourceSelectorProxy.js.flow +119 -0
  58. package/mutations/applyOptimisticMutation.js.flow +76 -0
  59. package/mutations/commitLocalUpdate.js.flow +24 -0
  60. package/mutations/commitMutation.js.flow +182 -0
  61. package/mutations/validateMutation.js.flow +213 -0
  62. package/network/ConvertToExecuteFunction.js.flow +49 -0
  63. package/network/RelayNetwork.js.flow +84 -0
  64. package/network/RelayNetworkTypes.js.flow +123 -0
  65. package/network/RelayObservable.js.flow +634 -0
  66. package/network/RelayQueryResponseCache.js.flow +111 -0
  67. package/package.json +1 -1
  68. package/query/GraphQLTag.js.flow +166 -0
  69. package/query/PreloadableQueryRegistry.js.flow +65 -0
  70. package/query/fetchQuery.js.flow +47 -0
  71. package/query/fetchQueryInternal.js.flow +348 -0
  72. package/relay-runtime.js +2 -2
  73. package/relay-runtime.min.js +2 -2
  74. package/store/ClientID.js.flow +43 -0
  75. package/store/DataChecker.js.flow +502 -0
  76. package/store/RelayConcreteVariables.js.flow +96 -0
  77. package/store/RelayModernEnvironment.js.flow +551 -0
  78. package/store/RelayModernFragmentSpecResolver.js.flow +426 -0
  79. package/store/RelayModernOperationDescriptor.js.flow +88 -0
  80. package/store/RelayModernQueryExecutor.js.flow +1321 -0
  81. package/store/RelayModernRecord.js.flow +403 -0
  82. package/store/RelayModernSelector.js.flow +455 -0
  83. package/store/RelayModernStore.js.flow +842 -0
  84. package/store/RelayOperationTracker.js.flow +164 -0
  85. package/store/RelayOptimisticRecordSource.js.flow +119 -0
  86. package/store/RelayPublishQueue.js.flow +401 -0
  87. package/store/RelayReader.js.flow +473 -0
  88. package/store/RelayRecordSource.js.flow +29 -0
  89. package/store/RelayRecordSourceMapImpl.js.flow +87 -0
  90. package/store/RelayRecordState.js.flow +37 -0
  91. package/store/RelayReferenceMarker.js.flow +257 -0
  92. package/store/RelayResponseNormalizer.js.flow +680 -0
  93. package/store/RelayStoreTypes.js.flow +899 -0
  94. package/store/RelayStoreUtils.js.flow +219 -0
  95. package/store/StoreInspector.js.flow +171 -0
  96. package/store/TypeID.js.flow +28 -0
  97. package/store/ViewerPattern.js.flow +26 -0
  98. package/store/cloneRelayHandleSourceField.js.flow +66 -0
  99. package/store/cloneRelayScalarHandleSourceField.js.flow +62 -0
  100. package/store/createFragmentSpecResolver.js.flow +55 -0
  101. package/store/createRelayContext.js.flow +44 -0
  102. package/store/defaultGetDataID.js.flow +27 -0
  103. package/store/hasOverlappingIDs.js.flow +34 -0
  104. package/store/isRelayModernEnvironment.js.flow +27 -0
  105. package/store/normalizeRelayPayload.js.flow +51 -0
  106. package/store/readInlineData.js.flow +75 -0
  107. package/subscription/requestSubscription.js.flow +100 -0
  108. package/util/JSResourceTypes.flow.js.flow +20 -0
  109. package/util/NormalizationNode.js.flow +198 -0
  110. package/util/ReaderNode.js.flow +208 -0
  111. package/util/RelayConcreteNode.js.flow +93 -0
  112. package/util/RelayDefaultHandleKey.js.flow +17 -0
  113. package/util/RelayError.js.flow +62 -0
  114. package/util/RelayFeatureFlags.js.flow +30 -0
  115. package/util/RelayProfiler.js.flow +284 -0
  116. package/util/RelayReplaySubject.js.flow +135 -0
  117. package/util/RelayRuntimeTypes.js.flow +72 -0
  118. package/util/createPayloadFor3DField.js.flow +43 -0
  119. package/util/deepFreeze.js.flow +36 -0
  120. package/util/generateID.js.flow +21 -0
  121. package/util/getFragmentIdentifier.js.flow +52 -0
  122. package/util/getRelayHandleKey.js.flow +41 -0
  123. package/util/getRequestIdentifier.js.flow +42 -0
  124. package/util/isPromise.js.flow +21 -0
  125. package/util/isScalarAndEqual.js.flow +26 -0
  126. package/util/recycleNodesInto.js.flow +76 -0
  127. package/util/resolveImmediate.js.flow +30 -0
  128. package/util/stableCopy.js.flow +35 -0
  129. package/lib/handlers/RelayDefaultMissingFieldHandlers.js +0 -26
  130. package/lib/handlers/getRelayDefaultMissingFieldHandlers.js +0 -36
  131. package/lib/query/RelayModernGraphQLTag.js +0 -104
  132. package/lib/store/RelayConnection.js +0 -37
  133. package/lib/store/RelayConnectionResolver.js +0 -178
  134. package/lib/store/RelayRecordSourceObjectImpl.js +0 -79
  135. package/lib/util/getFragmentSpecIdentifier.js +0 -27
@@ -0,0 +1,899 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ // flowlint ambiguous-object-type:error
12
+
13
+ 'use strict';
14
+
15
+ import type {
16
+ GraphQLResponse,
17
+ INetwork,
18
+ PayloadData,
19
+ PayloadError,
20
+ UploadableMap,
21
+ } from '../network/RelayNetworkTypes';
22
+ import type RelayObservable from '../network/RelayObservable';
23
+ import type {
24
+ NormalizationLinkedField,
25
+ NormalizationScalarField,
26
+ NormalizationSelectableNode,
27
+ NormalizationSplitOperation,
28
+ } from '../util/NormalizationNode';
29
+ import type {ReaderFragment} from '../util/ReaderNode';
30
+ import type {
31
+ ConcreteRequest,
32
+ RequestParameters,
33
+ } from '../util/RelayConcreteNode';
34
+ import type {
35
+ CacheConfig,
36
+ DataID,
37
+ Disposable,
38
+ RenderPolicy,
39
+ Variables,
40
+ } from '../util/RelayRuntimeTypes';
41
+ import type {RequestIdentifier} from '../util/getRequestIdentifier';
42
+ import type {InvalidationState} from './RelayModernStore';
43
+ import type RelayOperationTracker from './RelayOperationTracker';
44
+ import type {RecordState} from './RelayRecordState';
45
+
46
+ export opaque type FragmentReference = empty;
47
+ export type OperationTracker = RelayOperationTracker;
48
+
49
+ /*
50
+ * An individual cached graph object.
51
+ */
52
+ export type Record = {[key: string]: mixed, ...};
53
+
54
+ /**
55
+ * A collection of records keyed by id.
56
+ */
57
+ export type RecordMap = {[dataID: DataID]: ?Record, ...};
58
+
59
+ export type FragmentMap = {[key: string]: ReaderFragment, ...};
60
+
61
+ /**
62
+ * The results of a selector given a store/RecordSource.
63
+ */
64
+ export type SelectorData = {[key: string]: mixed, ...};
65
+
66
+ export type SingularReaderSelector = {|
67
+ +kind: 'SingularReaderSelector',
68
+ +dataID: DataID,
69
+ +isWithinUnmatchedTypeRefinement: boolean,
70
+ +node: ReaderFragment,
71
+ +owner: RequestDescriptor,
72
+ +variables: Variables,
73
+ |};
74
+
75
+ export type ReaderSelector = SingularReaderSelector | PluralReaderSelector;
76
+
77
+ export type PluralReaderSelector = {|
78
+ +kind: 'PluralReaderSelector',
79
+ +selectors: $ReadOnlyArray<SingularReaderSelector>,
80
+ |};
81
+
82
+ export type RequestDescriptor = {|
83
+ +identifier: RequestIdentifier,
84
+ +node: ConcreteRequest,
85
+ +variables: Variables,
86
+ |};
87
+
88
+ /**
89
+ * A selector defines the starting point for a traversal into the graph for the
90
+ * purposes of targeting a subgraph.
91
+ */
92
+ export type NormalizationSelector = {|
93
+ +dataID: DataID,
94
+ +node: NormalizationSelectableNode,
95
+ +variables: Variables,
96
+ |};
97
+
98
+ /**
99
+ * A representation of a selector and its results at a particular point in time.
100
+ */
101
+ export type TypedSnapshot<TData> = {|
102
+ +data: TData,
103
+ +isMissingData: boolean,
104
+ +seenRecords: RecordMap,
105
+ +selector: SingularReaderSelector,
106
+ |};
107
+ export type Snapshot = TypedSnapshot<?SelectorData>;
108
+
109
+ /**
110
+ * An operation selector describes a specific instance of a GraphQL operation
111
+ * with variables applied.
112
+ *
113
+ * - `root`: a selector intended for processing server results or retaining
114
+ * response data in the store.
115
+ * - `fragment`: a selector intended for use in reading or subscribing to
116
+ * the results of the the operation.
117
+ */
118
+ export type OperationDescriptor = {|
119
+ +fragment: SingularReaderSelector,
120
+ +request: RequestDescriptor,
121
+ +root: NormalizationSelector,
122
+ |};
123
+
124
+ /**
125
+ * Arbitrary data e.g. received by a container as props.
126
+ */
127
+ export type Props = {[key: string]: mixed, ...};
128
+
129
+ /**
130
+ * The type of the `relay` property set on React context by the React/Relay
131
+ * integration layer (e.g. QueryRenderer, FragmentContainer, etc).
132
+ */
133
+ export type RelayContext = {|
134
+ environment: IEnvironment,
135
+ |};
136
+
137
+ /**
138
+ * The results of reading the results of a FragmentMap given some input
139
+ * `Props`.
140
+ */
141
+ export type FragmentSpecResults = {[key: string]: mixed, ...};
142
+
143
+ /**
144
+ * A utility for resolving and subscribing to the results of a fragment spec
145
+ * (key -> fragment mapping) given some "props" that determine the root ID
146
+ * and variables to use when reading each fragment. When props are changed via
147
+ * `setProps()`, the resolver will update its results and subscriptions
148
+ * accordingly. Internally, the resolver:
149
+ * - Converts the fragment map & props map into a map of `Selector`s.
150
+ * - Removes any resolvers for any props that became null.
151
+ * - Creates resolvers for any props that became non-null.
152
+ * - Updates resolvers with the latest props.
153
+ */
154
+ export interface FragmentSpecResolver {
155
+ /**
156
+ * Stop watching for changes to the results of the fragments.
157
+ */
158
+ dispose(): void;
159
+
160
+ /**
161
+ * Get the current results.
162
+ */
163
+ resolve(): FragmentSpecResults;
164
+
165
+ /**
166
+ * Update the resolver with new inputs. Call `resolve()` to get the updated
167
+ * results.
168
+ */
169
+ setProps(props: Props): void;
170
+
171
+ /**
172
+ * Override the variables used to read the results of the fragments. Call
173
+ * `resolve()` to get the updated results.
174
+ */
175
+ setVariables(variables: Variables, node: ConcreteRequest): void;
176
+
177
+ /**
178
+ * Subscribe to resolver updates.
179
+ * Overrides existing callback (if one has been specified).
180
+ */
181
+ setCallback(callback: () => void): void;
182
+ }
183
+
184
+ /**
185
+ * A read-only interface for accessing cached graph data.
186
+ */
187
+ export interface RecordSource {
188
+ get(dataID: DataID): ?Record;
189
+ getRecordIDs(): Array<DataID>;
190
+ getStatus(dataID: DataID): RecordState;
191
+ has(dataID: DataID): boolean;
192
+ size(): number;
193
+ toJSON(): {[DataID]: ?Record, ...};
194
+ }
195
+
196
+ /**
197
+ * A read/write interface for accessing and updating graph data.
198
+ */
199
+ export interface MutableRecordSource extends RecordSource {
200
+ clear(): void;
201
+ delete(dataID: DataID): void;
202
+ remove(dataID: DataID): void;
203
+ set(dataID: DataID, record: Record): void;
204
+ }
205
+
206
+ export type CheckOptions = {|
207
+ target: MutableRecordSource,
208
+ handlers: $ReadOnlyArray<MissingFieldHandler>,
209
+ |};
210
+
211
+ export type OperationAvailability =
212
+ | {|status: 'available', fetchTime: ?number|}
213
+ | {|status: 'stale'|}
214
+ | {|status: 'missing'|};
215
+
216
+ export type {InvalidationState} from './RelayModernStore';
217
+
218
+ /**
219
+ * An interface for keeping multiple views of data consistent across an
220
+ * application.
221
+ */
222
+ export interface Store {
223
+ /**
224
+ * Get a read-only view of the store's internal RecordSource.
225
+ */
226
+ getSource(): RecordSource;
227
+
228
+ /**
229
+ * Determine if the operation can be resolved with data in the store (i.e. no
230
+ * fields are missing).
231
+ */
232
+ check(
233
+ operation: OperationDescriptor,
234
+ options?: CheckOptions,
235
+ ): OperationAvailability;
236
+
237
+ /**
238
+ * Read the results of a selector from in-memory records in the store.
239
+ * Optionally takes an owner, corresponding to the operation that
240
+ * owns this selector (fragment).
241
+ */
242
+ lookup(selector: SingularReaderSelector): Snapshot;
243
+
244
+ /**
245
+ * Notify subscribers (see `subscribe`) of any data that was published
246
+ * (`publish()`) since the last time `notify` was called.
247
+ * Optionally provide an OperationDescriptor indicating the source operation
248
+ * that was being processed to produce this run.
249
+ *
250
+ * This method should return an array of the affected fragment owners
251
+ */
252
+ notify(
253
+ sourceOperation?: OperationDescriptor,
254
+ invalidateStore?: boolean,
255
+ ): $ReadOnlyArray<RequestDescriptor>;
256
+
257
+ /**
258
+ * Publish new information (e.g. from the network) to the store, updating its
259
+ * internal record source. Subscribers are not immediately notified - this
260
+ * occurs when `notify()` is called.
261
+ */
262
+ publish(source: RecordSource, idsMarkedForInvalidation?: Set<DataID>): void;
263
+
264
+ /**
265
+ * Ensure that all the records necessary to fulfill the given selector are
266
+ * retained in-memory. The records will not be eligible for garbage collection
267
+ * until the returned reference is disposed.
268
+ */
269
+ retain(operation: OperationDescriptor): Disposable;
270
+
271
+ /**
272
+ * Subscribe to changes to the results of a selector. The callback is called
273
+ * when `notify()` is called *and* records have been published that affect the
274
+ * selector results relative to the last `notify()`.
275
+ */
276
+ subscribe(
277
+ snapshot: Snapshot,
278
+ callback: (snapshot: Snapshot) => void,
279
+ ): Disposable;
280
+
281
+ /**
282
+ * The method should disable garbage collection until
283
+ * the returned reference is disposed.
284
+ */
285
+ holdGC(): Disposable;
286
+
287
+ /**
288
+ * Record a backup/snapshot of the current state of the store, including
289
+ * records and derived data such as fragment subscriptions.
290
+ * This state can be restored with restore().
291
+ */
292
+ snapshot(): void;
293
+
294
+ /**
295
+ * Reset the state of the store to the point that snapshot() was last called.
296
+ */
297
+ restore(): void;
298
+
299
+ /**
300
+ * Will return an opaque snapshot of the current invalidation state of
301
+ * the data ids that were provided.
302
+ */
303
+ lookupInvalidationState(dataIDs: $ReadOnlyArray<DataID>): InvalidationState;
304
+
305
+ /**
306
+ * Given the previous invalidation state for those
307
+ * ids, this function will return:
308
+ * - false, if the invalidation state for those ids is the same, meaning
309
+ * **it has not changed**
310
+ * - true, if the invalidation state for the given ids has changed
311
+ */
312
+ checkInvalidationState(previousInvalidationState: InvalidationState): boolean;
313
+
314
+ /**
315
+ * Will subscribe the provided callback to the invalidation state of the
316
+ * given data ids. Whenever the invalidation state for any of the provided
317
+ * ids changes, the callback will be called, and provide the latest
318
+ * invalidation state.
319
+ * Disposing of the returned disposable will remove the subscription.
320
+ */
321
+ subscribeToInvalidationState(
322
+ invalidationState: InvalidationState,
323
+ callback: () => void,
324
+ ): Disposable;
325
+ }
326
+
327
+ /**
328
+ * A type that accepts a callback and schedules it to run at some future time.
329
+ * By convention, implementations should not execute the callback immediately.
330
+ */
331
+ export type Scheduler = (() => void) => void;
332
+
333
+ /**
334
+ * An interface for imperatively getting/setting properties of a `Record`. This interface
335
+ * is designed to allow the appearance of direct Record manipulation while
336
+ * allowing different implementations that may e.g. create a changeset of
337
+ * the modifications.
338
+ */
339
+ export interface RecordProxy {
340
+ copyFieldsFrom(source: RecordProxy): void;
341
+ getDataID(): DataID;
342
+ getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
343
+ getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
344
+ getOrCreateLinkedRecord(
345
+ name: string,
346
+ typeName: string,
347
+ args?: ?Variables,
348
+ ): RecordProxy;
349
+ getType(): string;
350
+ getValue(name: string, args?: ?Variables): mixed;
351
+ setLinkedRecord(
352
+ record: RecordProxy,
353
+ name: string,
354
+ args?: ?Variables,
355
+ ): RecordProxy;
356
+ setLinkedRecords(
357
+ records: Array<?RecordProxy>,
358
+ name: string,
359
+ args?: ?Variables,
360
+ ): RecordProxy;
361
+ setValue(value: mixed, name: string, args?: ?Variables): RecordProxy;
362
+ invalidateRecord(): void;
363
+ }
364
+
365
+ export interface ReadOnlyRecordProxy {
366
+ getDataID(): DataID;
367
+ getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
368
+ getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
369
+ getType(): string;
370
+ getValue(name: string, args?: ?Variables): mixed;
371
+ }
372
+
373
+ /**
374
+ * An interface for imperatively getting/setting properties of a `RecordSource`. This interface
375
+ * is designed to allow the appearance of direct RecordSource manipulation while
376
+ * allowing different implementations that may e.g. create a changeset of
377
+ * the modifications.
378
+ */
379
+ export interface RecordSourceProxy {
380
+ create(dataID: DataID, typeName: string): RecordProxy;
381
+ delete(dataID: DataID): void;
382
+ get(dataID: DataID): ?RecordProxy;
383
+ getRoot(): RecordProxy;
384
+ invalidateStore(): void;
385
+ }
386
+
387
+ export interface ReadOnlyRecordSourceProxy {
388
+ get(dataID: DataID): ?ReadOnlyRecordProxy;
389
+ getRoot(): ReadOnlyRecordProxy;
390
+ }
391
+
392
+ /**
393
+ * Extends the RecordSourceProxy interface with methods for accessing the root
394
+ * fields of a Selector.
395
+ */
396
+ export interface RecordSourceSelectorProxy extends RecordSourceProxy {
397
+ getRootField(fieldName: string): ?RecordProxy;
398
+ getPluralRootField(fieldName: string): ?Array<?RecordProxy>;
399
+ invalidateStore(): void;
400
+ }
401
+
402
+ export type LogEvent =
403
+ | {|
404
+ +name: 'queryresource.fetch',
405
+ // ID of this query resource request and will be the same
406
+ // if there is an associated queryresource.retain event.
407
+ +resourceID: number,
408
+ +operation: OperationDescriptor,
409
+ // value from ProfilerContext
410
+ +profilerContext: mixed,
411
+ // FetchPolicy from relay-experimental
412
+ +fetchPolicy: string,
413
+ // RenderPolicy from relay-experimental
414
+ +renderPolicy: string,
415
+ +queryAvailability: OperationAvailability,
416
+ +shouldFetch: boolean,
417
+ |}
418
+ | {|
419
+ +name: 'queryresource.retain',
420
+ +resourceID: number,
421
+ // value from ProfilerContext
422
+ +profilerContext: mixed,
423
+ |}
424
+ | {|
425
+ +name: 'execute.info',
426
+ +transactionID: number,
427
+ +info: mixed,
428
+ |}
429
+ | {|
430
+ +name: 'execute.start',
431
+ +transactionID: number,
432
+ +params: RequestParameters,
433
+ +variables: Variables,
434
+ |}
435
+ | {|
436
+ +name: 'execute.next',
437
+ +transactionID: number,
438
+ +response: GraphQLResponse,
439
+ |}
440
+ | {|
441
+ +name: 'execute.error',
442
+ +transactionID: number,
443
+ +error: Error,
444
+ |}
445
+ | {|
446
+ +name: 'execute.complete',
447
+ +transactionID: number,
448
+ |}
449
+ | {|
450
+ +name: 'execute.unsubscribe',
451
+ +transactionID: number,
452
+ |}
453
+ | {|
454
+ +name: 'store.publish',
455
+ +source: RecordSource,
456
+ +optimistic: boolean,
457
+ |}
458
+ | {|
459
+ +name: 'store.snapshot',
460
+ |}
461
+ | {|
462
+ +name: 'store.restore',
463
+ |}
464
+ | {|
465
+ +name: 'store.gc',
466
+ +references: Set<DataID>,
467
+ |}
468
+ | {|
469
+ +name: 'store.notify.start',
470
+ |}
471
+ | {|
472
+ +name: 'store.notify.complete',
473
+ +updatedRecordIDs: UpdatedRecords,
474
+ +invalidatedRecordIDs: Set<DataID>,
475
+ |};
476
+ export type LogFunction = LogEvent => void;
477
+ export type LogRequestInfoFunction = mixed => void;
478
+
479
+ /**
480
+ * The public API of Relay core. Represents an encapsulated environment with its
481
+ * own in-memory cache.
482
+ */
483
+ export interface IEnvironment {
484
+ /**
485
+ * Extra information attached to the environment instance
486
+ */
487
+ +options: mixed;
488
+
489
+ /**
490
+ * **UNSTABLE** Event based logging API thats scoped to the environment.
491
+ */
492
+ __log: LogFunction;
493
+
494
+ /**
495
+ * Determine if the operation can be resolved with data in the store (i.e. no
496
+ * fields are missing).
497
+ *
498
+ * Note that this operation effectively "executes" the selector against the
499
+ * cache and therefore takes time proportional to the size/complexity of the
500
+ * selector.
501
+ */
502
+ check(operation: OperationDescriptor): OperationAvailability;
503
+
504
+ /**
505
+ * Subscribe to changes to the results of a selector. The callback is called
506
+ * when data has been committed to the store that would cause the results of
507
+ * the snapshot's selector to change.
508
+ */
509
+ subscribe(
510
+ snapshot: Snapshot,
511
+ callback: (snapshot: Snapshot) => void,
512
+ ): Disposable;
513
+
514
+ /**
515
+ * Ensure that all the records necessary to fulfill the given selector are
516
+ * retained in-memory. The records will not be eligible for garbage collection
517
+ * until the returned reference is disposed.
518
+ */
519
+ retain(operation: OperationDescriptor): Disposable;
520
+
521
+ /**
522
+ * Apply an optimistic update to the environment. The mutation can be reverted
523
+ * by calling `dispose()` on the returned value.
524
+ */
525
+ applyUpdate(optimisticUpdate: OptimisticUpdateFunction): Disposable;
526
+
527
+ /**
528
+ * Apply an optimistic mutation response and/or updater. The mutation can be
529
+ * reverted by calling `dispose()` on the returned value.
530
+ */
531
+ applyMutation(optimisticConfig: OptimisticResponseConfig): Disposable;
532
+
533
+ /**
534
+ * Commit an updater to the environment. This mutation cannot be reverted and
535
+ * should therefore not be used for optimistic updates. This is mainly
536
+ * intended for updating fields from client schema extensions.
537
+ */
538
+ commitUpdate(updater: StoreUpdater): void;
539
+
540
+ /**
541
+ * Commit a payload to the environment using the given operation selector.
542
+ */
543
+ commitPayload(
544
+ operationDescriptor: OperationDescriptor,
545
+ payload: PayloadData,
546
+ ): void;
547
+
548
+ /**
549
+ * Get the environment's internal Network.
550
+ */
551
+ getNetwork(): INetwork;
552
+
553
+ /**
554
+ * Get the environment's internal Store.
555
+ */
556
+ getStore(): Store;
557
+
558
+ /**
559
+ * Returns the environment specific OperationTracker.
560
+ */
561
+ getOperationTracker(): RelayOperationTracker;
562
+
563
+ /**
564
+ * EXPERIMENTAL
565
+ * Returns the default render policy to use when rendering a query
566
+ * that uses Relay Hooks
567
+ */
568
+ UNSTABLE_getDefaultRenderPolicy(): RenderPolicy;
569
+
570
+ /**
571
+ * Read the results of a selector from in-memory records in the store.
572
+ * Optionally takes an owner, corresponding to the operation that
573
+ * owns this selector (fragment).
574
+ */
575
+ lookup(selector: SingularReaderSelector): Snapshot;
576
+
577
+ /**
578
+ * Send a query to the server with Observer semantics: one or more
579
+ * responses may be returned (via `next`) over time followed by either
580
+ * the request completing (`completed`) or an error (`error`).
581
+ *
582
+ * Networks/servers that support subscriptions may choose to hold the
583
+ * subscription open indefinitely such that `complete` is not called.
584
+ *
585
+ * Note: Observables are lazy, so calling this method will do nothing until
586
+ * the result is subscribed to: environment.execute({...}).subscribe({...}).
587
+ */
588
+ execute(config: {|
589
+ operation: OperationDescriptor,
590
+ cacheConfig?: ?CacheConfig,
591
+ updater?: ?SelectorStoreUpdater,
592
+ |}): RelayObservable<GraphQLResponse>;
593
+
594
+ /**
595
+ * Returns an Observable of GraphQLResponse resulting from executing the
596
+ * provided Mutation operation, the result of which is then normalized and
597
+ * committed to the publish queue along with an optional optimistic response
598
+ * or updater.
599
+ *
600
+ * Note: Observables are lazy, so calling this method will do nothing until
601
+ * the result is subscribed to:
602
+ * environment.executeMutation({...}).subscribe({...}).
603
+ */
604
+ executeMutation({|
605
+ cacheConfig?: ?CacheConfig,
606
+ operation: OperationDescriptor,
607
+ optimisticUpdater?: ?SelectorStoreUpdater,
608
+ optimisticResponse?: ?Object,
609
+ updater?: ?SelectorStoreUpdater,
610
+ uploadables?: ?UploadableMap,
611
+ |}): RelayObservable<GraphQLResponse>;
612
+
613
+ /**
614
+ * Returns an Observable of GraphQLResponse resulting from executing the
615
+ * provided Query or Subscription operation responses, the result of which is
616
+ * then normalized and comitted to the publish queue.
617
+ *
618
+ * Note: Observables are lazy, so calling this method will do nothing until
619
+ * the result is subscribed to:
620
+ * environment.executeWithSource({...}).subscribe({...}).
621
+ */
622
+ executeWithSource({|
623
+ operation: OperationDescriptor,
624
+ source: RelayObservable<GraphQLResponse>,
625
+ |}): RelayObservable<GraphQLResponse>;
626
+
627
+ /**
628
+ * Returns true if a request is currently "active", meaning it's currently
629
+ * actively receiving payloads or downloading modules, and has not received
630
+ * a final payload yet. Note that a request might still be pending (or "in flight")
631
+ * without actively receiving payload, for example a live query or an
632
+ * active GraphQL subscription
633
+ */
634
+ isRequestActive(requestIdentifier: string): boolean;
635
+
636
+ /**
637
+ * Returns true if the environment is for use during server side rendering.
638
+ * functions like getQueryResource key off of this in order to determine
639
+ * whether we need to set up certain caches and timeout's.
640
+ */
641
+ isServer(): boolean;
642
+ }
643
+
644
+ /**
645
+ * The results of reading data for a fragment. This is similar to a `Selector`,
646
+ * but references the (fragment) node by name rather than by value.
647
+ */
648
+ export type FragmentPointer = {
649
+ __id: DataID,
650
+ __fragments: {[fragmentName: string]: Variables, ...},
651
+ __fragmentOwner: RequestDescriptor,
652
+ ...
653
+ };
654
+
655
+ /**
656
+ * The partial shape of an object with a '...Fragment @module(name: "...")'
657
+ * selection
658
+ */
659
+ export type ModuleImportPointer = {
660
+ +__fragmentPropName: ?string,
661
+ +__module_component: mixed,
662
+ +$fragmentRefs: mixed,
663
+ ...
664
+ };
665
+
666
+ /**
667
+ * A map of records affected by an update operation.
668
+ */
669
+ export type UpdatedRecords = {[dataID: DataID]: boolean, ...};
670
+
671
+ /**
672
+ * A function that updates a store (via a proxy) given the results of a "handle"
673
+ * field payload.
674
+ */
675
+ export type Handler = {
676
+ update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void,
677
+ ...
678
+ };
679
+
680
+ /**
681
+ * A payload that is used to initialize or update a "handle" field with
682
+ * information from the server.
683
+ */
684
+ export type HandleFieldPayload = {|
685
+ // The arguments that were fetched.
686
+ +args: Variables,
687
+ // The __id of the record containing the source/handle field.
688
+ +dataID: DataID,
689
+ // The (storage) key at which the original server data was written.
690
+ +fieldKey: string,
691
+ // The name of the handle.
692
+ +handle: string,
693
+ // The (storage) key at which the handle's data should be written by the
694
+ // handler.
695
+ +handleKey: string,
696
+ // The arguments applied to the handle
697
+ +handleArgs: Variables,
698
+ |};
699
+
700
+ /**
701
+ * A payload that represents data necessary to process the results of an object
702
+ * with a `@module` fragment spread:
703
+ * - data: The GraphQL response value for the @match field.
704
+ * - dataID: The ID of the store object linked to by the @match field.
705
+ * - operationReference: A reference to a generated module containing the
706
+ * SplitOperation with which to normalize the field's `data`.
707
+ * - variables: Query variables.
708
+ * - typeName: the type that matched.
709
+ *
710
+ * The dataID, variables, and fragmentName can be used to create a Selector
711
+ * which can in turn be used to normalize and publish the data. The dataID and
712
+ * typeName can also be used to construct a root record for normalization.
713
+ */
714
+ export type ModuleImportPayload = {|
715
+ +data: PayloadData,
716
+ +dataID: DataID,
717
+ +operationReference: mixed,
718
+ +path: $ReadOnlyArray<string>,
719
+ +typeName: string,
720
+ +variables: Variables,
721
+ |};
722
+
723
+ /**
724
+ * Data emitted after processing a Defer or Stream node during normalization
725
+ * that describes how to process the corresponding response chunk when it
726
+ * arrives.
727
+ */
728
+ export type DeferPlaceholder = {|
729
+ +kind: 'defer',
730
+ +data: PayloadData,
731
+ +label: string,
732
+ +path: $ReadOnlyArray<string>,
733
+ +selector: NormalizationSelector,
734
+ +typeName: string,
735
+ |};
736
+ export type StreamPlaceholder = {|
737
+ +kind: 'stream',
738
+ +label: string,
739
+ +path: $ReadOnlyArray<string>,
740
+ +parentID: DataID,
741
+ +node: NormalizationSelectableNode,
742
+ +variables: Variables,
743
+ |};
744
+ export type IncrementalDataPlaceholder = DeferPlaceholder | StreamPlaceholder;
745
+
746
+ /**
747
+ * A user-supplied object to load a generated operation (SplitOperation) AST
748
+ * by a module reference. The exact format of a module reference is left to
749
+ * the application, but it must be a plain JavaScript value (string, number,
750
+ * or object/array of same).
751
+ */
752
+ export type OperationLoader = {|
753
+ /**
754
+ * Synchronously load an operation, returning either the node or null if it
755
+ * cannot be resolved synchronously.
756
+ */
757
+ get(reference: mixed): ?NormalizationSplitOperation,
758
+
759
+ /**
760
+ * Asynchronously load an operation.
761
+ */
762
+ load(reference: mixed): Promise<?NormalizationSplitOperation>,
763
+ |};
764
+
765
+ /**
766
+ * A function that receives a proxy over the store and may trigger side-effects
767
+ * (indirectly) by calling `set*` methods on the store or its record proxies.
768
+ */
769
+ export type StoreUpdater = (store: RecordSourceProxy) => void;
770
+
771
+ /**
772
+ * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in
773
+ * order to easily access the root fields of a query/mutation as well as a
774
+ * second argument of the response object of the mutation.
775
+ */
776
+ export type SelectorStoreUpdater = (
777
+ store: RecordSourceSelectorProxy,
778
+ // Actually SelectorData, but mixed is inconvenient to access deeply in
779
+ // product code.
780
+ data: $FlowFixMe,
781
+ ) => void;
782
+
783
+ /**
784
+ * A set of configs that can be used to apply an optimistic update into the
785
+ * store.
786
+ */
787
+ export type OptimisticUpdate =
788
+ | OptimisticUpdateFunction
789
+ | OptimisticUpdateRelayPayload;
790
+
791
+ export type OptimisticUpdateFunction = {|
792
+ +storeUpdater: StoreUpdater,
793
+ |};
794
+
795
+ export type OptimisticUpdateRelayPayload = {|
796
+ +operation: OperationDescriptor,
797
+ +payload: RelayResponsePayload,
798
+ +updater: ?SelectorStoreUpdater,
799
+ |};
800
+
801
+ export type OptimisticResponseConfig = {|
802
+ +operation: OperationDescriptor,
803
+ +response: ?PayloadData,
804
+ +updater: ?SelectorStoreUpdater,
805
+ |};
806
+
807
+ /**
808
+ * A set of handlers that can be used to provide substitute data for missing
809
+ * fields when reading a selector from a source.
810
+ */
811
+ export type MissingFieldHandler =
812
+ | {|
813
+ kind: 'scalar',
814
+ handle: (
815
+ field: NormalizationScalarField,
816
+ record: ?Record,
817
+ args: Variables,
818
+ store: ReadOnlyRecordSourceProxy,
819
+ ) => mixed,
820
+ |}
821
+ | {|
822
+ kind: 'linked',
823
+ handle: (
824
+ field: NormalizationLinkedField,
825
+ record: ?Record,
826
+ args: Variables,
827
+ store: ReadOnlyRecordSourceProxy,
828
+ ) => ?DataID,
829
+ |}
830
+ | {|
831
+ kind: 'pluralLinked',
832
+ handle: (
833
+ field: NormalizationLinkedField,
834
+ record: ?Record,
835
+ args: Variables,
836
+ store: ReadOnlyRecordSourceProxy,
837
+ ) => ?Array<?DataID>,
838
+ |};
839
+
840
+ /**
841
+ * The results of normalizing a query.
842
+ */
843
+ export type RelayResponsePayload = {|
844
+ +errors: ?Array<PayloadError>,
845
+ +fieldPayloads: ?Array<HandleFieldPayload>,
846
+ +incrementalPlaceholders: ?Array<IncrementalDataPlaceholder>,
847
+ +moduleImportPayloads: ?Array<ModuleImportPayload>,
848
+ +source: MutableRecordSource,
849
+ +isFinal: boolean,
850
+ |};
851
+
852
+ /**
853
+ * Public interface for Publish Queue
854
+ */
855
+ export interface PublishQueue {
856
+ /**
857
+ * Schedule applying an optimistic updates on the next `run()`.
858
+ */
859
+ applyUpdate(updater: OptimisticUpdate): void;
860
+
861
+ /**
862
+ * Schedule reverting an optimistic updates on the next `run()`.
863
+ */
864
+ revertUpdate(updater: OptimisticUpdate): void;
865
+
866
+ /**
867
+ * Schedule a revert of all optimistic updates on the next `run()`.
868
+ */
869
+ revertAll(): void;
870
+
871
+ /**
872
+ * Schedule applying a payload to the store on the next `run()`.
873
+ */
874
+ commitPayload(
875
+ operation: OperationDescriptor,
876
+ payload: RelayResponsePayload,
877
+ updater?: ?SelectorStoreUpdater,
878
+ ): void;
879
+
880
+ /**
881
+ * Schedule an updater to mutate the store on the next `run()` typically to
882
+ * update client schema fields.
883
+ */
884
+ commitUpdate(updater: StoreUpdater): void;
885
+
886
+ /**
887
+ * Schedule a publish to the store from the provided source on the next
888
+ * `run()`. As an example, to update the store with substituted fields that
889
+ * are missing in the store.
890
+ */
891
+ commitSource(source: RecordSource): void;
892
+
893
+ /**
894
+ * Execute all queued up operations from the other public methods.
895
+ * Optionally provide an OperationDescriptor indicating the source operation
896
+ * that was being processed to produce this run.
897
+ */
898
+ run(sourceOperation?: OperationDescriptor): $ReadOnlyArray<RequestDescriptor>;
899
+ }