@salesforce/lds-ads-bridge 1.100.2

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,57 @@
1
+ import { Luvio } from '@luvio/engine';
2
+ import { ingestRecord, ingestObjectInfo } from '@salesforce/lds-adapters-uiapi';
3
+
4
+ export function createRecord(config: any = {}) {
5
+ return {
6
+ apiName: 'Test__c',
7
+ childRelationships: {},
8
+ lastModifiedById: null,
9
+ lastModifiedDate: null,
10
+ recordTypeId: null,
11
+ recordTypeInfo: null,
12
+ systemModstamp: null,
13
+ weakEtag: 0,
14
+ eTag: '123456',
15
+ fields: {},
16
+ ...config,
17
+ };
18
+ }
19
+
20
+ export function createObjectInfo(config: any = {}) {
21
+ return {
22
+ apiName: 'Test__c',
23
+ associateEntityType: null,
24
+ associateParentEntity: null,
25
+ childRelationships: [],
26
+ createable: true,
27
+ custom: true,
28
+ defaultRecordTypeId: null,
29
+ deletable: true,
30
+ dependentFields: {},
31
+ feedEnabled: true,
32
+ fields: {},
33
+ keyPrefix: '00X',
34
+ label: 'test',
35
+ labelPlural: 'tests',
36
+ layoutable: true,
37
+ mruEnabled: true,
38
+ nameFields: [],
39
+ queryable: true,
40
+ recordTypeInfos: {},
41
+ searchable: true,
42
+ themeInfo: null,
43
+ updateable: true,
44
+ eTag: '123456',
45
+ ...config,
46
+ };
47
+ }
48
+
49
+ export function addRecord(luvio: Luvio, data: any) {
50
+ luvio.storeIngest('', ingestRecord, data);
51
+ luvio.storeBroadcast();
52
+ }
53
+
54
+ export function addObjectInfo(luvio: Luvio, data: any) {
55
+ luvio.storeIngest('', ingestObjectInfo, data);
56
+ luvio.storeBroadcast();
57
+ }
@@ -0,0 +1,457 @@
1
+ import type { Luvio, ProxyGraphNode, GraphNode } from '@luvio/engine';
2
+ import type {
3
+ RecordRepresentation,
4
+ RecordRepresentationNormalized,
5
+ ObjectInfoRepresentation,
6
+ FieldValueRepresentation,
7
+ FieldValueRepresentationNormalized,
8
+ } from '@salesforce/lds-adapters-uiapi';
9
+ import {
10
+ ingestRecord,
11
+ keyBuilderRecord,
12
+ keyBuilderObjectInfo,
13
+ } from '@salesforce/lds-adapters-uiapi';
14
+
15
+ import {
16
+ ArrayPrototypePush,
17
+ JSONParse,
18
+ JSONStringify,
19
+ ObjectKeys,
20
+ ObjectPrototypeHasOwnProperty,
21
+ } from './utils/language';
22
+
23
+ import {
24
+ ADS_BRIDGE_ADD_RECORDS_DURATION,
25
+ ADS_BRIDGE_EMIT_RECORD_CHANGED_DURATION,
26
+ ADS_BRIDGE_EVICT_DURATION,
27
+ } from './utils/metric-keys';
28
+ import { instrumentation } from './instrumentation';
29
+
30
+ import { RECORD_ID_PREFIX, isStoreKeyRecordId } from '@salesforce/lds-uiapi-record-utils';
31
+
32
+ // No need to pass the actual record key `luvio.ingestStore`. The `RecordRepresentation.ts#ingest`
33
+ // function extracts the appropriate record id from the ingested record.
34
+ const INGEST_KEY = '';
35
+
36
+ const MASTER_RECORD_TYPE_ID = '012000000000000AAA';
37
+
38
+ const DMO_API_NAME_SUFFIX = '__dlm';
39
+
40
+ type Unsubscribe = () => void;
41
+
42
+ interface AdsRecord {
43
+ /**
44
+ * True if the passed record is a primary record, otherwise false.
45
+ *
46
+ * The Salesforce APIs may represent different records with the same record id. All the
47
+ * records returned by the UI API are primary records.
48
+ */
49
+ isPrimary: boolean;
50
+
51
+ /** The actual record data */
52
+ record: RecordRepresentation;
53
+ }
54
+
55
+ interface AdsRecordMap {
56
+ [recordId: string]: {
57
+ [objectApiName: string]: AdsRecord;
58
+ };
59
+ }
60
+
61
+ interface ObjectMetadata {
62
+ /**
63
+ * The entity key prefix.
64
+ * This originally was typed as simply a "string",
65
+ * however, "keyPrefix" can be null on ObjectInfoRepresentation
66
+ * and existing behavior simply passes ObjectInfoRepresentation.keyPrefix
67
+ * straight to ADS. This type has been updated to capture that
68
+ * a string or null can be passed here.
69
+ * */
70
+
71
+ _keyPrefix: string | null;
72
+
73
+ /** The entity field name. */
74
+ _nameField: string;
75
+
76
+ /** The entity label. */
77
+ _entityLabel: string;
78
+ }
79
+
80
+ interface AdsObjectMetadataMap {
81
+ [objectApiName: string]: ObjectMetadata;
82
+ }
83
+
84
+ type LdsRecordChangedCallback = (record: AdsRecordMap, objectMetadata: AdsObjectMetadataMap) => any;
85
+
86
+ function isGraphNode<T, U>(node: ProxyGraphNode<T, U>): node is GraphNode<T, U> {
87
+ return node !== null && node.type === 'Node';
88
+ }
89
+
90
+ function isSpanningRecord(
91
+ fieldValue: null | string | number | boolean | RecordRepresentation
92
+ ): fieldValue is RecordRepresentation {
93
+ return fieldValue !== null && typeof fieldValue === 'object';
94
+ }
95
+
96
+ /**
97
+ * Returns a shallow copy of a record with its field values if it is a scalar and a reference and a
98
+ * a RecordRepresentation with no field if the value if a spanning record.
99
+ * It returns null if the record contains any pending field.
100
+ */
101
+ function getShallowRecord(luvio: Luvio, storeRecordId: string): RecordRepresentation | null {
102
+ const recordNode = luvio.getNode<RecordRepresentationNormalized, RecordRepresentation>(
103
+ storeRecordId
104
+ );
105
+
106
+ if (!isGraphNode(recordNode)) {
107
+ return null;
108
+ }
109
+
110
+ const fieldsCopy: RecordRepresentation['fields'] = {};
111
+ const copy: RecordRepresentation = {
112
+ ...recordNode.retrieve(),
113
+ fields: fieldsCopy,
114
+ childRelationships: {},
115
+ };
116
+
117
+ const fieldsNode = recordNode.object('fields');
118
+ const fieldNames = fieldsNode.keys();
119
+
120
+ for (let i = 0, len = fieldNames.length; i < len; i++) {
121
+ let fieldCopy: FieldValueRepresentation;
122
+
123
+ const fieldName = fieldNames[i];
124
+ const fieldLink = fieldsNode.link<
125
+ FieldValueRepresentationNormalized,
126
+ FieldValueRepresentation
127
+ >(fieldName);
128
+ if (fieldLink.isPending() === true) {
129
+ return null;
130
+ }
131
+
132
+ const fieldNode = fieldLink.follow();
133
+ if (!isGraphNode(fieldNode)) {
134
+ continue;
135
+ }
136
+
137
+ const { displayValue, value } = fieldNode.retrieve();
138
+ if (fieldNode.isScalar('value')) {
139
+ fieldCopy = {
140
+ displayValue: displayValue,
141
+ value: value as string | number | boolean | null,
142
+ };
143
+ } else {
144
+ const spanningRecordLink = fieldNode.link<
145
+ RecordRepresentationNormalized,
146
+ RecordRepresentation
147
+ >('value');
148
+ if (spanningRecordLink.isPending() === true) {
149
+ return null;
150
+ }
151
+
152
+ const spanningRecordNode = spanningRecordLink.follow();
153
+ if (!isGraphNode(spanningRecordNode)) {
154
+ continue;
155
+ }
156
+
157
+ fieldCopy = {
158
+ displayValue,
159
+ value: {
160
+ ...spanningRecordNode.retrieve(),
161
+ fields: {},
162
+ childRelationships: {},
163
+ },
164
+ };
165
+ }
166
+
167
+ fieldsCopy[fieldName] = fieldCopy;
168
+ }
169
+
170
+ return copy;
171
+ }
172
+
173
+ /**
174
+ * Returns the ADS object metadata representation for a specific record.
175
+ */
176
+ function getObjectMetadata(luvio: Luvio, record: RecordRepresentation): ObjectMetadata {
177
+ const { data: objectInfo } = luvio.storeLookup<ObjectInfoRepresentation>({
178
+ recordId: keyBuilderObjectInfo(luvio, { apiName: record.apiName }),
179
+ node: {
180
+ kind: 'Fragment',
181
+ private: ['eTag'],
182
+ opaque: true,
183
+ },
184
+ variables: {},
185
+ });
186
+
187
+ if (objectInfo !== undefined) {
188
+ let nameField = 'Name';
189
+
190
+ // Extract the entity name field from the object info. In the case where there are multiple
191
+ // field names then pick up the first one.
192
+ if (objectInfo.nameFields.length !== 0 && objectInfo.nameFields.indexOf('Name') === -1) {
193
+ nameField = objectInfo.nameFields[0];
194
+ }
195
+
196
+ return {
197
+ _nameField: nameField,
198
+ _entityLabel: objectInfo.label,
199
+ _keyPrefix: objectInfo.keyPrefix,
200
+ };
201
+ }
202
+
203
+ return {
204
+ _nameField: 'Name',
205
+ _entityLabel: record.apiName,
206
+ _keyPrefix: record.id.substring(0, 3),
207
+ };
208
+ }
209
+
210
+ /**
211
+ * RecordGvp can send records back to ADS with record types incorrectly set to the master
212
+ * record type. Since there are no known legitimate scenarios where a record can change from a
213
+ * non-master record type back to the master record type, we assume such a transition
214
+ * indicates a RecordGvp mistake. This function checks for that scenario and overwrites the
215
+ * incoming ADS record type information with what we already have in the store when it
216
+ * occurs.
217
+ *
218
+ * @param luvio Luvio
219
+ * @param record record from ADS, will be fixed in situ
220
+ */
221
+ function fixRecordTypes(luvio: Luvio, record: RecordRepresentation): void {
222
+ // non-master record types should always be correct
223
+ if (record.recordTypeId === MASTER_RECORD_TYPE_ID) {
224
+ const key = keyBuilderRecord(luvio, { recordId: record.id });
225
+ const recordNode = luvio.getNode<RecordRepresentationNormalized, RecordRepresentation>(key);
226
+
227
+ if (
228
+ isGraphNode(recordNode) &&
229
+ recordNode.scalar('recordTypeId') !== MASTER_RECORD_TYPE_ID
230
+ ) {
231
+ // ignore bogus incoming record type information & keep what we have
232
+ record.recordTypeId = recordNode.scalar('recordTypeId');
233
+ record.recordTypeInfo = recordNode.object('recordTypeInfo').data;
234
+ }
235
+ }
236
+
237
+ // recurse on nested records
238
+ const fieldKeys = ObjectKeys(record.fields);
239
+ const fieldKeysLen = fieldKeys.length;
240
+ for (let i = 0; i < fieldKeysLen; ++i) {
241
+ const fieldValue = record.fields[fieldKeys[i]].value;
242
+ if (isSpanningRecord(fieldValue)) {
243
+ fixRecordTypes(luvio, fieldValue);
244
+ }
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Returns whether or not a the record is a DMO entity.
250
+ * @param record - The record.
251
+ * @returns True if DMO, false otherwise.
252
+ */
253
+ export function isDMOEntity(record: RecordRepresentation): boolean {
254
+ return record.apiName.endsWith(DMO_API_NAME_SUFFIX);
255
+ }
256
+
257
+ export default class AdsBridge {
258
+ private isRecordEmitLocked: boolean = false;
259
+ private watchUnsubscribe: Unsubscribe | undefined;
260
+
261
+ constructor(private luvio: Luvio) {}
262
+
263
+ /**
264
+ * This setter invoked by recordLibrary to listen for records ingested by Luvio. The passed method
265
+ * is invoked whenever a record is ingested. It may be via getRecord, getRecordUi, getListUi, ...
266
+ */
267
+ public set receiveFromLdsCallback(callback: LdsRecordChangedCallback | undefined) {
268
+ // Unsubscribe if there is an existing subscription.
269
+ if (this.watchUnsubscribe !== undefined) {
270
+ this.watchUnsubscribe();
271
+ this.watchUnsubscribe = undefined;
272
+ }
273
+
274
+ if (callback !== undefined) {
275
+ this.watchUnsubscribe = this.luvio.storeWatch(RECORD_ID_PREFIX, (entries) => {
276
+ if (this.isRecordEmitLocked === true) {
277
+ return;
278
+ }
279
+
280
+ this.emitRecordChanged(entries, callback);
281
+ });
282
+ }
283
+ }
284
+
285
+ /**
286
+ * This method is invoked when a record has been ingested by ADS.
287
+ *
288
+ * ADS may invoke this method with records that are not UIAPI allowlisted so not refreshable by
289
+ * Luvio. Luvio filters the provided list so it ingests only UIAPI allowlisted records.
290
+ */
291
+ public addRecords(
292
+ records: RecordRepresentation[],
293
+ uiApiEntityAllowlist?: {
294
+ [name: string]: 'false' | undefined;
295
+ }
296
+ ): void {
297
+ const startTime = Date.now();
298
+ const { luvio } = this;
299
+ let didIngestRecord = false;
300
+ return this.lockLdsRecordEmit(() => {
301
+ for (let i = 0; i < records.length; i++) {
302
+ const record = records[i];
303
+ const { apiName } = record;
304
+
305
+ // Ingest the record if no allowlist is passed or the entity name is allowlisted.
306
+ if (
307
+ uiApiEntityAllowlist === undefined ||
308
+ uiApiEntityAllowlist[apiName] !== 'false'
309
+ ) {
310
+ didIngestRecord = true;
311
+
312
+ // Deep-copy the record to ingest and ingest the record copy. This avoids
313
+ // corrupting the ADS cache since ingestion mutates the passed record.
314
+ const recordCopy = JSONParse(JSONStringify(record));
315
+
316
+ // Don't let incorrect ADS/RecordGVP recordTypeIds replace a valid record type in our store
317
+ // with the master record type. See W-7302870 for details.
318
+ fixRecordTypes(luvio, recordCopy);
319
+
320
+ luvio.storeIngest(INGEST_KEY, ingestRecord, recordCopy);
321
+ }
322
+ }
323
+
324
+ if (didIngestRecord === true) {
325
+ luvio.storeBroadcast();
326
+ }
327
+ instrumentation.timerMetricAddDuration(
328
+ ADS_BRIDGE_ADD_RECORDS_DURATION,
329
+ Date.now() - startTime
330
+ );
331
+ });
332
+ }
333
+
334
+ /**
335
+ * This method is invoked whenever a record has been evicted from ADS.
336
+ */
337
+ public evict(recordId: string): Promise<void> {
338
+ const startTime = Date.now();
339
+ const { luvio } = this;
340
+ const key = keyBuilderRecord(luvio, { recordId });
341
+ return this.lockLdsRecordEmit(() => {
342
+ luvio.storeEvict(key);
343
+ luvio.storeBroadcast();
344
+ instrumentation.timerMetricAddDuration(
345
+ ADS_BRIDGE_EVICT_DURATION,
346
+ Date.now() - startTime
347
+ );
348
+ return Promise.resolve();
349
+ });
350
+ }
351
+
352
+ /**
353
+ * Gets the list of fields of a record that Luvio has in its store. The field list doesn't
354
+ * contains the spanning record fields. ADS uses this list when it loads a record from the
355
+ * server. This is an optimization to make a single roundtrip it queries for all fields required
356
+ * by ADS and Luvio.
357
+ */
358
+ public getTrackedFieldsForRecord(recordId: string): Promise<string[]> {
359
+ const { luvio } = this;
360
+ const storeRecordId = keyBuilderRecord(luvio, { recordId });
361
+
362
+ const recordNode = luvio.getNode<RecordRepresentationNormalized, RecordRepresentation>(
363
+ storeRecordId
364
+ );
365
+
366
+ if (!isGraphNode(recordNode)) {
367
+ return Promise.resolve([]);
368
+ }
369
+
370
+ const apiName = recordNode.scalar('apiName');
371
+ const fieldNames = recordNode.object('fields').keys();
372
+
373
+ // Prefix all the fields with the record API name.
374
+ const qualifiedFieldNames: string[] = [];
375
+ for (let i = 0, len = fieldNames.length; i < len; i++) {
376
+ ArrayPrototypePush.call(qualifiedFieldNames, `${apiName}.${fieldNames[i]}`);
377
+ }
378
+
379
+ return Promise.resolve(qualifiedFieldNames);
380
+ }
381
+
382
+ /**
383
+ * Prevents the bridge to emit record change during the execution of the callback.
384
+ * This methods should wrap all the Luvio store mutation done by the bridge. It prevents Luvio store
385
+ * mutations triggered by ADS to be emit back to ADS.
386
+ */
387
+ private lockLdsRecordEmit<T>(callback: () => T): T {
388
+ this.isRecordEmitLocked = true;
389
+
390
+ try {
391
+ return callback();
392
+ } finally {
393
+ this.isRecordEmitLocked = false;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * This method retrieves queries the store with with passed record ids to retrieve their
399
+ * associated records and object info. Note that the passed ids are not Salesforce record id
400
+ * but rather Luvio internals store ids.
401
+ */
402
+ private emitRecordChanged(
403
+ updatedEntries: { id: string }[],
404
+ callback: LdsRecordChangedCallback
405
+ ): void {
406
+ const startTime = Date.now();
407
+ const { luvio } = this;
408
+ let shouldEmit = false;
409
+
410
+ const adsRecordMap: AdsRecordMap = {};
411
+ const adsObjectMap: AdsObjectMetadataMap = {};
412
+
413
+ for (let i = 0; i < updatedEntries.length; i++) {
414
+ const storeRecordId = updatedEntries[i].id;
415
+
416
+ // Exclude all the store record ids not matching with the record id pattern.
417
+ // Note: FieldValueRepresentation have the same prefix than RecordRepresentation so we
418
+ // need to filter them out.
419
+ if (!isStoreKeyRecordId(storeRecordId)) {
420
+ continue;
421
+ }
422
+
423
+ const record = getShallowRecord(luvio, storeRecordId);
424
+ if (record === null) {
425
+ continue;
426
+ }
427
+
428
+ // W-9978523
429
+ if (isDMOEntity(record) === true) {
430
+ continue;
431
+ }
432
+
433
+ const { id, apiName } = record;
434
+
435
+ shouldEmit = true;
436
+ adsRecordMap[id] = {
437
+ [apiName]: {
438
+ isPrimary: true,
439
+ record,
440
+ },
441
+ };
442
+
443
+ // Extract and add the object metadata to the map if not already present.
444
+ if (!ObjectPrototypeHasOwnProperty.call(adsObjectMap, apiName)) {
445
+ adsObjectMap[apiName] = getObjectMetadata(luvio, record);
446
+ }
447
+ }
448
+
449
+ if (shouldEmit === true) {
450
+ callback(adsRecordMap, adsObjectMap);
451
+ }
452
+ instrumentation.timerMetricAddDuration(
453
+ ADS_BRIDGE_EMIT_RECORD_CHANGED_DURATION,
454
+ Date.now() - startTime
455
+ );
456
+ }
457
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Instrumentation hooks exposed by this module.
3
+ */
4
+ export interface AdsBridgeInstrumentation {
5
+ /**
6
+ * Called at the end of execution for a function to track latency
7
+ * Current functions tracked: packages/lds-ads-bridge/src/utils/metric-keys.ts
8
+ */
9
+ timerMetricAddDuration?: (metricName: string, valueInMs: number) => void;
10
+ }
11
+
12
+ // For use by callers within this module to instrument interesting things.
13
+ export let instrumentation = {
14
+ timerMetricAddDuration: (_metricName: string, _valueInMs: number) => {},
15
+ };
16
+
17
+ /**
18
+ * Allows external modules (typically a runtime environment) to set
19
+ * instrumentation hooks for this module. Note that the hooks are
20
+ * incremental - hooks not suppiled in newInstrumentation will retain
21
+ * their previous values. The default instrumentation hooks are no-ops.
22
+ *
23
+ * @param newInstrumentation instrumentation hooks to be overridden
24
+ */
25
+ export function instrument(newInstrumentation: AdsBridgeInstrumentation) {
26
+ instrumentation = Object.assign(instrumentation, newInstrumentation);
27
+ }
package/src/main.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { Luvio } from '@luvio/engine';
2
+ import AdsBridge from './ads-bridge';
3
+
4
+ import { withDefaultLuvio } from '@salesforce/lds-default-luvio';
5
+
6
+ /**
7
+ * Callback used to inform interested parties that a new default Luvio has been set.
8
+ */
9
+ export type Callback = (adsBridge: AdsBridge) => void;
10
+
11
+ // most recently created AdsBridge
12
+ let adsBridge: AdsBridge;
13
+
14
+ // callbacks to be invoked when AdsBridge is set/changed
15
+ let callbacks: Callback[] = [];
16
+
17
+ // create a new AdsBridge whenever the default Luvio is set/changed
18
+ withDefaultLuvio((luvio: Luvio) => {
19
+ adsBridge = new AdsBridge(luvio);
20
+
21
+ for (let i = 0; i < callbacks.length; ++i) {
22
+ callbacks[i](adsBridge);
23
+ }
24
+ });
25
+
26
+ /**
27
+ * Registers a callback to be invoked with the AdsBridge instance. Note that the
28
+ * callback may be invoked multiple times if the default Luvio changes.
29
+ *
30
+ * @param callback callback to be invoked with the AdsBridge
31
+ */
32
+ export function withAdsBridge(callback: Callback) {
33
+ if (adsBridge) {
34
+ callback(adsBridge);
35
+ }
36
+ callbacks.push(callback);
37
+ }
38
+
39
+ // Expose module instrumentation
40
+ export { instrument, AdsBridgeInstrumentation } from './instrumentation';
@@ -0,0 +1,16 @@
1
+ const { push } = Array.prototype;
2
+ const { keys } = Object;
3
+ const { hasOwnProperty } = Object.prototype;
4
+ const { parse, stringify } = JSON;
5
+
6
+ export {
7
+ // Array.prototype
8
+ push as ArrayPrototypePush,
9
+ // Object
10
+ keys as ObjectKeys,
11
+ // Object.prototype
12
+ hasOwnProperty as ObjectPrototypeHasOwnProperty,
13
+ // JSON
14
+ parse as JSONParse,
15
+ stringify as JSONStringify,
16
+ };
@@ -0,0 +1,3 @@
1
+ export const ADS_BRIDGE_ADD_RECORDS_DURATION = 'ads-bridge-add-records-duration';
2
+ export const ADS_BRIDGE_EMIT_RECORD_CHANGED_DURATION = 'ads-bridge-emit-record-changed-duration';
3
+ export const ADS_BRIDGE_EVICT_DURATION = 'ads-bridge-evict-duration';
package/tsconfig.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "include": ["src"]
4
+ }