@salesforce/lds-adapters-graphql 1.311.1 → 1.312.0

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.
@@ -4,1337 +4,18 @@
4
4
  * For full license text, see the LICENSE.txt file
5
5
  */
6
6
 
7
- import { deepFreeze, StoreKeyMap } from '@luvio/engine';
8
- import { register } from '@salesforce/lds-default-luvio';
9
- import { Kind, astResolver } from '@luvio/graphql-parser';
7
+ import { astResolver } from '@luvio/graphql-parser';
10
8
  import { graphqlAdapterFactory } from '@salesforce/lds-adapters-uiapi';
11
- import { createIngestRecordWithFields, keyBuilderRecord } from '@salesforce/lds-adapters-uiapi';
12
- import ldsAdapterForwardingGate from '@salesforce/gate/lds.graphqlAdapterForwarding';
13
9
 
14
10
  const { isArray } = Array;
15
- const { keys, freeze, create } = Object;
16
11
  const { hasOwnProperty } = Object.prototype;
17
- const { parse, stringify } = JSON;
18
12
 
19
- function sortAndCopyUsingObjectKey(arr, key) {
20
- return [...arr].sort((a, b) => {
21
- const aKey = a[key];
22
- const bKey = b[key];
23
- if (aKey < bKey) {
24
- return -1;
25
- }
26
- if (aKey > bKey) {
27
- return 1;
28
- }
29
- return 0;
30
- });
31
- }
32
-
33
- function untrustedIsObject(untrusted) {
34
- return typeof untrusted === 'object' && untrusted !== null && isArray(untrusted) === false;
35
- }
36
- /**
37
- * A deterministic JSON stringify implementation. Heavily adapted from https://github.com/epoberezkin/fast-json-stable-stringify.
38
- * This is needed because insertion order for JSON.stringify(object) affects output:
39
- * JSON.stringify({a: 1, b: 2})
40
- * "{"a":1,"b":2}"
41
- * JSON.stringify({b: 2, a: 1})
42
- * "{"b":2,"a":1}"
43
- * @param data Data to be JSON-stringified.
44
- * @returns JSON.stringified value with consistent ordering of keys.
45
- */
46
- function stableJSONStringify(node) {
47
- // This is for Date values.
48
- if (node && node.toJSON && typeof node.toJSON === 'function') {
49
- // eslint-disable-next-line no-param-reassign
50
- node = node.toJSON();
51
- }
52
- if (node === undefined) {
53
- return '';
54
- }
55
- if (typeof node === 'number') {
56
- return isFinite(node) ? '' + node : 'null';
57
- }
58
- if (typeof node !== 'object') {
59
- return stringify(node);
60
- }
61
- let i;
62
- let out;
63
- if (isArray(node)) {
64
- node.sort();
65
- out = '[';
66
- for (i = 0; i < node.length; i++) {
67
- if (i) {
68
- out += ',';
69
- }
70
- out += stableJSONStringify(node[i]) || 'null';
71
- }
72
- return out + ']';
73
- }
74
- if (node === null) {
75
- return 'null';
76
- }
77
- const keys$1 = keys(node).sort();
78
- out = '';
79
- for (i = 0; i < keys$1.length; i++) {
80
- const key = keys$1[i];
81
- const value = stableJSONStringify(node[key]);
82
- if (!value) {
83
- continue;
84
- }
85
- if (out) {
86
- out += ',';
87
- }
88
- out += key + ':' + value;
89
- }
90
- return '{' + out + '}';
91
- }
13
+ const adapterName = 'graphQL';
92
14
  const namespace = 'GraphQL';
93
15
  const representationName = 'graphql';
94
-
95
- function serialize$1(args) {
96
- return serializeArgs(args, { render: false });
97
- }
98
- function render$1(args, variables) {
99
- return serializeArgs(args, { render: true, variables });
100
- }
101
- function serializeArgs(args, option) {
102
- const sortedArgs = option.render === true ? sortAndCopyUsingObjectKey(args, 'name') : args;
103
- let str = '';
104
- for (let i = 0, len = sortedArgs.length; i < len; i += 1) {
105
- str = `${str}${serializeArgumentNode(sortedArgs[i], option)}`;
106
- if (len > 1 && i < len - 1) {
107
- str = `${str},`;
108
- }
109
- }
110
- return str;
111
- }
112
- function serializeArgumentValueNode(valueDefinition, option) {
113
- const { kind } = valueDefinition;
114
- switch (kind) {
115
- case 'ObjectValue':
116
- return serializeAndSortObjectValueNode(valueDefinition, option);
117
- case 'ListValue':
118
- return serializeAndSortListValueNode(valueDefinition, option);
119
- case 'Variable':
120
- return serializeVariableNode$1(valueDefinition, option);
121
- default:
122
- return serializeValueNode(valueDefinition);
123
- }
124
- }
125
- function serializeVariableNode$1(literalValueNode, option) {
126
- if (option.render === false) {
127
- return `$${literalValueNode.name}`;
128
- }
129
- return `${serializeVariableValue(option.variables[literalValueNode.name])}`;
130
- }
131
- function serializeVariableValue(value) {
132
- return stableJSONStringify(value);
133
- }
134
- function serializeAndSortListValueNode(objectValueDefinition, option) {
135
- const { values } = objectValueDefinition;
136
- const str = [];
137
- const sorted = option.render === true ? sortAndCopyUsingObjectKey(values, 'value') : values;
138
- for (let i = 0, len = sorted.length; i < len; i += 1) {
139
- str.push(serializeArgumentValueNode(sorted[i], option));
140
- }
141
- return `[${str.join(',')}]`;
142
- }
143
- function serializeAndSortObjectValueNode(objectValueDefinition, option) {
144
- const { fields } = objectValueDefinition;
145
- let str = '';
146
- const fieldKeys = keys(fields).sort();
147
- for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
148
- const fieldKey = fieldKeys[i];
149
- str = `${str}${fieldKey}:${serializeArgumentValueNode(fields[fieldKey], option)}`;
150
- if (len > 1 && i < len - 1) {
151
- str = `${str},`;
152
- }
153
- }
154
- return `{${str}}`;
155
- }
156
- function serializeArgumentNode(arg, option) {
157
- const { name, value } = arg;
158
- return `${name}:${serializeArgumentValueNode(value, option)}`;
159
- }
160
-
161
- function render(sel, variables) {
162
- return serializeField(sel, { render: true, variables });
163
- }
164
- function serializeField(sel, option) {
165
- const { name: fieldName } = sel;
166
- if (sel.kind === 'ScalarFieldSelection') {
167
- return fieldName;
168
- }
169
- const { arguments: selectionArguments } = sel;
170
- if (selectionArguments === undefined || selectionArguments.length === 0) {
171
- return fieldName;
172
- }
173
- return `${fieldName}(${option.render === true
174
- ? render$1(selectionArguments, option.variables)
175
- : serialize$1(selectionArguments)})`;
176
- }
177
-
178
- function readScalarFieldSelection(builder, source, fieldName, sink) {
179
- const gqlData = source[fieldName];
180
- if (gqlData !== undefined && gqlData !== null && gqlData.__ref !== undefined) {
181
- if (process.env.NODE_ENV !== 'production') {
182
- throw new Error(`Scalar requested at "${fieldName}" but is instead an object at "${gqlData.__ref}"`);
183
- }
184
- }
185
- builder.readScalar(fieldName, source, sink);
186
- }
187
-
188
- const CUSTOM_FIELD_NODE_TYPE = 'Record';
189
- const RECORD_DEFAULT_FIELD_VALUES = ['value', 'displayValue'];
190
- function collectObjectFieldSelection(data) {
191
- return {
192
- value: data.value,
193
- displayValue: data.displayValue,
194
- };
195
- }
196
- function childTypeIsChildRelationships(sel, _data) {
197
- return sel.type === CONNECTION_NODE_TYPE;
198
- }
199
- function childTypeIsSpanningGqlRecord(sel, _data) {
200
- return sel.type === CUSTOM_FIELD_NODE_TYPE;
201
- }
202
- function convertAstToTrie(ast) {
203
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
204
- const children = {};
205
- const trie = {
206
- name: ast.name,
207
- children,
208
- };
209
- for (let i = 0, len = selections.length; i < len; i += 1) {
210
- const sel = getLuvioFieldNodeSelection(selections[i]);
211
- const { name: selName, kind } = sel;
212
- switch (kind) {
213
- case 'ObjectFieldSelection': {
214
- children[selName] = {
215
- name: selName,
216
- children: {},
217
- };
218
- break;
219
- }
220
- case 'CustomFieldSelection': {
221
- children[selName] = convertAstToTrie(sel);
222
- break;
223
- }
224
- }
225
- }
226
- return trie;
227
- }
228
- function formatSpanningCustomFieldSelection(sel, data) {
229
- if (data === null) {
230
- return {
231
- value: {
232
- displayValue: null,
233
- value: null,
234
- },
235
- trie: convertAstToTrie(sel),
236
- };
237
- }
238
- const { recordRepresentation, fieldsTrie } = convertToRecordRepresentation(sel, data);
239
- return {
240
- trie: fieldsTrie,
241
- value: {
242
- displayValue: data.DisplayValue,
243
- value: recordRepresentation,
244
- },
245
- };
246
- }
247
- function convertToRecordRepresentation(ast, record) {
248
- const { Id, WeakEtag, ApiName, LastModifiedById, LastModifiedDate, SystemModstamp, ldsRecordTypeId, } = record;
249
- const { luvioSelections } = ast;
250
- if (luvioSelections === undefined) {
251
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
252
- throw new Error('Undefined selections');
253
- }
254
- const trieChildren = {};
255
- const trie = {
256
- name: ApiName,
257
- children: trieChildren,
258
- };
259
- const childRelationships = {};
260
- const fieldsBag = {};
261
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
262
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
263
- const { name: fieldName, alias } = sel;
264
- const propertyName = alias === undefined ? fieldName : alias;
265
- const data = record[propertyName];
266
- switch (sel.kind) {
267
- case 'ObjectFieldSelection': {
268
- trieChildren[fieldName] = {
269
- name: fieldName,
270
- children: {},
271
- };
272
- fieldsBag[fieldName] = collectObjectFieldSelection(data);
273
- break;
274
- }
275
- case 'CustomFieldSelection': {
276
- if (childTypeIsSpanningGqlRecord(sel)) {
277
- const { value, trie } = formatSpanningCustomFieldSelection(sel, data);
278
- trieChildren[fieldName] = trie;
279
- fieldsBag[fieldName] = value;
280
- }
281
- else if (childTypeIsChildRelationships(sel)) {
282
- childRelationships[fieldName] = {
283
- ast: sel,
284
- data: data,
285
- };
286
- }
287
- break;
288
- }
289
- }
290
- }
291
- const rep = {
292
- apiName: ApiName,
293
- eTag: '',
294
- lastModifiedById: LastModifiedById.value,
295
- lastModifiedDate: LastModifiedDate.value,
296
- systemModstamp: SystemModstamp.value,
297
- recordTypeId: ldsRecordTypeId === null ? null : ldsRecordTypeId.value,
298
- recordTypeInfo: null,
299
- childRelationships: {},
300
- id: Id,
301
- weakEtag: WeakEtag,
302
- fields: fieldsBag,
303
- };
304
- return {
305
- recordRepresentation: rep,
306
- fieldsTrie: trie,
307
- childRelationships,
308
- };
309
- }
310
- const defaultRecordFieldsFragmentName = 'defaultRecordFields';
311
- const defaultRecordFieldsFragment = `fragment ${defaultRecordFieldsFragmentName} on Record { __typename, ApiName, WeakEtag, Id, DisplayValue, SystemModstamp { value } LastModifiedById { value } LastModifiedDate { value } ldsRecordTypeId: RecordTypeId(fallback: true) { value } }`;
312
- function getChildRelationshipsKey(recordKey, propertyName) {
313
- return `${recordKey}__childRelationships__${propertyName}`;
314
- }
315
- const createIngest$4 = (ast, variables) => {
316
- return (data, path, luvio, store, timestamp) => {
317
- const { recordRepresentation, fieldsTrie, childRelationships } = convertToRecordRepresentation(ast, data);
318
- const ingestRecord = createIngestRecordWithFields(fieldsTrie, {
319
- name: recordRepresentation.apiName,
320
- children: {},
321
- });
322
- const recordIngest = ingestRecord(recordRepresentation, path, luvio, store, timestamp);
323
- const recordKey = recordIngest.__ref;
324
- const childRelationshipKeys = Object.keys(childRelationships);
325
- for (let i = 0, len = childRelationshipKeys.length; i < len; i += 1) {
326
- const propertyName = childRelationshipKeys[i];
327
- const childRelationship = childRelationships[propertyName];
328
- const { ast: childRelationshipAst, data: childRelationshipData } = childRelationship;
329
- const fullPath = getChildRelationshipsKey(recordKey, propertyName);
330
- createIngest$1(childRelationshipAst, fullPath, variables)(childRelationshipData, {
331
- parent: {
332
- data,
333
- key: recordKey,
334
- existing: undefined,
335
- },
336
- fullPath: fullPath,
337
- propertyName: propertyName,
338
- }, luvio, store, timestamp);
339
- }
340
- return recordIngest;
341
- };
342
- };
343
- const recordProperties = {
344
- Id: {
345
- propertyName: 'id',
346
- },
347
- ApiName: {
348
- propertyName: 'apiName',
349
- },
350
- };
351
- function getNonSpanningField(sel, builder, source) {
352
- const sink = {};
353
- const { luvioSelections } = sel;
354
- if (luvioSelections === undefined) {
355
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
356
- throw new Error('Empty selections not supported');
357
- }
358
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
359
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
360
- const { kind } = sel;
361
- const name = sel.name;
362
- builder.enterPath(name);
363
- if (kind !== 'ScalarFieldSelection') {
364
- if (process.env.NODE_ENV !== 'production') {
365
- throw new Error(`Unexpected kind "${kind}"`);
366
- }
367
- }
368
- builder.assignScalar(name, sink, source[name]);
369
- builder.exitPath();
370
- }
371
- return sink;
372
- }
373
- function getCustomSelection(luvio, selection, builder, options, variables) {
374
- const { type } = selection;
375
- switch (type) {
376
- case 'Record':
377
- return readRecordRepresentation(luvio, selection, builder, options, variables);
378
- }
379
- }
380
- function getScalarValue(selectionName, state) {
381
- if (selectionName === 'DisplayValue') {
382
- const { parentFieldValue } = state;
383
- if (parentFieldValue === undefined) {
384
- if (process.env.NODE_ENV !== 'production') {
385
- throw new Error('Unable to calculate DisplayValue');
386
- }
387
- else {
388
- return undefined;
389
- }
390
- }
391
- return parentFieldValue.displayValue;
392
- }
393
- const assignment = recordProperties[selectionName];
394
- if (assignment === undefined) {
395
- if (process.env.NODE_ENV !== 'production') {
396
- throw new Error(`Unknown assignment for ScalarFieldSelection at property "${selectionName}"`);
397
- }
398
- }
399
- return state.source[assignment.propertyName];
400
- }
401
- function assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables) {
402
- const key = getChildRelationshipsKey(recordKey, propertyName);
403
- const resolved = resolveKey(builder, key);
404
- if (resolved === undefined) {
405
- return;
406
- }
407
- const data = createRead$2(luvio, sel, variables)(resolved.value, builder);
408
- builder.assignNonScalar(sink, propertyName, data);
409
- }
410
- function assignSelection(luvio, selection, builder, state, variables) {
411
- const sel = getLuvioFieldNodeSelection(selection);
412
- const { name: selectionName, kind, alias } = sel;
413
- const propertyName = alias === undefined ? selectionName : alias;
414
- const { source, sink } = state;
415
- const { fields } = source;
416
- builder.enterPath(selectionName);
417
- switch (kind) {
418
- case 'ScalarFieldSelection': {
419
- builder.assignScalar(propertyName, sink, getScalarValue(selectionName, state));
420
- break;
421
- }
422
- case 'ObjectFieldSelection': {
423
- // regular field, not spanning
424
- const field = propertyLookup(builder, selectionName, fields);
425
- if (field.state === PropertyLookupResultState.Missing) {
426
- break;
427
- }
428
- const resolved = resolveLink(builder, field.value);
429
- if (resolved === undefined) {
430
- break;
431
- }
432
- const data = getNonSpanningField(sel, builder, resolved.value);
433
- builder.assignNonScalar(sink, propertyName, data);
434
- break;
435
- }
436
- case 'CustomFieldSelection': {
437
- if (sel.type === 'Connection') {
438
- const recordKey = keyBuilderRecord(luvio, {
439
- recordId: state.source.id,
440
- });
441
- assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables);
442
- }
443
- else {
444
- const field = fields[selectionName];
445
- const resolvedParentFieldValue = resolveLink(builder, field);
446
- if (resolvedParentFieldValue === undefined) {
447
- break;
448
- }
449
- const { value: spanningFieldResult } = resolvedParentFieldValue;
450
- const { value: spanningFieldValue } = spanningFieldResult;
451
- if (spanningFieldValue === null || typeof spanningFieldValue !== 'object') {
452
- sink[propertyName] = null;
453
- break;
454
- }
455
- const resolvedSpanningRecordValue = resolveLink(builder, spanningFieldValue);
456
- if (resolvedSpanningRecordValue === undefined) {
457
- break;
458
- }
459
- const data = getCustomSelection(luvio, sel, builder, {
460
- source: resolvedSpanningRecordValue.value,
461
- parentFieldValue: spanningFieldResult,
462
- }, variables);
463
- builder.assignNonScalar(sink, propertyName, data);
464
- }
465
- }
466
- }
467
- builder.exitPath();
468
- }
469
- function readRecordRepresentation(luvio, ast, builder, options, variables) {
470
- const { luvioSelections } = ast;
471
- if (luvioSelections === undefined) {
472
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
473
- throw new Error('Empty selections not supported');
474
- }
475
- const sink = {};
476
- const state = {
477
- source: options.source,
478
- sink,
479
- parentFieldValue: options.parentFieldValue,
480
- };
481
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
482
- assignSelection(luvio, luvioSelections[i], builder, state, variables);
483
- }
484
- return sink;
485
- }
486
- const createRead$3 = (luvio, ast, variables) => {
487
- return (data, builder) => {
488
- return readRecordRepresentation(luvio, ast, builder, {
489
- source: data,
490
- parentFieldValue: undefined,
491
- }, variables);
492
- };
493
- };
494
-
495
- const createIngest$3 = (ast, variables) => {
496
- const { type } = ast;
497
- switch (type) {
498
- case CUSTOM_FIELD_NODE_TYPE:
499
- return createIngest$4(ast, variables);
500
- case CONNECTION_NODE_TYPE:
501
- return createIngest$1(ast, keyBuilder(ast, variables), variables);
502
- }
503
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
504
- throw new Error(`Unsupported type: "${type}"`);
505
- };
506
-
507
- function merge(existing, incoming) {
508
- if (existing === undefined) {
509
- return incoming;
510
- }
511
- // Merge existing and incoming values together
512
- return {
513
- ...existing,
514
- ...incoming,
515
- };
516
- }
517
-
518
- function resolveValue(ast, variables, source) {
519
- const { alias } = ast;
520
- const propertyName = render(ast, variables);
521
- if (process.env.NODE_ENV !== 'production') {
522
- if (alias !== undefined && alias in source) {
523
- throw new Error(`Invalid alias "${alias}" passed to "equal" function. All aliases need to be normalized before calling equal`);
524
- }
525
- }
526
- return source[propertyName];
527
- }
528
- function linkEquals(ast, variables, existing, incoming) {
529
- const value = resolveValue(ast, variables, existing);
530
- if (value === undefined) {
531
- return false;
532
- }
533
- const incomingLink = resolveValue(ast, variables, incoming);
534
- if (process.env.NODE_ENV !== 'production') {
535
- if (incomingLink === undefined) {
536
- throw new Error('Unexpected undefined link');
537
- }
538
- }
539
- return value.__ref === incomingLink.__ref;
540
- }
541
- function scalarFieldEquals(ast, variables, existing, incoming) {
542
- const { name } = ast;
543
- const value = existing[name];
544
- if (value === undefined) {
545
- return false;
546
- }
547
- return value === resolveValue(ast, variables, incoming);
548
- }
549
- function equals(ast, variables, existing, incoming) {
550
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
551
- for (let i = 0, len = selections.length; i < len; i += 1) {
552
- const sel = getLuvioFieldNodeSelection(selections[i]);
553
- if (sel.kind === 'ScalarFieldSelection') {
554
- if (scalarFieldEquals(sel, variables, existing, incoming) === false) {
555
- return false;
556
- }
557
- }
558
- else {
559
- if (linkEquals(sel, variables, existing, incoming) === false) {
560
- return false;
561
- }
562
- }
563
- }
564
- return true;
565
- }
566
-
567
- const DEFAULT_GRAPHQL_TTL = 30000;
568
- const GRAPHQL_INGEST_VERSION = 'GRAPHQL_INGEST_VERSION_1';
569
- function createIngest$2(ast, variables) {
570
- if (ast.kind === 'CustomFieldSelection') {
571
- return createIngest$3(ast, variables);
572
- }
573
- return genericCreateIngest(ast, variables);
574
- }
575
- function publishDataIfChanged(params) {
576
- const { store, key, ast, incoming, luvio, variables } = params;
577
- const existing = store.readEntry(key);
578
- if (existing === undefined || equals(ast, variables, existing, incoming) === false) {
579
- const newData = merge(existing, incoming);
580
- luvio.storePublish(key, newData);
581
- }
582
- }
583
- function genericCreateIngest(ast, variables) {
584
- let selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
585
- return (data, path, luvio, store, timestamp) => {
586
- const { fullPath } = path;
587
- for (let i = 0, len = selections.length; i < len; i += 1) {
588
- const sel = getLuvioFieldNodeSelection(selections[i]);
589
- if (sel.kind === 'ScalarFieldSelection') {
590
- continue;
591
- }
592
- const { name: fieldName, alias } = sel;
593
- const readPropertyName = alias === undefined ? fieldName : alias;
594
- const propertyFullPath = `${fullPath}__${fieldName}`;
595
- const writePropertyName = render(sel, variables);
596
- const childPath = {
597
- parent: {
598
- existing: null,
599
- key: fullPath,
600
- data,
601
- },
602
- propertyName: readPropertyName,
603
- fullPath: propertyFullPath,
604
- };
605
- data[writePropertyName] = createIngest$2(sel, variables)(data[readPropertyName], childPath, luvio, store, timestamp);
606
- if (writePropertyName !== readPropertyName && data[readPropertyName] !== undefined) {
607
- delete data[readPropertyName];
608
- }
609
- }
610
- publishDataIfChanged({
611
- ast,
612
- luvio,
613
- store,
614
- key: fullPath,
615
- variables: {},
616
- incoming: data,
617
- });
618
- if (data && data.__typename !== undefined) {
619
- luvio.publishStoreMetadata(fullPath, {
620
- representationName: data.__typename,
621
- namespace: namespace,
622
- ttl: DEFAULT_GRAPHQL_TTL,
623
- version: GRAPHQL_INGEST_VERSION,
624
- ingestionTimestamp: timestamp,
625
- });
626
- }
627
- return {
628
- __ref: fullPath,
629
- };
630
- };
631
- }
632
-
633
- const CONNECTION_NODE_TYPE = 'Connection';
634
- const TYPENAME_FIELD$1 = '__typename';
635
- const PAGE_INFO_REQUIRED_FIELDS = ['hasNextPage', 'hasPreviousPage'];
636
- const EDGE_REQUIRED_FIELDS = ['cursor'];
637
- const PROPERTY_NAME_EDGES = 'edges';
638
- const PROPERTY_NAME_PAGE_INFO = 'pageInfo';
639
- const PROPERTY_NAME_TOTAL_COUNT = 'totalCount';
640
- function keyBuilder(ast, variables) {
641
- const { arguments: args, name } = ast;
642
- if (args === undefined) {
643
- return `${namespace}::${CONNECTION_NODE_TYPE}:${name}()`;
644
- }
645
- const serialized = render$1(args, variables);
646
- return `${namespace}::${CONNECTION_NODE_TYPE}:${name}(${serialized})`;
647
- }
648
- function selectEdges(luvio, builder, ast, links, variables) {
649
- const sink = [];
650
- for (let i = 0, len = links.length; i < len; i += 1) {
651
- builder.enterPath(i);
652
- const link = links[i];
653
- const resolved = followLink(luvio, ast, builder, link, variables);
654
- builder.assignNonScalar(sink, i, resolved);
655
- builder.exitPath();
656
- }
657
- return sink;
658
- }
659
- const createRead$2 = (luvio, ast, variables) => {
660
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
661
- return (source, builder) => {
662
- const sink = {};
663
- for (let i = 0, len = selections.length; i < len; i += 1) {
664
- const sel = getLuvioFieldNodeSelection(selections[i]);
665
- const { name, kind } = sel;
666
- if (kind === 'ScalarFieldSelection') {
667
- readScalarFieldSelection(builder, source, name, sink);
668
- continue;
669
- }
670
- const readPropertyName = render(sel, variables);
671
- builder.enterPath(readPropertyName);
672
- const edges = resolveLink(builder, source[readPropertyName]);
673
- if (edges === undefined) {
674
- builder.exitPath();
675
- break;
676
- }
677
- if (readPropertyName === PROPERTY_NAME_EDGES) {
678
- const data = selectEdges(luvio, builder, sel, edges.value, variables);
679
- builder.assignNonScalar(sink, readPropertyName, data);
680
- }
681
- else {
682
- if (process.env.NODE_ENV !== 'production') {
683
- throw new Error('Not supported');
684
- }
685
- }
686
- builder.exitPath();
687
- }
688
- return sink;
689
- };
690
- };
691
- function ingestConnectionProperty(sel, data, path, luvio, store, timestamp, variables) {
692
- const propertyName = sel.name;
693
- switch (propertyName) {
694
- case PROPERTY_NAME_EDGES:
695
- return ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables);
696
- }
697
- }
698
- function ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables) {
699
- const key = path.fullPath;
700
- const existing = store.readEntry(key);
701
- let hasChanges = existing === undefined || data.length !== existing.length;
702
- for (let i = 0, len = data.length; i < len; i += 1) {
703
- const incomingItem = (data[i] = createIngest$2(sel, variables)(data[i], {
704
- parent: {
705
- data,
706
- existing: null,
707
- key,
708
- },
709
- propertyName: i,
710
- fullPath: `${key}__${i}`,
711
- }, luvio, store, timestamp));
712
- const existingItem = existing !== undefined ? existing[i] : undefined;
713
- if (existingItem === undefined || existingItem.__ref !== incomingItem.__ref) {
714
- hasChanges = true;
715
- }
716
- }
717
- if (hasChanges === true) {
718
- luvio.storePublish(key, data);
719
- }
720
- luvio.publishStoreMetadata(key, {
721
- representationName: CONNECTION_NODE_TYPE,
722
- namespace: namespace,
723
- ttl: DEFAULT_GRAPHQL_TTL,
724
- version: GRAPHQL_INGEST_VERSION,
725
- ingestionTimestamp: timestamp,
726
- });
727
- return {
728
- __ref: key,
729
- };
730
- }
731
- const createIngest$1 = (ast, key, variables) => {
732
- const { luvioSelections } = ast;
733
- const selections = luvioSelections === undefined ? [] : luvioSelections;
734
- return (data, path, luvio, store, timestamp) => {
735
- for (let i = 0, len = selections.length; i < len; i += 1) {
736
- const sel = getLuvioFieldNodeSelection(selections[i]);
737
- const { kind } = sel;
738
- const propertyName = sel.name;
739
- if (kind !== 'ObjectFieldSelection') {
740
- continue;
741
- }
742
- data[propertyName] = ingestConnectionProperty(sel, data[propertyName], {
743
- parent: {
744
- existing: null,
745
- key,
746
- data,
747
- },
748
- fullPath: `${key}__${propertyName}`,
749
- propertyName,
750
- }, luvio, store, timestamp, variables);
751
- }
752
- publishDataIfChanged({
753
- key,
754
- luvio,
755
- store,
756
- incoming: data,
757
- variables: {},
758
- ast,
759
- });
760
- const typeName = data.__typename;
761
- luvio.publishStoreMetadata(key, {
762
- representationName: typeName,
763
- namespace: namespace,
764
- ttl: DEFAULT_GRAPHQL_TTL,
765
- version: GRAPHQL_INGEST_VERSION,
766
- ingestionTimestamp: timestamp,
767
- });
768
- return {
769
- __ref: key,
770
- };
771
- };
772
- };
773
- function serialize(def, state) {
774
- const { luvioSelections, arguments: args } = def;
775
- if (luvioSelections === undefined) {
776
- if (process.env.NODE_ENV !== 'production') {
777
- throw new Error('Connection field node must have selections');
778
- }
779
- return '';
780
- }
781
- const argsString = args === undefined || args.length === 0 ? '' : `(${serializeArguments(args)})`;
782
- const seenFields = {};
783
- const serializedFields = [];
784
- for (let i = 0; i < luvioSelections.length; i++) {
785
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
786
- const { name: fieldName } = sel;
787
- seenFields[fieldName] = true;
788
- if (fieldName === PROPERTY_NAME_PAGE_INFO) {
789
- serializedFields.push(serializePageInfo(sel, state));
790
- }
791
- else if (fieldName === PROPERTY_NAME_EDGES) {
792
- serializedFields.push(serializeEdges(sel, state));
793
- }
794
- else {
795
- serializedFields.push(serializeFieldNode(sel, state));
796
- }
797
- }
798
- appendRequiredConnectionFields(seenFields, serializedFields);
799
- return `${serializeFieldNodeName(def)}${argsString} { ${serializedFields.join(' ')} }`;
800
- }
801
- function serializeEdges(node, state) {
802
- if (!isLuvioFieldNodeObjectFieldNode(node)) {
803
- if (process.env.NODE_ENV !== 'production') {
804
- throw new Error('PageInfo must be an ObjectFieldNode');
805
- }
806
- return '';
807
- }
808
- const { luvioSelections } = node;
809
- if (luvioSelections === undefined)
810
- return '';
811
- const seenFields = {};
812
- const serializedFields = [];
813
- for (let i = 0; i < luvioSelections.length; i++) {
814
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
815
- seenFields[sel.name] = true;
816
- serializedFields.push(serializeFieldNode(sel, state));
817
- }
818
- appendRequiredFields(EDGE_REQUIRED_FIELDS, seenFields, serializedFields);
819
- insertTypeName(seenFields, serializedFields);
820
- return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
821
- }
822
- function serializePageInfo(node, state) {
823
- if (!isLuvioFieldNodeObjectFieldNode(node)) {
824
- if (process.env.NODE_ENV !== 'production') {
825
- throw new Error('PageInfo must be an ObjectFieldNode');
826
- }
827
- return '';
828
- }
829
- const { luvioSelections } = node;
830
- if (luvioSelections === undefined)
831
- return '';
832
- const seenFields = {};
833
- const serializedFields = [];
834
- for (let i = 0; i < luvioSelections.length; i++) {
835
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
836
- seenFields[sel.name] = true;
837
- serializedFields.push(serializeFieldNode(sel, state));
838
- }
839
- appendRequiredFields(PAGE_INFO_REQUIRED_FIELDS, seenFields, serializedFields);
840
- return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
841
- }
842
- function appendRequiredFields(requiredFields, seenFields, result) {
843
- for (let i = 0; i < requiredFields.length; i++) {
844
- const fieldName = requiredFields[i];
845
- if (seenFields[fieldName] !== true) {
846
- result.push(fieldName);
847
- }
848
- }
849
- }
850
- function appendRequiredConnectionFields(seenFields, result) {
851
- if (seenFields[PROPERTY_NAME_PAGE_INFO] !== true) {
852
- result.push('pageInfo { hasNextPage hasPreviousPage }');
853
- }
854
- if (seenFields[PROPERTY_NAME_TOTAL_COUNT] !== true) {
855
- result.push(PROPERTY_NAME_TOTAL_COUNT);
856
- }
857
- insertTypeName(seenFields, result);
858
- }
859
- function insertTypeName(seenFields, result) {
860
- if (seenFields[TYPENAME_FIELD$1] !== true) {
861
- result.unshift(TYPENAME_FIELD$1);
862
- }
863
- }
864
-
865
- function createCustomFieldRead(luvio, sel, variables) {
866
- if (sel.type === 'Connection') {
867
- return createRead$2(luvio, sel, variables);
868
- }
869
- return createRead$3(luvio, sel, variables);
870
- }
871
- function createRead$1(luvio, ast, variables) {
872
- if (ast.kind === 'CustomFieldSelection') {
873
- return createCustomFieldRead(luvio, ast, variables);
874
- }
875
- if (ast.kind === 'FragmentSpread' ||
876
- ast.kind === 'InlineFragment' ||
877
- ast.kind === 'ScalarFieldSelection') {
878
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
879
- throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
880
- }
881
- return genericCreateRead(luvio, ast, variables);
882
- }
883
- const genericCreateRead = (luvio, ast, variables) => {
884
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
885
- return (source, builder) => {
886
- const sink = {};
887
- for (let i = 0, len = selections.length; i < len; i += 1) {
888
- const sel = getLuvioFieldNodeSelection(selections[i]);
889
- const { name: fieldName, alias } = sel;
890
- const propertyName = alias === undefined ? fieldName : alias;
891
- builder.enterPath(fieldName);
892
- switch (sel.kind) {
893
- case 'ScalarFieldSelection':
894
- readScalarFieldSelection(builder, source, fieldName, sink);
895
- break;
896
- default: {
897
- const data = followLink(luvio, sel, builder, source[render(sel, variables)], variables);
898
- builder.assignNonScalar(sink, propertyName, data);
899
- }
900
- }
901
- builder.exitPath();
902
- }
903
- return sink;
904
- };
905
- };
906
-
907
- var PropertyLookupResultState;
908
- (function (PropertyLookupResultState) {
909
- PropertyLookupResultState[PropertyLookupResultState["Missing"] = 0] = "Missing";
910
- PropertyLookupResultState[PropertyLookupResultState["Present"] = 1] = "Present";
911
- })(PropertyLookupResultState || (PropertyLookupResultState = {}));
912
- const objectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty;
913
- function propertyLookup(builder, key, source) {
914
- if (objectPrototypeHasOwnProperty.call(source, key) === false) {
915
- builder.markMissing();
916
- return {
917
- state: PropertyLookupResultState.Missing,
918
- };
919
- }
920
- return {
921
- state: PropertyLookupResultState.Present,
922
- value: source[key],
923
- };
924
- }
925
- function markStoreResolveResultSeen(builder, state) {
926
- const { redirects, resolvedKey } = state;
927
- builder.markSeenId(resolvedKey);
928
- const { length: len } = redirects;
929
- if (len === 0) {
930
- return;
931
- }
932
- for (let i = 0; i < len; i += 1) {
933
- builder.markSeenId(redirects[i]);
934
- }
935
- }
936
- function resolveKey(builder, key) {
937
- const { StoreResolveResultState } = builder;
938
- const lookup = builder.storeLookup(key);
939
- markStoreResolveResultSeen(builder, lookup);
940
- switch (lookup.state) {
941
- case StoreResolveResultState.NotPresent:
942
- builder.markMissingLink(key);
943
- return;
944
- case StoreResolveResultState.Stale:
945
- builder.markStale();
946
- return lookup;
947
- case StoreResolveResultState.Error:
948
- if (process.env.NODE_ENV !== 'production') {
949
- throw new Error('TODO: Implement error links');
950
- }
951
- else {
952
- return;
953
- }
954
- }
955
- return lookup;
956
- }
957
- function resolveLink(builder, storeLink) {
958
- const { StoreLinkStateValues } = builder;
959
- const linkState = builder.getLinkState(storeLink);
960
- switch (linkState.state) {
961
- case StoreLinkStateValues.RefNotPresent:
962
- case StoreLinkStateValues.NotPresent:
963
- case StoreLinkStateValues.Missing:
964
- builder.markMissing();
965
- return;
966
- case StoreLinkStateValues.Pending:
967
- builder.markPending();
968
- return;
969
- case StoreLinkStateValues.Null:
970
- if (process.env.NODE_ENV !== 'production') {
971
- throw new Error(`TODO: Invalid Link State. Link on "${builder.currentPath.fullPath}"`);
972
- }
973
- else {
974
- return;
975
- }
976
- }
977
- const { key: __ref } = linkState;
978
- return resolveKey(builder, __ref);
979
- }
980
- function followLink(luvio, sel, builder, storeLink, variables) {
981
- const linkState = resolveLink(builder, storeLink);
982
- if (linkState === undefined) {
983
- return;
984
- }
985
- const { value } = linkState;
986
- return createRead$1(luvio, sel, variables)(value, builder);
987
- }
988
- function getLuvioFieldNodeSelection(ast) {
989
- const { kind } = ast;
990
- if (kind === 'FragmentSpread' || kind === 'InlineFragment') {
991
- if (process.env.NODE_ENV !== 'production') {
992
- throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
993
- }
994
- }
995
- return ast;
996
- }
997
-
998
- const TYPENAME_FIELD = '__typename';
999
- const KIND_OBJECT_FIELD_SELECTION = 'ObjectFieldSelection';
1000
- function serializeFieldNodeName(node) {
1001
- const { name, alias } = node;
1002
- return alias === undefined ? `${name}` : `${alias}: ${name}`;
1003
- }
1004
- function serializeSelections(selections, state) {
1005
- if (selections === undefined) {
1006
- return '';
1007
- }
1008
- let str = '';
1009
- for (let i = 0, len = selections.length; i < len; i += 1) {
1010
- const def = serializeFieldNode(selections[i], state);
1011
- str = `${str}${def}`;
1012
- }
1013
- return str;
1014
- }
1015
- function serializeFieldNode(def, state) {
1016
- const { kind } = def;
1017
- switch (kind) {
1018
- case 'ObjectFieldSelection':
1019
- return serializeObjectFieldNode(def, state);
1020
- case 'CustomFieldSelection':
1021
- return serializeCustomFieldNode(def, state);
1022
- case 'ScalarFieldSelection':
1023
- return serializeScalarFieldNode(def);
1024
- }
1025
- if (process.env.NODE_ENV !== 'production') {
1026
- throw new Error(`Unable to serialize graphql query, unsupported field node "${kind}"`);
1027
- }
1028
- return '';
1029
- }
1030
- function serializeObjectFieldNode(def, state) {
1031
- const { luvioSelections, arguments: defArgs } = def;
1032
- const args = defArgs === undefined ? '' : `(${serializeArguments(defArgs)})`;
1033
- return `${serializeFieldNodeName(def)}${args} { ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1034
- }
1035
- function serializeCustomFieldNode(def, state) {
1036
- const { type } = def;
1037
- switch (type) {
1038
- case 'Connection':
1039
- return serialize(def, state);
1040
- case 'Record':
1041
- return serializeCustomFieldRecord(def, state);
1042
- }
1043
- if (process.env.NODE_ENV !== 'production') {
1044
- throw new Error(`Unable to serialize graphql query, unsupported CustomField type "${type}"`);
1045
- }
1046
- return '';
1047
- }
1048
- function serializeScalarFieldNode(def) {
1049
- return `${serializeFieldNodeName(def)}, `;
1050
- }
1051
- function serializeRecordSelections(selections, state) {
1052
- if (selections === undefined) {
1053
- return '';
1054
- }
1055
- let str = '';
1056
- for (let i = 0, len = selections.length; i < len; i += 1) {
1057
- const sel = getLuvioFieldNodeSelection(selections[i]);
1058
- const def = isLuvioFieldNodeObjectFieldNode(sel)
1059
- ? serializeObjectFieldNodeUnderRecord(sel)
1060
- : serializeFieldNode(sel, state);
1061
- str = `${str}${def}`;
1062
- }
1063
- return str;
1064
- }
1065
- function isLuvioFieldNodeObjectFieldNode(node) {
1066
- return node.kind === KIND_OBJECT_FIELD_SELECTION;
1067
- }
1068
- function serializeObjectFieldNodeUnderRecord(node) {
1069
- const { luvioSelections, arguments: nodeArgs, name: nodeName } = node;
1070
- const fields = {};
1071
- let result = ``;
1072
- if (luvioSelections === undefined) {
1073
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1074
- throw new Error('selection should not be empty for ObjectFieldNodeUnderRecord');
1075
- }
1076
- const luvioSelectionsLength = luvioSelections.length;
1077
- for (let i = 0; i < luvioSelectionsLength; i++) {
1078
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
1079
- const { name } = sel;
1080
- if (sel.kind !== 'ScalarFieldSelection') {
1081
- if (process.env.NODE_ENV !== 'production') {
1082
- throw new Error(`Invalid selection for ${nodeName}. ${nodeName} appears to be a Record, but is missing @resource(type: "Record")`);
1083
- }
1084
- }
1085
- if (RECORD_DEFAULT_FIELD_VALUES.indexOf(name) === -1) {
1086
- if (process.env.NODE_ENV !== 'production') {
1087
- throw new Error(`Invalid selection for "${nodeName}.${name}". Only ${RECORD_DEFAULT_FIELD_VALUES.join(', ')} are supported. If "${nodeName}" is a spanning Record, please include @resource(type: "Record") directive.`);
1088
- }
1089
- }
1090
- fields[name] = true;
1091
- result = `${result}${serializeScalarFieldNode(sel)}`;
1092
- }
1093
- result = appendRecordDefaultFieldValues(result, fields);
1094
- const args = nodeArgs === undefined ? '' : `(${serializeArguments(nodeArgs)})`;
1095
- return `${serializeFieldNodeName(node)}${args} { ${TYPENAME_FIELD} ${result} }`;
1096
- }
1097
- function appendRecordDefaultFieldValues(fieldValues, fieldValuesMap) {
1098
- let str = fieldValues;
1099
- for (let i = 0, len = RECORD_DEFAULT_FIELD_VALUES.length; i < len; i++) {
1100
- const defaultField = RECORD_DEFAULT_FIELD_VALUES[i];
1101
- if (fieldValuesMap[defaultField] !== true) {
1102
- str = `${str}${defaultField}, `;
1103
- }
1104
- }
1105
- return str;
1106
- }
1107
- function appendSpanningRecordIds(luvioSelections) {
1108
- if (luvioSelections === undefined) {
1109
- return undefined;
1110
- }
1111
- //add record ref ids
1112
- let spanningRecordIdFields = [];
1113
- let selections = luvioSelections;
1114
- //Find all fields with a record type declaration and add the corresponding
1115
- //reference ID.
1116
- // TODO [W-11342283]: This approach uses a naming pattern that is brittle and not
1117
- // guaranteed to work in the long run. A more correct approach is to thread through
1118
- // ObjectInfo schemas and use its mapping definitions.
1119
- for (let i = 0; i < selections.length; i++) {
1120
- const selection = selections[i];
1121
- if (selection.kind === 'CustomFieldSelection' && selection.type === 'Record') {
1122
- const customFieldMatches = selection.name.match(/(.*__)r$/);
1123
- if (customFieldMatches) {
1124
- // For `FSL__Related_Service__r {...}`, inject `FSL__Related_Service__c { value } as a peer field`
1125
- const [, captureGroup] = customFieldMatches;
1126
- spanningRecordIdFields.push(`${captureGroup}c`);
1127
- }
1128
- else {
1129
- // For `Owner {...}`, inject `OwnerId { value } as a peer field`
1130
- spanningRecordIdFields.push(`${selection.name}Id`);
1131
- }
1132
- }
1133
- }
1134
- //Add all missing reference IDs to the set of selections
1135
- for (let i = 0; i < spanningRecordIdFields.length; i++) {
1136
- const idField = spanningRecordIdFields[i];
1137
- if (selections.findIndex((e) => e.kind === 'ObjectFieldSelection' && e.name === idField) >
1138
- -1) {
1139
- continue;
1140
- }
1141
- selections.push({
1142
- kind: 'ObjectFieldSelection',
1143
- name: idField,
1144
- luvioSelections: [{ kind: 'ScalarFieldSelection', name: 'value' }],
1145
- });
1146
- }
1147
- return selections;
1148
- }
1149
- function serializeCustomFieldRecord(def, state) {
1150
- const { luvioSelections } = def;
1151
- if (state.fragments[defaultRecordFieldsFragmentName] === undefined) {
1152
- state.fragments[defaultRecordFieldsFragmentName] = defaultRecordFieldsFragment;
1153
- }
1154
- const selections = appendSpanningRecordIds(luvioSelections);
1155
- return `${serializeFieldNodeName(def)} { ${serializeRecordSelections(selections, state)} ...${defaultRecordFieldsFragmentName} }`;
1156
- }
1157
- function serializeArguments(argDefinitions) {
1158
- if (argDefinitions === undefined) {
1159
- return '';
1160
- }
1161
- let str = '';
1162
- for (let i = 0, len = argDefinitions.length; i < len; i += 1) {
1163
- let def = serializeArgument(argDefinitions[i]);
1164
- if (i !== 0) {
1165
- def = ` ${def}`;
1166
- }
1167
- str = `${str}${def}`;
1168
- }
1169
- return str;
1170
- }
1171
- function serializeArgument(argDefinition) {
1172
- const { name, value } = argDefinition;
1173
- return `${name}: ${serializeValueNode(value)}`;
1174
- }
1175
-
1176
- function serializeValueNode(valueDefinition) {
1177
- const { kind } = valueDefinition;
1178
- switch (kind) {
1179
- case 'ObjectValue':
1180
- return serializeObjectValueNode(valueDefinition);
1181
- case 'StringValue':
1182
- return serializeStringValueNode(valueDefinition);
1183
- case 'NullValue':
1184
- return 'null';
1185
- case 'FloatValue':
1186
- case 'IntValue':
1187
- case 'BooleanValue':
1188
- case 'EnumValue':
1189
- return valueDefinition.value;
1190
- case 'Variable':
1191
- return serializeVariableNode(valueDefinition);
1192
- case 'ListValue':
1193
- return serializeListValueNode(valueDefinition);
1194
- }
1195
- if (process.env.NODE_ENV !== 'production') {
1196
- throw new Error(`Unable to serialize graphql query, unsupported value node "${kind}"`);
1197
- }
1198
- }
1199
- function serializeVariableNode(variableNode) {
1200
- return `$${variableNode.name}`;
1201
- }
1202
- function serializeListValueNode(listNode) {
1203
- const { values } = listNode;
1204
- if (values.length === 0) {
1205
- return '';
1206
- }
1207
- let str = '';
1208
- for (let i = 0, len = values.length; i < len; i += 1) {
1209
- str = `${str}${serializeValueNode(values[i])}, `;
1210
- }
1211
- return `[${str.substring(0, str.length - 2)}]`;
1212
- }
1213
- function serializeStringValueNode(literalValueNode) {
1214
- return `"${literalValueNode.value}"`;
1215
- }
1216
- function serializeObjectValueNode(objectValueDefinition) {
1217
- const { fields } = objectValueDefinition;
1218
- let str = [];
1219
- const fieldKeys = keys(fields);
1220
- for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
1221
- const fieldKey = fieldKeys[i];
1222
- str.push(`${fieldKey}: ${serializeValueNode(fields[fieldKey])}`);
1223
- }
1224
- return `{ ${str.join(', ')} }`;
1225
- }
1226
- function serializeVariableDefinitions(definitons) {
1227
- if (definitons === undefined || definitons.length === 0) {
1228
- return '';
1229
- }
1230
- let str = '';
1231
- for (let i = 0, len = definitons.length; i < len; i += 1) {
1232
- const def = serializeVariableDefinitionNode(definitons[i]);
1233
- str = `${str}${def}, `;
1234
- }
1235
- return ` (${str.substring(0, str.length - 2)})`;
1236
- }
1237
- function serializeVariableDefinitionNode(def) {
1238
- const { variable, type, defaultValue } = def;
1239
- return defaultValue === undefined
1240
- ? `$${variable.name}: ${serializeTypeNode(type)}`
1241
- : `$${variable.name}: ${serializeTypeNode(type)} = ${serializeValueNode(defaultValue)}`;
1242
- }
1243
- function serializeTypeNode(type) {
1244
- const { kind } = type;
1245
- switch (kind) {
1246
- case 'NamedType':
1247
- return serializeNamedTypeNode(type);
1248
- case 'ListType':
1249
- return serializeListTypeNode(type);
1250
- }
1251
- if (process.env.NODE_ENV !== 'production') {
1252
- throw new Error(`Unable to serialize graphql query, unsupported variable definition type node "${type.kind}"`);
1253
- }
1254
- return '';
1255
- }
1256
- function serializeNamedTypeNode(type) {
1257
- return type.name;
1258
- }
1259
- function serializeListTypeNode(type) {
1260
- return `[${serializeTypeNode(type.type)}]`;
1261
- }
1262
- function serializeOperationNode(def, state) {
1263
- const { kind } = def;
1264
- switch (kind) {
1265
- case 'OperationDefinition':
1266
- return serializeOperationDefinition(def, state);
1267
- }
1268
- if (process.env.NODE_ENV !== 'production') {
1269
- throw new Error(`Unable to serialize graphql query, unsupported OperationDefinition type "${kind}"`);
1270
- }
1271
- }
1272
- function serializeOperationDefinition(def, state) {
1273
- const { operation, luvioSelections, name, variableDefinitions } = def;
1274
- const nameStr = name === undefined ? ' ' : ` ${name} `;
1275
- return `${operation}${nameStr}${serializeVariableDefinitions(variableDefinitions)}{ ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1276
- }
1277
- function applyFragments(str, fragments) {
1278
- let appliedString = str;
1279
- const fragmentNames = Object.keys(fragments);
1280
- for (let i = 0, len = fragmentNames.length; i < len; i += 1) {
1281
- const name = fragmentNames[i];
1282
- appliedString = `${appliedString} ${fragments[name]}`;
1283
- }
1284
- return appliedString;
1285
- }
1286
- function astToString(ast) {
1287
- const { definitions } = ast;
1288
- const state = {
1289
- fragments: {},
1290
- };
1291
- let str = '';
1292
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1293
- const def = serializeOperationNode(definitions[i], state);
1294
- str = `${str}${def}`;
1295
- }
1296
- return applyFragments(str, state.fragments);
1297
- }
1298
-
1299
- function isGraphQLVariables(unknown) {
1300
- return untrustedIsObject(unknown);
1301
- }
1302
- function validateVariableDefinitions(definitons, variables) {
1303
- const errors = [];
1304
- for (let i = 0, len = definitons.length; i < len; i += 1) {
1305
- const { variable, type, defaultValue } = definitons[i];
1306
- const value = getVariableValue(variable.name, variables, defaultValue);
1307
- if (value === undefined) {
1308
- errors.push(`Variable $${variable.name} has an undefined value provided for it.`);
1309
- }
1310
- if (type.kind === 'NonNullType' && value === null) {
1311
- errors.push(`Expected a non-null value to be provided as value for $${variable.name}`);
1312
- }
1313
- if (type.kind === 'ListType' && value !== null && !Array.isArray(value)) {
1314
- errors.push(`Expected a list to be provided as value for $${variable.name}`);
1315
- }
1316
- }
1317
- return errors;
1318
- }
1319
- function getVariableValue(name, variables, defaultValue) {
1320
- if (name in variables) {
1321
- return variables[name];
1322
- }
1323
- if (defaultValue === undefined) {
1324
- return null;
1325
- }
1326
- return defaultValue;
1327
- }
1328
-
1329
- function validate$1(ast, variables) {
1330
- const { variableDefinitions } = ast;
1331
- const errors = [];
1332
- if (variableDefinitions !== undefined) {
1333
- errors.push(...validateVariableDefinitions(variableDefinitions, variables));
1334
- }
1335
- return errors;
16
+ function untrustedIsObject(untrusted) {
17
+ return typeof untrusted === 'object' && untrusted !== null && isArray(untrusted) === false;
1336
18
  }
1337
-
1338
19
  function isLuvioDocumentNode(unknown) {
1339
20
  if (untrustedIsObject(unknown) === true &&
1340
21
  hasOwnProperty.call(unknown, 'kind') === true &&
@@ -1344,737 +25,6 @@ function isLuvioDocumentNode(unknown) {
1344
25
  }
1345
26
  return false;
1346
27
  }
1347
- const createRead = (luvio, ast, variables) => {
1348
- const definitions = ast.definitions === undefined ? [] : ast.definitions;
1349
- return (source, builder) => {
1350
- builder.enterPath('data');
1351
- let sink = {};
1352
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1353
- const def = definitions[i];
1354
- if (def.kind !== 'OperationDefinition') {
1355
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1356
- throw new Error(`Unsupported document definition "${def.kind}"`);
1357
- }
1358
- const data = createRead$1(luvio, def, variables)(source, builder);
1359
- sink = {
1360
- ...sink,
1361
- ...data,
1362
- };
1363
- }
1364
- const gqlData = {};
1365
- builder.assignNonScalar(gqlData, 'data', sink);
1366
- builder.exitPath();
1367
- builder.enterPath('errors');
1368
- builder.assignNonScalar(gqlData, 'errors', []);
1369
- builder.exitPath();
1370
- return gqlData;
1371
- };
1372
- };
1373
- function createIngest(ast, variables) {
1374
- const definitions = ast.definitions === undefined ? [] : ast.definitions;
1375
- return (data, path, luvio, store, timestamp) => {
1376
- const key = path.fullPath;
1377
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1378
- const def = definitions[i];
1379
- if (def.kind !== 'OperationDefinition') {
1380
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1381
- throw new Error(`Unsupported document definition "${def.kind}"`);
1382
- }
1383
- createIngest$2(def, variables)(data, {
1384
- parent: null,
1385
- fullPath: key,
1386
- propertyName: null,
1387
- }, luvio, store, timestamp);
1388
- }
1389
- return {
1390
- __ref: key,
1391
- };
1392
- };
1393
- }
1394
- function validate(ast, variables) {
1395
- const errors = [];
1396
- const { definitions } = ast;
1397
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1398
- const def = definitions[i];
1399
- if (def.kind !== 'OperationDefinition') {
1400
- errors.push(`Unsupported document definition "${def.kind}"`);
1401
- }
1402
- else {
1403
- errors.push(...validate$1(def, variables));
1404
- }
1405
- }
1406
- return errors;
1407
- }
1408
-
1409
- let storeEval = undefined;
1410
- let draftFunctions = undefined;
1411
- const configuration = {
1412
- setStoreEval: function (storeEvalArg) {
1413
- storeEval = storeEvalArg;
1414
- },
1415
- setDraftFunctions: function (draftFuncs) {
1416
- draftFunctions = draftFuncs;
1417
- },
1418
- };
1419
-
1420
- const assignedToMe = {
1421
- kind: 'CustomFieldSelection',
1422
- name: 'ServiceResources',
1423
- type: 'Connection',
1424
- luvioSelections: [
1425
- {
1426
- kind: 'ObjectFieldSelection',
1427
- name: 'edges',
1428
- luvioSelections: [
1429
- {
1430
- kind: 'CustomFieldSelection',
1431
- name: 'node',
1432
- type: 'Record',
1433
- luvioSelections: [
1434
- {
1435
- kind: 'ObjectFieldSelection',
1436
- name: 'ServiceResourceId',
1437
- luvioSelections: [
1438
- {
1439
- kind: 'ScalarFieldSelection',
1440
- name: 'value',
1441
- },
1442
- ],
1443
- },
1444
- {
1445
- kind: 'ObjectFieldSelection',
1446
- name: 'ServiceAppointmentId',
1447
- luvioSelections: [
1448
- {
1449
- kind: 'ScalarFieldSelection',
1450
- name: 'value',
1451
- },
1452
- ],
1453
- },
1454
- {
1455
- kind: 'CustomFieldSelection',
1456
- name: 'ServiceResource',
1457
- type: 'Record',
1458
- luvioSelections: [
1459
- {
1460
- kind: 'ScalarFieldSelection',
1461
- name: 'Id',
1462
- },
1463
- {
1464
- kind: 'ObjectFieldSelection',
1465
- name: 'RelatedRecordId',
1466
- luvioSelections: [
1467
- {
1468
- kind: 'ScalarFieldSelection',
1469
- name: 'value',
1470
- },
1471
- ],
1472
- },
1473
- ],
1474
- },
1475
- ],
1476
- },
1477
- ],
1478
- },
1479
- ],
1480
- };
1481
- function shouldInjectFields(ast) {
1482
- let injectScope = false;
1483
- const recordNodes = findRecordSelections(ast);
1484
- if (recordNodes !== undefined && recordNodes.length > 0) {
1485
- for (const recordNode of recordNodes) {
1486
- if (recordNode.arguments !== undefined) {
1487
- for (const argument of recordNode.arguments) {
1488
- if (argument.name === 'scope' &&
1489
- argument.value.kind === 'EnumValue' &&
1490
- argument.value.value === 'ASSIGNEDTOME') {
1491
- injectScope = true;
1492
- break;
1493
- }
1494
- }
1495
- }
1496
- }
1497
- }
1498
- return injectScope;
1499
- }
1500
- function injectFieldsGQL(ast) {
1501
- return injectScopeFields(ast);
1502
- }
1503
- function swapIdsOfDocumentNode(documentnode, draftFunctions) {
1504
- const recordNodes = findRecordSelections(documentnode);
1505
- recordNodes.forEach((recordConnection) => {
1506
- swapIdsOfFieldNode(recordConnection, draftFunctions);
1507
- });
1508
- return documentnode;
1509
- }
1510
- function swapIdsOfFieldNode(selectionNode, draftFunctions) {
1511
- if (isCustomFieldNode(selectionNode) &&
1512
- selectionNode.type === 'Connection' &&
1513
- selectionNode.arguments !== undefined &&
1514
- selectionNode.arguments.some((argment) => argment.name === 'where')) {
1515
- const swappedArguments = selectionNode.arguments.map((argument) => {
1516
- if (argument.name === 'where') {
1517
- return {
1518
- ...argument,
1519
- value: swapIdsOfValueNode(argument.value, draftFunctions.isDraftId, draftFunctions.getCanonicalId),
1520
- };
1521
- }
1522
- else {
1523
- return argument;
1524
- }
1525
- });
1526
- selectionNode.arguments = swappedArguments;
1527
- }
1528
- if (selectionNode.luvioSelections !== undefined) {
1529
- for (const childSelectionNode of selectionNode.luvioSelections) {
1530
- if (isCustomFieldNode(childSelectionNode) ||
1531
- isObjectFieldSelection(childSelectionNode)) {
1532
- swapIdsOfFieldNode(childSelectionNode, draftFunctions);
1533
- }
1534
- }
1535
- }
1536
- }
1537
- function swapIdsOfValueNode(valueNode, isDraftId, idMapper) {
1538
- switch (valueNode.kind) {
1539
- case Kind.OBJECT: {
1540
- const swappedObjectValueNode = {};
1541
- for (const key of keys(valueNode.fields)) {
1542
- swappedObjectValueNode[key] = swapIdsOfValueNode(valueNode.fields[key], isDraftId, idMapper);
1543
- }
1544
- return {
1545
- kind: 'ObjectValue',
1546
- fields: swappedObjectValueNode,
1547
- };
1548
- }
1549
- case Kind.LIST: {
1550
- const listValueNodes = [];
1551
- for (const child of valueNode.values) {
1552
- listValueNodes.push(swapIdsOfValueNode(child, isDraftId, idMapper));
1553
- }
1554
- return {
1555
- kind: 'ListValue',
1556
- values: listValueNodes,
1557
- };
1558
- }
1559
- case Kind.STRING: {
1560
- if (!isDraftId(valueNode.value)) {
1561
- return valueNode;
1562
- }
1563
- return {
1564
- kind: 'StringValue',
1565
- value: idMapper(valueNode.value),
1566
- block: false,
1567
- };
1568
- }
1569
- default:
1570
- return {
1571
- ...valueNode,
1572
- };
1573
- }
1574
- }
1575
- function injectScopeFields(ast) {
1576
- const modifiedDocumentNode = {
1577
- kind: 'Document',
1578
- definitions: [
1579
- {
1580
- kind: 'OperationDefinition',
1581
- operation: 'query',
1582
- luvioSelections: [
1583
- {
1584
- kind: 'ObjectFieldSelection',
1585
- name: 'uiapi',
1586
- luvioSelections: [
1587
- {
1588
- kind: 'ObjectFieldSelection',
1589
- name: 'query',
1590
- luvioSelections: [],
1591
- },
1592
- ],
1593
- },
1594
- ],
1595
- },
1596
- ],
1597
- };
1598
- const modifiedSelections = [];
1599
- const recordNodes = findRecordSelections(ast);
1600
- if (recordNodes !== undefined && recordNodes.length > 0) {
1601
- // each record node represent a connection
1602
- for (const recordNode of recordNodes) {
1603
- modifiedSelections.push(injectConnectionForScope(recordNode));
1604
- }
1605
- }
1606
- const queryNode = modifiedDocumentNode.definitions
1607
- .filter(isOperationDefinition)
1608
- .reduce(flatMap(luvioSelections), [])
1609
- .filter(isObjectFieldSelection)
1610
- .filter(named('uiapi'))
1611
- .reduce(flatMap(luvioSelections), [])
1612
- .filter(isObjectFieldSelection)
1613
- .filter(named('query'))[0];
1614
- queryNode.luvioSelections.push(...modifiedSelections);
1615
- return ast;
1616
- }
1617
- function injectConnectionForScope(connectionNode) {
1618
- if (connectionNode.name === 'ServiceAppointment') {
1619
- if (connectionNode.arguments !== undefined) {
1620
- for (const argument of connectionNode.arguments) {
1621
- if (argument.name === 'scope' &&
1622
- argument.value.kind === 'EnumValue' &&
1623
- argument.value.value === 'ASSIGNEDTOME') {
1624
- const injectedConnctionNode = {
1625
- ...connectionNode,
1626
- };
1627
- if (injectedConnctionNode.luvioSelections !== undefined) {
1628
- const injectedNodes = injectedConnctionNode.luvioSelections
1629
- .filter(isObjectFieldSelection)
1630
- .filter(named('edges'))
1631
- .reduce(flatMap(luvioSelections), [])
1632
- .filter(isCustomFieldNode)
1633
- .filter(named('node'));
1634
- if (injectedNodes !== undefined && injectedNodes.length > 0) {
1635
- const injectedNode = injectedNodes[0];
1636
- if (injectedNode.luvioSelections !== undefined) {
1637
- injectedNode.luvioSelections = mergeSelectionNodes(injectedNode.luvioSelections, [assignedToMe]);
1638
- }
1639
- }
1640
- }
1641
- return injectedConnctionNode;
1642
- }
1643
- }
1644
- }
1645
- }
1646
- return { ...connectionNode };
1647
- }
1648
- function mergeSelectionNodes(group1, group2) {
1649
- let sameFields1 = [];
1650
- let sameFields2 = [];
1651
- let results = [];
1652
- for (const node2 of group2) {
1653
- if (isCustomFieldNode(node2)) {
1654
- const nodes1SameLevel = group1
1655
- .filter(isCustomFieldNode)
1656
- .filter((node1) => node1.name === node2.name && node1.type === node2.type);
1657
- if (nodes1SameLevel.length > 0) {
1658
- sameFields1.push(...nodes1SameLevel);
1659
- sameFields2.push(node2);
1660
- const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), node2);
1661
- results.push(mergedNode);
1662
- }
1663
- }
1664
- else if (isObjectFieldSelection(node2)) {
1665
- const nodes1SameLevel = group1
1666
- .filter(isObjectFieldSelection)
1667
- .filter((node1) => node1.name === node2.name);
1668
- if (nodes1SameLevel.length > 0) {
1669
- sameFields1.push(...nodes1SameLevel);
1670
- sameFields2.push(node2);
1671
- const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), node2);
1672
- results.push(mergedNode);
1673
- }
1674
- }
1675
- }
1676
- if (sameFields1.length > 0) {
1677
- const differentNodes1 = group1.filter((node) => !sameFields1.includes(node));
1678
- results.push(...differentNodes1);
1679
- const differentNodes2 = group2.filter((node) => !sameFields2.includes(node));
1680
- results.push(...differentNodes2);
1681
- }
1682
- else {
1683
- return group1.concat(group2);
1684
- }
1685
- return results;
1686
- }
1687
- function mergeCustomFieldNodes(node1, node2) {
1688
- let result = node1;
1689
- if (node1.name === node2.name && node1.kind === node2.kind && node1.type === node2.type) {
1690
- result = {
1691
- kind: node1.kind,
1692
- name: node1.name,
1693
- type: node1.type,
1694
- luvioSelections: [],
1695
- };
1696
- let selections = [];
1697
- let sameCustomFields1 = [];
1698
- let sameCustomFields2 = [];
1699
- let sameObjectFields1 = [];
1700
- let sameObjectFields2 = [];
1701
- let sameScalarFields1 = [];
1702
- let sameScalarFields2 = [];
1703
- if (node1.luvioSelections && node2.luvioSelections) {
1704
- sameCustomFields1 = node1.luvioSelections
1705
- .filter(isCustomFieldNode)
1706
- .filter((childNode1) => {
1707
- if (node2.luvioSelections) {
1708
- const sames = node2.luvioSelections
1709
- .filter(isCustomFieldNode)
1710
- .filter((childNode2) => childNode2.name === childNode1.name);
1711
- if (sames.length > 0) {
1712
- const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1713
- selections.push(mergedNode);
1714
- result = {
1715
- ...result,
1716
- luvioSelections: selections,
1717
- };
1718
- sameCustomFields2.push(...sames);
1719
- return true;
1720
- }
1721
- }
1722
- return false;
1723
- });
1724
- sameObjectFields1 = node1.luvioSelections
1725
- .filter(isObjectFieldSelection)
1726
- .filter((childNode1) => {
1727
- if (node2.luvioSelections) {
1728
- const sames = node2.luvioSelections
1729
- .filter(isObjectFieldSelection)
1730
- .filter((childNode2) => childNode2.name === childNode1.name);
1731
- if (sames.length > 0) {
1732
- const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1733
- selections.push(mergedNode);
1734
- result = {
1735
- ...result,
1736
- luvioSelections: selections,
1737
- };
1738
- sameObjectFields2.push(...sames);
1739
- return true;
1740
- }
1741
- }
1742
- return false;
1743
- });
1744
- sameScalarFields1 = node1.luvioSelections
1745
- .filter(isScalarFieldNode)
1746
- .filter((childNode1) => {
1747
- if (node2.luvioSelections) {
1748
- const sames = node2.luvioSelections
1749
- .filter(isScalarFieldNode)
1750
- .filter((childNode2) => childNode2.name === childNode1.name);
1751
- if (sames.length > 0) {
1752
- const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1753
- selections.push(mergedNode);
1754
- result = {
1755
- ...result,
1756
- luvioSelections: selections,
1757
- };
1758
- sameScalarFields2.push(...sames);
1759
- return true;
1760
- }
1761
- }
1762
- return false;
1763
- });
1764
- if (sameCustomFields1.length > 0 ||
1765
- sameObjectFields1.length > 0 ||
1766
- sameScalarFields1.length > 0) {
1767
- const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1768
- !sameObjectFields1.includes(node) &&
1769
- !sameScalarFields1.includes(node));
1770
- selections.push(...diffNodes1);
1771
- const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1772
- !sameObjectFields2.includes(node) &&
1773
- !sameScalarFields2.includes(node));
1774
- selections.push(...diffNodes2);
1775
- result = {
1776
- ...result,
1777
- luvioSelections: selections,
1778
- };
1779
- }
1780
- else {
1781
- selections.push(...node1.luvioSelections);
1782
- selections.push(...node2.luvioSelections);
1783
- result = {
1784
- ...result,
1785
- luvioSelections: selections,
1786
- };
1787
- }
1788
- }
1789
- else {
1790
- if (node1.luvioSelections) {
1791
- return node1;
1792
- }
1793
- if (node2.luvioSelections) {
1794
- return node2;
1795
- }
1796
- }
1797
- return result;
1798
- }
1799
- else {
1800
- // eslint-disable-next-line
1801
- throw new Error('The fields name needs to be same to be merged');
1802
- }
1803
- }
1804
- function mergeObjectFieldNodes(node1, node2) {
1805
- let result = node1;
1806
- if (node1.name === node2.name && node1.kind === node2.kind) {
1807
- result = {
1808
- kind: node1.kind,
1809
- name: node1.name,
1810
- directives: node1.directives,
1811
- luvioSelections: [],
1812
- };
1813
- let selections = [];
1814
- let sameCustomFields1 = [];
1815
- let sameCustomFields2 = [];
1816
- let sameObjectFields1 = [];
1817
- let sameObjectFields2 = [];
1818
- let sameScalarFields1 = [];
1819
- let sameScalarFields2 = [];
1820
- if (node1.luvioSelections && node2.luvioSelections) {
1821
- sameCustomFields1 = node1.luvioSelections
1822
- .filter(isCustomFieldNode)
1823
- .filter((childNode1) => {
1824
- if (node2.luvioSelections) {
1825
- const sames = node2.luvioSelections
1826
- .filter(isCustomFieldNode)
1827
- .filter((childNode2) => childNode2.name === childNode1.name);
1828
- if (sames.length > 0) {
1829
- const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1830
- selections.push(mergedNode);
1831
- result = {
1832
- ...result,
1833
- luvioSelections: selections,
1834
- };
1835
- sameCustomFields2.push(...sames);
1836
- return true;
1837
- }
1838
- }
1839
- return false;
1840
- });
1841
- sameObjectFields1 = node1.luvioSelections
1842
- .filter(isObjectFieldSelection)
1843
- .filter((childNode1) => {
1844
- if (node2.luvioSelections) {
1845
- const sames = node2.luvioSelections
1846
- .filter(isObjectFieldSelection)
1847
- .filter((childNode2) => childNode2.name === childNode1.name);
1848
- if (sames.length > 0) {
1849
- const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1850
- selections.push(mergedNode);
1851
- result = {
1852
- ...result,
1853
- luvioSelections: selections,
1854
- };
1855
- sameObjectFields2.push(...sames);
1856
- return true;
1857
- }
1858
- }
1859
- return false;
1860
- });
1861
- sameScalarFields1 = node1.luvioSelections
1862
- .filter(isScalarFieldNode)
1863
- .filter((childNode1) => {
1864
- if (node2.luvioSelections) {
1865
- const sames = node2.luvioSelections
1866
- .filter(isScalarFieldNode)
1867
- .filter((childNode2) => childNode2.name === childNode1.name);
1868
- if (sames.length > 0) {
1869
- const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1870
- selections.push(mergedNode);
1871
- result = {
1872
- ...result,
1873
- luvioSelections: selections,
1874
- };
1875
- sameScalarFields2.push(...sames);
1876
- return true;
1877
- }
1878
- }
1879
- return false;
1880
- });
1881
- if (sameCustomFields1.length > 0 ||
1882
- sameObjectFields1.length > 0 ||
1883
- sameScalarFields1.length > 0) {
1884
- const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1885
- !sameObjectFields1.includes(node) &&
1886
- !sameScalarFields1.includes(node));
1887
- selections.push(...diffNodes1);
1888
- const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1889
- !sameObjectFields2.includes(node) &&
1890
- !sameScalarFields2.includes(node));
1891
- selections.push(...diffNodes2);
1892
- result = {
1893
- ...result,
1894
- luvioSelections: selections,
1895
- };
1896
- }
1897
- else {
1898
- selections.push(...node1.luvioSelections);
1899
- selections.push(...node2.luvioSelections);
1900
- result = {
1901
- ...result,
1902
- luvioSelections: selections,
1903
- };
1904
- }
1905
- }
1906
- else {
1907
- if (node1.luvioSelections) {
1908
- return node1;
1909
- }
1910
- if (node2.luvioSelections) {
1911
- return node2;
1912
- }
1913
- }
1914
- return result;
1915
- }
1916
- else {
1917
- // eslint-disable-next-line
1918
- throw new Error('The fields name needs to be same to be merged');
1919
- }
1920
- }
1921
- function mergeScalarFieldNode(node1, node2) {
1922
- if (node1.kind === node1.kind && node1.name === node2.name) {
1923
- return { ...node1 };
1924
- }
1925
- // eslint-disable-next-line
1926
- throw new Error('The fields name needs to be same to be merged');
1927
- }
1928
- function findRecordSelections(document) {
1929
- return document.definitions
1930
- .filter(isOperationDefinition)
1931
- .reduce(flatMap(luvioSelections), [])
1932
- .filter(isObjectFieldSelection)
1933
- .filter(named('uiapi'))
1934
- .reduce(flatMap(luvioSelections), [])
1935
- .filter(isObjectFieldSelection)
1936
- .filter(named('query'))
1937
- .reduce(flatMap(luvioSelections), [])
1938
- .filter(isCustomFieldNode);
1939
- }
1940
- function isOperationDefinition(node) {
1941
- return node.kind === 'OperationDefinition';
1942
- }
1943
- function isObjectFieldSelection(node) {
1944
- return node !== undefined && node.kind === 'ObjectFieldSelection';
1945
- }
1946
- function isCustomFieldNode(node) {
1947
- return node !== undefined && node.kind === 'CustomFieldSelection';
1948
- }
1949
- function isScalarFieldNode(node) {
1950
- return node !== undefined && node.kind === 'ScalarFieldSelection';
1951
- }
1952
- function flatMap(transform) {
1953
- return (acc, current) => {
1954
- const mapped = transform(current);
1955
- return acc.concat(mapped);
1956
- };
1957
- }
1958
- function luvioSelections(node) {
1959
- return node.luvioSelections === undefined ? [] : node.luvioSelections;
1960
- }
1961
- function named(name) {
1962
- return (node) => node.name === name;
1963
- }
1964
-
1965
- const adapterName = 'graphQL';
1966
- const RECORD_REPRESENTATION_NAME = 'RecordRepresentation';
1967
- const GRAPHQL_ROOT_KEY = `${namespace}::${representationName}`;
1968
- function buildSnapshotRefresh(luvio, config, fragment) {
1969
- return {
1970
- config,
1971
- resolve: () => buildNetworkSnapshot(luvio, config, fragment),
1972
- };
1973
- }
1974
- function createFragment(luvio, query, variables) {
1975
- return {
1976
- kind: 'Fragment',
1977
- synthetic: false,
1978
- reader: true,
1979
- version: GRAPHQL_INGEST_VERSION,
1980
- read: createRead(luvio, query, variables),
1981
- };
1982
- }
1983
- function onFetchResponseSuccess(luvio, config, response, fragment) {
1984
- const { query, variables } = config;
1985
- const { body } = response;
1986
- if (body.errors && body.errors.length > 0) {
1987
- return Promise.resolve(luvio.storeLookup({
1988
- recordId: representationName,
1989
- node: {
1990
- kind: 'Fragment',
1991
- synthetic: true,
1992
- reader: true,
1993
- read: (reader) => {
1994
- const sink = {};
1995
- reader.enterPath('data');
1996
- reader.assignNonScalar(sink, 'data', body.data);
1997
- reader.exitPath();
1998
- reader.enterPath('errors');
1999
- deepFreeze(body.errors);
2000
- reader.assignNonScalar(sink, 'errors', body.errors);
2001
- reader.exitPath();
2002
- return sink;
2003
- },
2004
- },
2005
- variables: {},
2006
- }));
2007
- }
2008
- const ingest = createIngest(query, variables);
2009
- luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, body.data);
2010
- const snapshot = luvio.storeLookup({
2011
- recordId: GRAPHQL_ROOT_KEY,
2012
- node: fragment,
2013
- variables: {},
2014
- }, buildSnapshotRefresh(luvio, config, fragment));
2015
- return luvio.storeBroadcast().then(() => snapshot);
2016
- }
2017
- function getResponseCacheKeys(luvio, config, response, fragment) {
2018
- // TODO [W-10147827]: make this more efficient
2019
- // for now we will get the cache keys by actually ingesting then looking at
2020
- // the seenRecords + recordId
2021
- const { query, variables } = config;
2022
- const { body } = response;
2023
- if (body.errors && body.errors.length > 0) {
2024
- return new StoreKeyMap();
2025
- }
2026
- const ingest = createIngest(query, variables);
2027
- // ingest mutates the response so we have to make a copy
2028
- const dataCopy = parse(stringify(body.data));
2029
- luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, dataCopy);
2030
- const snapshot = luvio.storeLookup({
2031
- recordId: GRAPHQL_ROOT_KEY,
2032
- node: fragment,
2033
- variables: {},
2034
- }, buildSnapshotRefresh(luvio, config, fragment));
2035
- if (snapshot.state === 'Error') {
2036
- return new StoreKeyMap();
2037
- }
2038
- const keys = [...snapshot.seenRecords.keysAsArray(), snapshot.recordId];
2039
- const keySet = new StoreKeyMap();
2040
- for (let i = 0, len = keys.length; i < len; i++) {
2041
- const key = keys[i];
2042
- const keyNamespace = key.split('::')[0];
2043
- const representationName = key.split('::')[1].split(':')[0];
2044
- keySet.set(key, {
2045
- namespace: keyNamespace,
2046
- representationName,
2047
- mergeable: keyNamespace === namespace || representationName === RECORD_REPRESENTATION_NAME,
2048
- });
2049
- }
2050
- return keySet;
2051
- }
2052
- function onFetchResponseError(luvio, config, response) {
2053
- const errorSnapshot = luvio.errorSnapshot(response);
2054
- luvio.storeIngestError(GRAPHQL_ROOT_KEY, errorSnapshot);
2055
- return luvio.storeBroadcast().then(() => errorSnapshot);
2056
- }
2057
- function buildNetworkSnapshot(luvio, config, fragment, options) {
2058
- const { variables: queryVariables, query } = config;
2059
- const request = {
2060
- baseUri: '/services/data/v63.0',
2061
- basePath: '/graphql',
2062
- method: 'post',
2063
- priority: 'normal',
2064
- body: {
2065
- query: astToString(query),
2066
- variables: queryVariables,
2067
- },
2068
- queryParams: {},
2069
- urlParams: {},
2070
- headers: {},
2071
- };
2072
- return luvio.dispatchResourceRequest(request, options).then((resp) => {
2073
- return luvio.handleSuccessResponse(() => onFetchResponseSuccess(luvio, config, resp, fragment), () => getResponseCacheKeys(luvio, config, resp, fragment));
2074
- }, (errorResponse) => {
2075
- return luvio.handleErrorResponse(() => onFetchResponseError(luvio, config, errorResponse));
2076
- });
2077
- }
2078
28
  function validateGraphQlConfig(untrustedConfig) {
2079
29
  if (!untrustedIsObject(untrustedConfig)) {
2080
30
  return {
@@ -2095,8 +45,7 @@ function validateGraphQlConfig(untrustedConfig) {
2095
45
  if (isLuvioDocumentNode(query) === false) {
2096
46
  validationErrors.push('The config parameter "query" isn\'t a valid LuvioDocumentNode');
2097
47
  }
2098
- const ast = query;
2099
- if (isGraphQLVariables(variables) === false) {
48
+ if (untrustedIsObject(variables) === false) {
2100
49
  validationErrors.push('The config parameter "variables" isn\'t an object');
2101
50
  }
2102
51
  if (validationErrors.length > 0) {
@@ -2105,83 +54,14 @@ function validateGraphQlConfig(untrustedConfig) {
2105
54
  errors: validationErrors,
2106
55
  };
2107
56
  }
2108
- validationErrors.push(...validate(ast, variables));
2109
- const { useUiApiAdapter } = untrustedConfig;
2110
- if (useUiApiAdapter !== undefined && typeof useUiApiAdapter !== 'boolean') {
2111
- validationErrors.push('The config parameter "useUiApiAdapter" isn\'t a boolean');
2112
- }
2113
- if (validationErrors.length > 0) {
2114
- return {
2115
- validatedConfig: null,
2116
- errors: validationErrors,
2117
- };
2118
- }
2119
57
  return {
2120
58
  validatedConfig: {
2121
59
  variables,
2122
60
  query,
2123
- useUiApiAdapter,
2124
61
  },
2125
62
  errors: [],
2126
63
  };
2127
64
  }
2128
- function buildCachedSnapshot(context, storeLookup) {
2129
- return buildInMemorySnapshot(context, storeLookup);
2130
- }
2131
- function buildInMemorySnapshot(context, storeLookup) {
2132
- const { config, fragment, luvio } = context;
2133
- const selector = {
2134
- recordId: GRAPHQL_ROOT_KEY,
2135
- node: fragment,
2136
- variables: {},
2137
- };
2138
- return storeLookup(selector, buildSnapshotRefresh(luvio, config, fragment));
2139
- }
2140
- function buildNetworkSnapshotCachePolicy(context, coercedAdapterRequestContext) {
2141
- const { config, fragment, luvio } = context;
2142
- const { networkPriority, requestCorrelator, eventObservers, sourceContext } = coercedAdapterRequestContext;
2143
- const dispatchOptions = {
2144
- resourceRequestContext: {
2145
- requestCorrelator,
2146
- sourceContext,
2147
- },
2148
- eventObservers,
2149
- };
2150
- if (networkPriority !== 'normal') {
2151
- dispatchOptions.overrides = {
2152
- priority: networkPriority,
2153
- };
2154
- }
2155
- return buildNetworkSnapshot(luvio, config, fragment, dispatchOptions);
2156
- }
2157
- const replaceDraftIdsInVariables = (variables, draftFunctions) => {
2158
- const replace = (object) => {
2159
- if (typeof object === 'string') {
2160
- if (!draftFunctions.isDraftId(object)) {
2161
- return object;
2162
- }
2163
- return draftFunctions.getCanonicalId(object);
2164
- }
2165
- else if (isArray(object)) {
2166
- return object.map(replace);
2167
- }
2168
- else if (typeof object === 'object' && object !== null) {
2169
- let source = object;
2170
- return keys(source).reduce((acc, key) => {
2171
- acc[key] = replace(source[key]);
2172
- return acc;
2173
- }, {});
2174
- }
2175
- else {
2176
- return object;
2177
- }
2178
- };
2179
- let newVariables = keys(variables).reduce((acc, key) => {
2180
- acc[key] = replace(variables[key]);
2181
- return acc;
2182
- }, {});
2183
- return newVariables;
2184
- };
2185
65
  const graphQLAdapterFactory = (luvio) => {
2186
66
  const uiApiGraphQLAdapter = graphqlAdapterFactory(luvio);
2187
67
  function graphql(untrustedConfig, requestContext) {
@@ -2192,78 +72,21 @@ const graphQLAdapterFactory = (luvio) => {
2192
72
  }
2193
73
  return null;
2194
74
  }
2195
- const { query, variables, useUiApiAdapter } = validatedConfig;
2196
- if (useUiApiAdapter === true || ldsAdapterForwardingGate.isOpen({ fallback: false })) {
2197
- // Forward to new adapters
2198
- const resolvedQuery = astResolver(query);
2199
- if (resolvedQuery === undefined) {
2200
- if (process.env.NODE_ENV !== 'production') {
2201
- throw new Error('Could not resolve standard AST');
2202
- }
2203
- return null;
2204
- }
2205
- return uiApiGraphQLAdapter({
2206
- query: resolvedQuery,
2207
- variables,
2208
- }, requestContext);
2209
- }
2210
- else {
2211
- const fieldInjectionRequired = shouldInjectFields(query);
2212
- const validatedConfigWithInjection = fieldInjectionRequired
2213
- ? graphqlConfigWithInjectedAST(validatedConfig)
2214
- : validatedConfig;
2215
- const sanitizedConfig = draftFunctions !== undefined
2216
- ? sanitizeConfig(validatedConfigWithInjection, draftFunctions)
2217
- : validatedConfigWithInjection;
2218
- if (sanitizedConfig.variables && draftFunctions !== undefined) {
2219
- const variablesWithSwappedDraftIds = replaceDraftIdsInVariables(sanitizedConfig.variables, draftFunctions);
2220
- sanitizedConfig.variables = variablesWithSwappedDraftIds;
2221
- validatedConfig.variables = variablesWithSwappedDraftIds;
2222
- }
2223
- const fragment = createFragment(luvio, sanitizedConfig.query, sanitizedConfig.variables);
2224
- const context = {
2225
- config: sanitizedConfig,
2226
- fragment,
2227
- luvio,
2228
- };
2229
- // NOTE: For evaluating environments, set a context property to let the
2230
- // environment detect that eval will happen and to check varous gates
2231
- // for eval behavior customizations.
2232
- if (storeEval !== undefined) {
2233
- context.gqlEval = true;
2234
- }
2235
- const snapshotOrPromiseFromCachePolicy = luvio.applyCachePolicy(requestContext || {}, context, buildCachedSnapshot, buildNetworkSnapshotCachePolicy);
2236
- if (storeEval !== undefined) {
2237
- const observers = requestContext && requestContext.eventObservers
2238
- ? requestContext.eventObservers
2239
- : [];
2240
- // uses the original ast to do the eval to avoid fields not needed by users. The draftID swapping happens when filters transform to predicates.
2241
- return storeEval(validatedConfig, snapshotOrPromiseFromCachePolicy, observers, keyBuilder);
75
+ const { query, variables } = validatedConfig;
76
+ // Forward to new adapter
77
+ const resolvedQuery = astResolver(query);
78
+ if (resolvedQuery === undefined) {
79
+ if (process.env.NODE_ENV !== 'production') {
80
+ throw new Error('Could not resolve standard AST');
2242
81
  }
2243
- return snapshotOrPromiseFromCachePolicy;
82
+ return null;
2244
83
  }
84
+ return uiApiGraphQLAdapter({
85
+ query: resolvedQuery,
86
+ variables,
87
+ }, requestContext);
2245
88
  }
2246
89
  return graphql;
2247
90
  };
2248
- function graphqlConfigWithInjectedAST(graphqlConfig) {
2249
- const { query } = graphqlConfig;
2250
- const astCopy = parse(stringify(query));
2251
- const modifiedAST = injectFieldsGQL(astCopy);
2252
- return {
2253
- ...graphqlConfig,
2254
- query: modifiedAST,
2255
- };
2256
- }
2257
- function sanitizeConfig(graphqlConfig, draftFunctions) {
2258
- const { query } = graphqlConfig;
2259
- const astCopy = parse(stringify(query));
2260
- const modifiedAST = swapIdsOfDocumentNode(astCopy, draftFunctions);
2261
- return {
2262
- ...graphqlConfig,
2263
- query: modifiedAST,
2264
- };
2265
- }
2266
- // make sure to register the configuration whenever this module loads
2267
- register({ id: '@salesforce/lds-adapters-graphql', configuration });
2268
91
 
2269
- export { adapterName, buildCachedSnapshot, keyBuilder as connectionKeyBuilder, graphQLAdapterFactory, graphqlConfigWithInjectedAST, namespace, replaceDraftIdsInVariables, representationName, sanitizeConfig };
92
+ export { adapterName, graphQLAdapterFactory, namespace, representationName };