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