@salesforce/lds-adapters-apex 1.100.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,684 @@
1
+ /**
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ (function (global, factory) {
8
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@luvio/engine')) :
9
+ typeof define === 'function' && define.amd ? define(['exports', '@luvio/engine'], factory) :
10
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.apexService = {}, global.engine));
11
+ })(this, (function (exports, engine) { 'use strict';
12
+
13
+ var ObjectKeys$1 = Object.keys;
14
+ var JSONStringify = JSON.stringify;
15
+ var ArrayIsArray$1 = Array.isArray;
16
+ function untrustedIsObject(untrusted) {
17
+ return typeof untrusted === 'object' && untrusted !== null && ArrayIsArray$1(untrusted) === false;
18
+ }
19
+ var snapshotRefreshOptions = {
20
+ overrides: {
21
+ headers: {
22
+ 'Cache-Control': 'no-cache',
23
+ },
24
+ }
25
+ };
26
+ /**
27
+ * A deterministic JSON stringify implementation. Heavily adapted from https://github.com/epoberezkin/fast-json-stable-stringify.
28
+ * This is needed because insertion order for JSON.stringify(object) affects output:
29
+ * JSON.stringify({a: 1, b: 2})
30
+ * "{"a":1,"b":2}"
31
+ * JSON.stringify({b: 2, a: 1})
32
+ * "{"b":2,"a":1}"
33
+ * @param data Data to be JSON-stringified.
34
+ * @returns JSON.stringified value with consistent ordering of keys.
35
+ */
36
+ function stableJSONStringify$1(node) {
37
+ // This is for Date values.
38
+ if (node && node.toJSON && typeof node.toJSON === 'function') {
39
+ // eslint-disable-next-line no-param-reassign
40
+ node = node.toJSON();
41
+ }
42
+ if (node === undefined) {
43
+ return;
44
+ }
45
+ if (typeof node === 'number') {
46
+ return isFinite(node) ? '' + node : 'null';
47
+ }
48
+ if (typeof node !== 'object') {
49
+ return JSONStringify(node);
50
+ }
51
+ var i;
52
+ var out;
53
+ if (ArrayIsArray$1(node)) {
54
+ out = '[';
55
+ for (i = 0; i < node.length; i++) {
56
+ if (i) {
57
+ out += ',';
58
+ }
59
+ out += stableJSONStringify$1(node[i]) || 'null';
60
+ }
61
+ return out + ']';
62
+ }
63
+ if (node === null) {
64
+ return 'null';
65
+ }
66
+ var keys = ObjectKeys$1(node).sort();
67
+ out = '';
68
+ for (i = 0; i < keys.length; i++) {
69
+ var key = keys[i];
70
+ var value = stableJSONStringify$1(node[key]);
71
+ if (!value) {
72
+ continue;
73
+ }
74
+ if (out) {
75
+ out += ',';
76
+ }
77
+ out += JSONStringify(key) + ':' + value;
78
+ }
79
+ return '{' + out + '}';
80
+ }
81
+ var keyPrefix = 'Apex';
82
+
83
+ function createResourceRequest$1(config) {
84
+ var headers = {};
85
+ var header_xSFDCAllowContinuation = config.headers.xSFDCAllowContinuation;
86
+ if (header_xSFDCAllowContinuation !== undefined) {
87
+ headers['X-SFDC-Allow-Continuation'] = header_xSFDCAllowContinuation;
88
+ }
89
+ return {
90
+ baseUri: '/lwr/apex/v58.0',
91
+ basePath: '/' + config.urlParams.apexClass + '/' + config.urlParams.apexMethod + '',
92
+ method: 'get',
93
+ body: null,
94
+ urlParams: config.urlParams,
95
+ queryParams: config.queryParams,
96
+ headers: headers,
97
+ priority: 'normal',
98
+ };
99
+ }
100
+
101
+ var create = Object.create, keys = Object.keys, values = Object.values;
102
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
103
+ var isArray = Array.isArray;
104
+ var stringify = JSON.stringify;
105
+
106
+ var ObjectFreeze = Object.freeze, ObjectKeys = Object.keys;
107
+ var ArrayIsArray = Array.isArray;
108
+ function deepFreeze(value) {
109
+ // No need to freeze primitives
110
+ if (typeof value !== 'object' || value === null) {
111
+ return;
112
+ }
113
+ if (ArrayIsArray(value)) {
114
+ for (var i = 0, len = value.length; i < len; i += 1) {
115
+ deepFreeze(value[i]);
116
+ }
117
+ }
118
+ else {
119
+ var keys = ObjectKeys(value);
120
+ for (var i = 0, len = keys.length; i < len; i += 1) {
121
+ deepFreeze(value[keys[i]]);
122
+ }
123
+ }
124
+ ObjectFreeze(value);
125
+ }
126
+ function createLink(ref) {
127
+ return {
128
+ __ref: engine.serializeStructuredKey(ref),
129
+ };
130
+ }
131
+
132
+ var CACHE_CONTROL = 'cache-control';
133
+ var SHARED_ADAPTER_CONTEXT_ID = 'apex__shared';
134
+ // eslint-disable-next-line @salesforce/lds/no-invalid-todo
135
+ // TODO: APEX_TTL, apexResponseEquals, apexResponseIngest, and validateAdapterConfig should have been code generated
136
+ // however compiler does not support response body type any so hand roll for now
137
+ /**
138
+ * Time to live for the Apex cache value. 5 minutes.
139
+ */
140
+ var APEX_TTL = 5 * 60 * 1000;
141
+ // apex is essentially versionless, we can never know the shape of apex data
142
+ // so we will rely on components to code defensively. All apex data will be ingested
143
+ // and looked up with this version
144
+ var APEX_VERSION = 'APEX_V_1';
145
+ var APEX_STORE_METADATA_PARAMS = {
146
+ ttl: APEX_TTL,
147
+ namespace: keyPrefix,
148
+ representationName: '',
149
+ version: APEX_VERSION,
150
+ };
151
+ function apexResponseEquals(existing, incoming) {
152
+ return stringify(incoming) === stringify(existing);
153
+ }
154
+ var apexResponseIngest = function (input, path, luvio, store) {
155
+ // skip validation and normalization, since input type is any
156
+ var key = path.fullPath;
157
+ var incomingRecord = input;
158
+ var existingRecord = store.readEntry(key);
159
+ // freeze on ingest (luvio.opaque)
160
+ deepFreeze(incomingRecord);
161
+ if (existingRecord === undefined ||
162
+ apexResponseEquals(existingRecord, incomingRecord) === false) {
163
+ luvio.storePublish(key, incomingRecord);
164
+ }
165
+ luvio.publishStoreMetadata(key, APEX_STORE_METADATA_PARAMS);
166
+ return createLink(key);
167
+ };
168
+ function validateAdapterConfig(untrustedConfig) {
169
+ if (untrustedIsObject(untrustedConfig)) {
170
+ var values$1 = values(untrustedConfig);
171
+ return values$1.indexOf(undefined) === -1 ? untrustedConfig : null;
172
+ }
173
+ return untrustedConfig;
174
+ }
175
+ /**
176
+ * A standard delimiter when producing cache keys.
177
+ */
178
+ var KEY_DELIM = ':';
179
+ function isEmptyParam(param) {
180
+ return (param === undefined ||
181
+ param === null ||
182
+ (typeof param === 'object' && keys(param).length === 0));
183
+ }
184
+ function keyBuilder(classname, method, isContinuation, params) {
185
+ return [
186
+ classname.replace('__', KEY_DELIM),
187
+ method,
188
+ isContinuation,
189
+ isEmptyParam(params) ? '' : stableJSONStringify$1(params),
190
+ ].join(KEY_DELIM);
191
+ }
192
+ function configBuilder(config, classname, method, isContinuation) {
193
+ return {
194
+ apexMethod: method,
195
+ apexClass: classname,
196
+ methodParams: config,
197
+ xSFDCAllowContinuation: isContinuation + '',
198
+ };
199
+ }
200
+ function apexClassnameBuilder(namespace, classname) {
201
+ return namespace !== '' ? "".concat(namespace, "__").concat(classname) : classname;
202
+ }
203
+ function isCacheControlValueCacheable(value) {
204
+ if (value === undefined || value === null || typeof value !== 'string') {
205
+ return false;
206
+ }
207
+ return value.indexOf('no-cache') < 0 && value.indexOf('no-store') < 0;
208
+ }
209
+ function getCacheControlHeaderValue(headers) {
210
+ if (headers === undefined) {
211
+ return undefined;
212
+ }
213
+ // header fields are case-insensitive according to
214
+ // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
215
+ var headerKeys = keys(headers);
216
+ for (var i = 0, len = headerKeys.length; i < len; i += 1) {
217
+ var key = headerKeys[i];
218
+ if (key.toLowerCase() === CACHE_CONTROL) {
219
+ return headers[key];
220
+ }
221
+ }
222
+ return undefined;
223
+ }
224
+ function shouldCache(response) {
225
+ var headers = response.headers;
226
+ var headerValue = getCacheControlHeaderValue(headers);
227
+ return isCacheControlValueCacheable(headerValue);
228
+ }
229
+ function getCacheableKey(recordId) {
230
+ return "".concat(recordId, "_cacheable");
231
+ }
232
+ function set(context, recordId, value) {
233
+ var key = getCacheableKey(recordId);
234
+ context.set(key, value);
235
+ }
236
+ function get(context, key) {
237
+ return context.get(getCacheableKey(key));
238
+ }
239
+ function setCacheControlAdapterContext(context, recordId, response) {
240
+ var headers = response.headers;
241
+ var headerValue = getCacheControlHeaderValue(headers);
242
+ if (headerValue !== undefined) {
243
+ set(context, recordId, headerValue);
244
+ }
245
+ }
246
+ function isCacheable(config, context) {
247
+ var apexClass = config.apexClass, apexMethod = config.apexMethod, xSFDCAllowContinuation = config.xSFDCAllowContinuation, methodParams = config.methodParams;
248
+ var recordId = keyBuilder(apexClass, apexMethod, xSFDCAllowContinuation, methodParams);
249
+ return checkAdapterContext(context, recordId);
250
+ }
251
+ function checkAdapterContext(context, recordId) {
252
+ var contextValue = get(context, recordId);
253
+ return isCacheControlValueCacheable(contextValue);
254
+ }
255
+
256
+ function createResourceParams$1(config) {
257
+ var queryParams = create(null);
258
+ if (!isEmptyParam(config.methodParams)) {
259
+ queryParams.methodParams = config.methodParams;
260
+ }
261
+ return {
262
+ queryParams: queryParams,
263
+ urlParams: {
264
+ apexMethod: config.apexMethod,
265
+ apexClass: config.apexClass,
266
+ },
267
+ headers: {
268
+ xSFDCAllowContinuation: config.xSFDCAllowContinuation,
269
+ },
270
+ };
271
+ }
272
+ function keyBuilderFromResourceParams$1(params) {
273
+ var classname = params.urlParams.apexClass.replace('__', KEY_DELIM);
274
+ return [
275
+ classname,
276
+ params.urlParams.apexMethod,
277
+ params.headers.xSFDCAllowContinuation,
278
+ isEmptyParam(params.queryParams.methodParams)
279
+ ? ''
280
+ : stableJSONStringify$1(params.queryParams.methodParams),
281
+ ].join(KEY_DELIM);
282
+ }
283
+ function ingestSuccess$1(luvio, resourceParams, response, snapshotRefresh) {
284
+ var body = response.body;
285
+ var recordId = keyBuilderFromResourceParams$1(resourceParams);
286
+ var select = {
287
+ recordId: recordId,
288
+ node: { kind: 'Fragment', opaque: true, private: [], version: APEX_VERSION },
289
+ variables: {},
290
+ };
291
+ luvio.storeIngest(recordId, apexResponseIngest, body);
292
+ var snapshot = luvio.storeLookup(select, snapshotRefresh);
293
+ if (process.env.NODE_ENV !== 'production') {
294
+ if (response.headers !== undefined && snapshot.state !== 'Fulfilled') {
295
+ throw new Error('Invalid network response. Expected resource response to result in Fulfilled snapshot');
296
+ }
297
+ if (!(snapshot.state === 'Fulfilled' || snapshot.state === 'Stale')) {
298
+ throw new Error('Invalid resource response. Expected resource response to result in Fulfilled or Stale snapshot');
299
+ }
300
+ }
301
+ return snapshot;
302
+ }
303
+ function buildCachedSnapshotCachePolicy$1(buildSnapshotContext, storeLookup) {
304
+ var luvio = buildSnapshotContext.luvio, config = buildSnapshotContext.config, adapterContext = buildSnapshotContext.adapterContext;
305
+ var apexClass = config.apexClass, apexMethod = config.apexMethod, xSFDCAllowContinuation = config.xSFDCAllowContinuation, methodParams = config.methodParams;
306
+ var recordId = keyBuilder(apexClass, apexMethod, xSFDCAllowContinuation, methodParams);
307
+ return storeLookup({
308
+ recordId: recordId,
309
+ node: {
310
+ kind: 'Fragment',
311
+ opaque: true,
312
+ private: [],
313
+ version: APEX_VERSION,
314
+ },
315
+ variables: {},
316
+ }, {
317
+ config: config,
318
+ resolve: function () {
319
+ return buildNetworkSnapshot$1(luvio, adapterContext, config, snapshotRefreshOptions);
320
+ },
321
+ });
322
+ }
323
+ function onFetchResponseSuccess$1(luvio, context, config, resourceParams, response) {
324
+ var recordId = keyBuilderFromResourceParams$1(resourceParams);
325
+ var select = {
326
+ recordId: recordId,
327
+ node: { kind: 'Fragment', opaque: true, private: [], version: APEX_VERSION },
328
+ variables: {},
329
+ };
330
+ setCacheControlAdapterContext(context, recordId, response);
331
+ if (shouldCache(response)) {
332
+ var snapshot_1 = ingestSuccess$1(luvio, resourceParams, response, {
333
+ config: config,
334
+ resolve: function () { return buildNetworkSnapshot$1(luvio, context, config, snapshotRefreshOptions); },
335
+ });
336
+ return luvio.storeBroadcast().then(function () { return snapshot_1; });
337
+ }
338
+ // if Cache-Control is not set or set to 'no-cache', return a synthetic snapshot
339
+ return Promise.resolve({
340
+ recordId: recordId,
341
+ variables: {},
342
+ seenRecords: new engine.StoreKeySet(),
343
+ select: select,
344
+ state: 'Fulfilled',
345
+ data: response.body,
346
+ });
347
+ }
348
+ function onFetchResponseError$1(luvio, context, config, _resourceParams, response) {
349
+ return Promise.resolve(luvio.errorSnapshot(response, {
350
+ config: config,
351
+ resolve: function () { return buildNetworkSnapshot$1(luvio, context, config, snapshotRefreshOptions); },
352
+ }));
353
+ }
354
+ function buildNetworkSnapshot$1(luvio, context, config, options) {
355
+ var resourceParams = createResourceParams$1(config);
356
+ var request = createResourceRequest$1(resourceParams);
357
+ return luvio.dispatchResourceRequest(request, options).then(function (response) {
358
+ return luvio.handleSuccessResponse(function () { return onFetchResponseSuccess$1(luvio, context, config, resourceParams, response); },
359
+ // TODO [W-10490362]: Properly generate the response cache keys
360
+ function () {
361
+ return new engine.StoreKeyMap();
362
+ });
363
+ }, function (response) {
364
+ return luvio.handleErrorResponse(function () {
365
+ return onFetchResponseError$1(luvio, context, config, resourceParams, response);
366
+ });
367
+ });
368
+ }
369
+ function buildNetworkSnapshotCachePolicy$1(context, coercedAdapterRequestContext) {
370
+ var luvio = context.luvio, config = context.config, adapterContext = context.adapterContext;
371
+ var networkPriority = coercedAdapterRequestContext.networkPriority, requestCorrelator = coercedAdapterRequestContext.requestCorrelator, eventObservers = coercedAdapterRequestContext.eventObservers;
372
+ var dispatchOptions = {
373
+ resourceRequestContext: {
374
+ requestCorrelator: requestCorrelator,
375
+ },
376
+ eventObservers: eventObservers,
377
+ };
378
+ if (networkPriority !== 'normal') {
379
+ dispatchOptions.overrides = {
380
+ priority: networkPriority,
381
+ };
382
+ }
383
+ return buildNetworkSnapshot$1(luvio, adapterContext, config, dispatchOptions);
384
+ }
385
+ var factory = function (luvio, invokerParams) {
386
+ var namespace = invokerParams.namespace, classname = invokerParams.classname, method = invokerParams.method, isContinuation = invokerParams.isContinuation;
387
+ return getApexAdapterFactory(luvio, namespace, classname, method, isContinuation);
388
+ };
389
+ function getApexAdapterFactory(luvio, namespace, classname, method, isContinuation) {
390
+ return luvio.withContext(function apex__getApex(untrustedConfig, context, requestContext) {
391
+ // Even though the config is of type `any`,
392
+ // validation is required here because `undefined`
393
+ // values on a wire mean that properties on the component
394
+ // used in the config have not been loaded yet.
395
+ var config = validateAdapterConfig(untrustedConfig);
396
+ // Invalid or incomplete config
397
+ if (config === null) {
398
+ return null;
399
+ }
400
+ var configPlus = configBuilder(config, apexClassnameBuilder(namespace, classname), method, isContinuation);
401
+ return luvio.applyCachePolicy(requestContext || {}, { config: configPlus, luvio: luvio, adapterContext: context }, buildCachedSnapshotCachePolicy$1, buildNetworkSnapshotCachePolicy$1);
402
+ }, { contextId: SHARED_ADAPTER_CONTEXT_ID });
403
+ }
404
+
405
+ /**
406
+ * A deterministic JSON stringify implementation. Heavily adapted from https://github.com/epoberezkin/fast-json-stable-stringify.
407
+ * This is needed because insertion order for JSON.stringify(object) affects output:
408
+ * JSON.stringify({a: 1, b: 2})
409
+ * "{"a":1,"b":2}"
410
+ * JSON.stringify({b: 2, a: 1})
411
+ * "{"b":2,"a":1}"
412
+ * @param data Data to be JSON-stringified.
413
+ * @returns JSON.stringified value with consistent ordering of keys.
414
+ */
415
+ function stableJSONStringify(node) {
416
+ // This is for Date values.
417
+ if (node && node.toJSON && typeof node.toJSON === 'function') {
418
+ // eslint-disable-next-line no-param-reassign
419
+ node = node.toJSON();
420
+ }
421
+ if (node === undefined) {
422
+ return;
423
+ }
424
+ if (typeof node === 'number') {
425
+ return isFinite(node) ? '' + node : 'null';
426
+ }
427
+ if (typeof node !== 'object') {
428
+ return stringify(node);
429
+ }
430
+ var i;
431
+ var out;
432
+ if (isArray(node)) {
433
+ out = '[';
434
+ for (i = 0; i < node.length; i++) {
435
+ if (i) {
436
+ out += ',';
437
+ }
438
+ out += stableJSONStringify(node[i]) || 'null';
439
+ }
440
+ return out + ']';
441
+ }
442
+ if (node === null) {
443
+ return 'null';
444
+ }
445
+ var keys$1 = keys(node).sort();
446
+ out = '';
447
+ for (i = 0; i < keys$1.length; i++) {
448
+ var key = keys$1[i];
449
+ var value = stableJSONStringify(node[key]);
450
+ if (!value) {
451
+ continue;
452
+ }
453
+ if (out) {
454
+ out += ',';
455
+ }
456
+ out += stringify(key) + ':' + value;
457
+ }
458
+ return '{' + out + '}';
459
+ }
460
+ /**
461
+ * Returns the field API name, qualified with an object name if possible.
462
+ * @param value The value from which to get the qualified field API name.
463
+ * @return The qualified field API name.
464
+ */
465
+ function getFieldApiName(value) {
466
+ if (typeof value === 'string') {
467
+ return value;
468
+ }
469
+ else if (value &&
470
+ typeof value.objectApiName === 'string' &&
471
+ typeof value.fieldApiName === 'string') {
472
+ return value.objectApiName + '.' + value.fieldApiName;
473
+ }
474
+ throw new TypeError('Value is not a string or FieldId.');
475
+ }
476
+ /**
477
+ * Split the object API name and field API name from a qualified field name.
478
+ * Eg: Opportunity.Title returns ['Opportunity', 'Title']
479
+ * Eg: Opportunity.Account.Name returns ['Opportunity', 'Account.Name']
480
+ * @param fieldApiName The qualified field name.
481
+ * @return The object and field API names.
482
+ */
483
+ function splitQualifiedFieldApiName(fieldApiName) {
484
+ var idx = fieldApiName.indexOf('.');
485
+ if (idx < 1) {
486
+ // object api name must non-empty
487
+ throw new TypeError('Value does not include an object API name.');
488
+ }
489
+ return [fieldApiName.substring(0, idx), fieldApiName.substring(idx + 1)];
490
+ }
491
+
492
+ function createResourceRequest(config) {
493
+ var headers = {};
494
+ var header_xSFDCAllowContinuation = config.headers.xSFDCAllowContinuation;
495
+ if (header_xSFDCAllowContinuation !== undefined) {
496
+ headers['X-SFDC-Allow-Continuation'] = header_xSFDCAllowContinuation;
497
+ }
498
+ return {
499
+ baseUri: '/lwr/apex/v58.0',
500
+ basePath: '/' + config.urlParams.apexClass + '/' + config.urlParams.apexMethod + '',
501
+ method: 'post',
502
+ body: config.body,
503
+ urlParams: config.urlParams,
504
+ queryParams: {},
505
+ headers: headers,
506
+ priority: 'normal',
507
+ };
508
+ }
509
+
510
+ function createResourceParams(config) {
511
+ return {
512
+ urlParams: {
513
+ apexMethod: config.apexMethod,
514
+ apexClass: config.apexClass,
515
+ },
516
+ body: config.methodParams,
517
+ headers: {
518
+ xSFDCAllowContinuation: config.xSFDCAllowContinuation,
519
+ },
520
+ };
521
+ }
522
+ function keyBuilderFromResourceParams(params) {
523
+ var classname = params.urlParams.apexClass.replace('__', KEY_DELIM);
524
+ return [
525
+ classname,
526
+ params.urlParams.apexMethod,
527
+ params.headers.xSFDCAllowContinuation,
528
+ isEmptyParam(params.body) ? '' : stableJSONStringify(params.body),
529
+ ].join(KEY_DELIM);
530
+ }
531
+ function ingestSuccess(luvio, resourceParams, response, snapshotRefresh) {
532
+ var body = response.body;
533
+ var recordId = keyBuilderFromResourceParams(resourceParams);
534
+ var select = {
535
+ recordId: recordId,
536
+ node: { kind: 'Fragment', opaque: true, private: [], version: APEX_VERSION },
537
+ variables: {},
538
+ };
539
+ luvio.storeIngest(recordId, apexResponseIngest, body);
540
+ var snapshot = luvio.storeLookup(select, snapshotRefresh);
541
+ if (process.env.NODE_ENV !== 'production') {
542
+ if (response.headers !== undefined && snapshot.state !== 'Fulfilled') {
543
+ throw new Error('Invalid network response. Expected resource response to result in Fulfilled snapshot');
544
+ }
545
+ if (!(snapshot.state === 'Fulfilled' || snapshot.state === 'Stale')) {
546
+ throw new Error('Invalid resource response. Expected resource response to result in Fulfilled or Stale snapshot');
547
+ }
548
+ }
549
+ return snapshot;
550
+ }
551
+ function buildCachedSnapshotCachePolicy(buildSnapshotContext, storeLookup) {
552
+ var config = buildSnapshotContext.config;
553
+ var apexClass = config.apexClass, apexMethod = config.apexMethod, xSFDCAllowContinuation = config.xSFDCAllowContinuation, methodParams = config.methodParams;
554
+ var recordId = keyBuilder(apexClass, apexMethod, xSFDCAllowContinuation, methodParams);
555
+ return storeLookup({
556
+ recordId: recordId,
557
+ node: {
558
+ kind: 'Fragment',
559
+ opaque: true,
560
+ private: [],
561
+ version: APEX_VERSION,
562
+ },
563
+ variables: {},
564
+ });
565
+ }
566
+ function onFetchResponseSuccess(luvio, context, _config, resourceParams, response) {
567
+ var recordId = keyBuilderFromResourceParams(resourceParams);
568
+ var select = {
569
+ recordId: recordId,
570
+ node: { kind: 'Fragment', opaque: true, private: [], version: APEX_VERSION },
571
+ variables: {},
572
+ };
573
+ setCacheControlAdapterContext(context, recordId, response);
574
+ if (shouldCache(response)) {
575
+ var snapshot_1 = ingestSuccess(luvio, resourceParams, response);
576
+ return luvio.storeBroadcast().then(function () { return snapshot_1; });
577
+ }
578
+ // if Cache-Control is not set or set to 'no-cache', return a synthetic snapshot
579
+ return Promise.resolve({
580
+ recordId: recordId,
581
+ variables: {},
582
+ seenRecords: new engine.StoreKeySet(),
583
+ select: select,
584
+ state: 'Fulfilled',
585
+ data: response.body,
586
+ });
587
+ }
588
+ function onFetchResponseError(luvio, _context, _config, _resourceParams, response) {
589
+ return Promise.resolve(luvio.errorSnapshot(response));
590
+ }
591
+ function buildNetworkSnapshot(luvio, context, config, options) {
592
+ var resourceParams = createResourceParams(config);
593
+ var request = createResourceRequest(resourceParams);
594
+ return luvio.dispatchResourceRequest(request, options).then(function (response) {
595
+ return luvio.handleSuccessResponse(function () { return onFetchResponseSuccess(luvio, context, config, resourceParams, response); },
596
+ // TODO [W-10490362]: Properly generate response cache keys
597
+ function () {
598
+ return new engine.StoreKeyMap();
599
+ });
600
+ }, function (response) {
601
+ return luvio.handleErrorResponse(function () {
602
+ return onFetchResponseError(luvio, context, config, resourceParams, response);
603
+ });
604
+ });
605
+ }
606
+ function buildNetworkSnapshotCachePolicy(context, coercedAdapterRequestContext) {
607
+ var luvio = context.luvio, config = context.config, adapterContext = context.adapterContext;
608
+ var networkPriority = coercedAdapterRequestContext.networkPriority, requestCorrelator = coercedAdapterRequestContext.requestCorrelator, eventObservers = coercedAdapterRequestContext.eventObservers;
609
+ var dispatchOptions = {
610
+ resourceRequestContext: {
611
+ requestCorrelator: requestCorrelator,
612
+ },
613
+ eventObservers: eventObservers,
614
+ };
615
+ if (networkPriority !== 'normal') {
616
+ dispatchOptions.overrides = {
617
+ priority: networkPriority,
618
+ };
619
+ }
620
+ return buildNetworkSnapshot(luvio, adapterContext, config, dispatchOptions);
621
+ }
622
+ var invoker = function (luvio, invokerParams) {
623
+ var namespace = invokerParams.namespace, classname = invokerParams.classname, method = invokerParams.method, isContinuation = invokerParams.isContinuation;
624
+ var ldsAdapter = postApexAdapterFactory(luvio, namespace, classname, method, isContinuation);
625
+ return getInvoker(ldsAdapter);
626
+ };
627
+ function getInvoker(ldsAdapter) {
628
+ return function (config, requestContext) {
629
+ var snapshotOrPromise = ldsAdapter(config, requestContext);
630
+ return Promise.resolve(snapshotOrPromise).then(function (snapshot) {
631
+ if (snapshot.state === 'Error') {
632
+ throw snapshot.error;
633
+ }
634
+ return snapshot.data;
635
+ });
636
+ };
637
+ }
638
+ function postApexAdapterFactory(luvio, namespace, classname, method, isContinuation) {
639
+ return luvio.withContext(function apex__postApex(config, context, requestContext) {
640
+ // config validation is unnecessary for this imperative adapter
641
+ // due to the config being of type `any`.
642
+ // however, we have special config validation for the wire adapter,
643
+ // explanation in getApex
644
+ var configPlus = configBuilder(config, apexClassnameBuilder(namespace, classname), method, isContinuation);
645
+ // if this response isn't meant to be cached then pass a buildCached
646
+ // func that returns undefined, that way cache policy impls will know
647
+ // not to do any cache lookups
648
+ var buildCached = isCacheable(configPlus, context)
649
+ ? buildCachedSnapshotCachePolicy
650
+ : function () { return undefined; };
651
+ return luvio.applyCachePolicy(requestContext || {}, { config: configPlus, luvio: luvio, adapterContext: context }, buildCached, buildNetworkSnapshotCachePolicy);
652
+ }, { contextId: SHARED_ADAPTER_CONTEXT_ID });
653
+ }
654
+
655
+ /**
656
+ * Gets a field value from an Apex sObject.
657
+ * @param sobject The sObject holding the field.
658
+ * @param field The qualified API name of the field to return.
659
+ * @returns The field's value. If it doesn't exist, undefined is returned.
660
+ */
661
+ function getSObjectValue(sObject, field) {
662
+ if (untrustedIsObject(sObject) === false) {
663
+ return;
664
+ }
665
+ var unqualifiedField = splitQualifiedFieldApiName(getFieldApiName(field))[1];
666
+ var fields = unqualifiedField.split('.');
667
+ var ret = sObject;
668
+ for (var i = 0, fieldsLength = fields.length; i < fieldsLength; i++) {
669
+ var nextField = fields[i];
670
+ if (!hasOwnProperty.call(ret, nextField)) {
671
+ return undefined;
672
+ }
673
+ ret = ret[nextField];
674
+ }
675
+ return ret;
676
+ }
677
+
678
+ exports.GetApexInvoker = invoker;
679
+ exports.GetApexWireAdapterFactory = factory;
680
+ exports.getSObjectValue = getSObjectValue;
681
+
682
+ Object.defineProperty(exports, '__esModule', { value: true });
683
+
684
+ }));