@salesforce/lds-drafts 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,1712 @@
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 { HttpStatusCode, StoreKeyMap } from '@luvio/engine';
8
+
9
+ var DraftActionStatus;
10
+ (function (DraftActionStatus) {
11
+ DraftActionStatus["Pending"] = "pending";
12
+ DraftActionStatus["Uploading"] = "uploading";
13
+ DraftActionStatus["Error"] = "error";
14
+ DraftActionStatus["Completed"] = "completed";
15
+ })(DraftActionStatus || (DraftActionStatus = {}));
16
+ function isDraftError(draft) {
17
+ return draft.status === DraftActionStatus.Error;
18
+ }
19
+ function isDraftQueueStateChangeEvent(event) {
20
+ return event.type === DraftQueueEventType.QueueStateChanged;
21
+ }
22
+ var ProcessActionResult;
23
+ (function (ProcessActionResult) {
24
+ // non-2xx network error, requires user intervention
25
+ ProcessActionResult["ACTION_ERRORED"] = "ERROR";
26
+ // upload succeeded
27
+ ProcessActionResult["ACTION_SUCCEEDED"] = "SUCCESS";
28
+ // queue is empty
29
+ ProcessActionResult["NO_ACTION_TO_PROCESS"] = "NO_ACTION_TO_PROCESS";
30
+ // network request is in flight
31
+ ProcessActionResult["ACTION_ALREADY_PROCESSING"] = "ACTION_ALREADY_PROCESSING";
32
+ // network call failed (offline)
33
+ ProcessActionResult["NETWORK_ERROR"] = "NETWORK_ERROR";
34
+ // queue is blocked on an error that requires user intervention
35
+ ProcessActionResult["BLOCKED_ON_ERROR"] = "BLOCKED_ON_ERROR";
36
+ //waiting for user to execute custom action
37
+ ProcessActionResult["CUSTOM_ACTION_WAITING"] = "CUSTOM_ACTION_WAITING";
38
+ })(ProcessActionResult || (ProcessActionResult = {}));
39
+ var DraftQueueState;
40
+ (function (DraftQueueState) {
41
+ /** Currently processing an item in the queue or queue is empty and waiting to process the next item. */
42
+ DraftQueueState["Started"] = "started";
43
+ /**
44
+ * The queue is stopped and will not attempt to upload any drafts until startDraftQueue() is called.
45
+ * This is the initial state when the DraftQueue gets instantiated.
46
+ */
47
+ DraftQueueState["Stopped"] = "stopped";
48
+ /**
49
+ * The queue is stopped due to a blocking error from the last upload attempt.
50
+ * The queue will not run again until startDraftQueue() is called.
51
+ */
52
+ DraftQueueState["Error"] = "error";
53
+ /**
54
+ * There was a network error and the queue will attempt to upload again shortly.
55
+ * To attempt to force an upload now call startDraftQueue().
56
+ */
57
+ DraftQueueState["Waiting"] = "waiting";
58
+ })(DraftQueueState || (DraftQueueState = {}));
59
+ var DraftQueueEventType;
60
+ (function (DraftQueueEventType) {
61
+ /**
62
+ * Triggered after an action had been added to the queue
63
+ */
64
+ DraftQueueEventType["ActionAdded"] = "added";
65
+ /**
66
+ * Triggered once an action failed
67
+ */
68
+ DraftQueueEventType["ActionFailed"] = "failed";
69
+ /**
70
+ * Triggered after an action has been deleted from the queue
71
+ */
72
+ DraftQueueEventType["ActionDeleted"] = "deleted";
73
+ /**
74
+ * Triggered after an action has been completed and after it has been removed from the queue
75
+ */
76
+ DraftQueueEventType["ActionCompleted"] = "completed";
77
+ /**
78
+ * Triggered after an action has been updated by the updateAction API
79
+ */
80
+ DraftQueueEventType["ActionUpdated"] = "updated";
81
+ /**
82
+ * Triggered after the Draft Queue state changes
83
+ */
84
+ DraftQueueEventType["QueueStateChanged"] = "state";
85
+ })(DraftQueueEventType || (DraftQueueEventType = {}));
86
+ var QueueOperationType;
87
+ (function (QueueOperationType) {
88
+ QueueOperationType["Add"] = "add";
89
+ QueueOperationType["Delete"] = "delete";
90
+ QueueOperationType["Update"] = "update";
91
+ })(QueueOperationType || (QueueOperationType = {}));
92
+
93
+ class DraftSynthesisError extends Error {
94
+ constructor(message, errorType) {
95
+ super(message);
96
+ this.errorType = errorType;
97
+ }
98
+ }
99
+ function isDraftSynthesisError(error) {
100
+ return error.errorType !== undefined;
101
+ }
102
+
103
+ const DRAFT_ERROR_CODE = 'DRAFT_ERROR';
104
+ class DraftFetchResponse {
105
+ constructor(status, body) {
106
+ this.headers = {};
107
+ this.status = status;
108
+ this.body = body;
109
+ }
110
+ get statusText() {
111
+ const { status } = this;
112
+ switch (status) {
113
+ case HttpStatusCode.Ok:
114
+ return 'OK';
115
+ case HttpStatusCode.Created:
116
+ return 'Created';
117
+ case HttpStatusCode.NoContent:
118
+ return 'No Content';
119
+ case HttpStatusCode.BadRequest:
120
+ return 'Bad Request';
121
+ case HttpStatusCode.ServerError:
122
+ return 'Server Error';
123
+ default:
124
+ return `Unexpected HTTP Status Code: ${status}`;
125
+ }
126
+ }
127
+ get ok() {
128
+ return this.status >= 200 && this.status < 300;
129
+ }
130
+ }
131
+ class DraftErrorFetchResponse {
132
+ constructor(status, body) {
133
+ this.ok = false;
134
+ this.headers = {};
135
+ this.errorType = 'fetchResponse';
136
+ this.status = status;
137
+ this.body = body;
138
+ }
139
+ get statusText() {
140
+ const { status } = this;
141
+ switch (status) {
142
+ case HttpStatusCode.BadRequest:
143
+ return 'Bad Request';
144
+ case HttpStatusCode.ServerError:
145
+ return 'Server Error';
146
+ case HttpStatusCode.NotFound:
147
+ return 'Not Found';
148
+ default:
149
+ return `Unexpected HTTP Status Code: ${status}`;
150
+ }
151
+ }
152
+ }
153
+ function createOkResponse(body) {
154
+ return new DraftFetchResponse(HttpStatusCode.Ok, body);
155
+ }
156
+ function createBadRequestResponse(body) {
157
+ return new DraftErrorFetchResponse(HttpStatusCode.BadRequest, body);
158
+ }
159
+ function createNotFoundResponse(body) {
160
+ return new DraftErrorFetchResponse(HttpStatusCode.NotFound, body);
161
+ }
162
+ function transformErrorToDraftSynthesisError(error) {
163
+ if (isDraftSynthesisError(error)) {
164
+ const { errorType, message } = error;
165
+ return createDraftSynthesisErrorResponse(message, errorType);
166
+ }
167
+ return createDraftSynthesisErrorResponse(error.message);
168
+ }
169
+ function createDraftSynthesisErrorResponse(message = 'failed to synthesize draft response', errorType) {
170
+ const error = {
171
+ errorCode: DRAFT_ERROR_CODE,
172
+ message: message,
173
+ };
174
+ if (errorType !== undefined) {
175
+ error.errorType = errorType;
176
+ }
177
+ return new DraftErrorFetchResponse(HttpStatusCode.BadRequest, error);
178
+ }
179
+ function createDeletedResponse() {
180
+ return new DraftFetchResponse(HttpStatusCode.NoContent, undefined);
181
+ }
182
+ function createInternalErrorResponse() {
183
+ return new DraftErrorFetchResponse(HttpStatusCode.ServerError, undefined);
184
+ }
185
+
186
+ const { keys, create, assign, values } = Object;
187
+ const { stringify, parse } = JSON;
188
+ const { isArray } = Array;
189
+
190
+ function buildLuvioOverrideForDraftAdapters(luvio, handler, extractTargetIdFromCacheKey, options = {}) {
191
+ // override this to create and enqueue a new draft action, and return synthetic response
192
+ const dispatchResourceRequest = async function (resourceRequest, _context) {
193
+ const action = await handler.enqueue(resourceRequest).catch((err) => {
194
+ throw transformErrorToDraftSynthesisError(err);
195
+ });
196
+ const record = await handler.getDataForAction(action);
197
+ if (record === undefined) {
198
+ return Promise.reject(createDraftSynthesisErrorResponse());
199
+ }
200
+ return createOkResponse(record);
201
+ };
202
+ // override this to use an infinitely large ttl so the cache entry never expires
203
+ const publishStoreMetadata = function (key, storeMetadataParams) {
204
+ // if we aren't publishing a draft then use base luvio method
205
+ const id = extractTargetIdFromCacheKey(key);
206
+ if (id === undefined || !handler.isDraftId(id)) {
207
+ return luvio.publishStoreMetadata(key, storeMetadataParams);
208
+ }
209
+ return luvio.publishStoreMetadata(key, {
210
+ ...storeMetadataParams,
211
+ ttl: Number.MAX_SAFE_INTEGER,
212
+ });
213
+ };
214
+ if (options.forDeleteAdapter === true) {
215
+ // delete adapters attempt to evict the record on successful network response,
216
+ // since draft-aware delete adapters do soft-delete (record stays in cache
217
+ // with a "drafts.deleted" property) we want storeEvict to just be a no-op
218
+ const storeEvict = function (_key) {
219
+ // no-op
220
+ };
221
+ return create(luvio, {
222
+ dispatchResourceRequest: { value: dispatchResourceRequest },
223
+ publishStoreMetadata: { value: publishStoreMetadata },
224
+ storeEvict: { value: storeEvict },
225
+ });
226
+ }
227
+ return create(luvio, {
228
+ dispatchResourceRequest: { value: dispatchResourceRequest },
229
+ publishStoreMetadata: { value: publishStoreMetadata },
230
+ });
231
+ }
232
+
233
+ const DraftIdMappingKeyPrefix240 = 'DraftIdMapping::';
234
+ const DraftKeyMappingKeyPrefix = 'DraftKeyMapping::V2::';
235
+ const DRAFT_ID_MAPPINGS_SEGMENT = 'DRAFT_ID_MAPPINGS';
236
+ function isLegacyDraftIdMapping(key, data) {
237
+ return key.startsWith(DraftIdMappingKeyPrefix240);
238
+ }
239
+ // TODO [W-11677776]: in 242 we changed the format to store keys instead of ids
240
+ // this can be removed when we drop support for id storing
241
+ function getRecordKeyForId(id) {
242
+ return `UiApi::RecordRepresentation:${id}`;
243
+ }
244
+ function generateDraftIdMappingKey(draftIdMapping) {
245
+ return `${DraftKeyMappingKeyPrefix}${draftIdMapping.draftKey}::${draftIdMapping.canonicalKey}`;
246
+ }
247
+ /**
248
+ *
249
+ * @param mappingIds (optional) requested mapping ids, if undefined all will be retrieved
250
+ */
251
+ async function getDraftIdMappings(durableStore, mappingIds) {
252
+ const mappings = [];
253
+ let durableStoreOperation;
254
+ if (mappingIds === undefined) {
255
+ durableStoreOperation =
256
+ durableStore.getAllEntries(DRAFT_ID_MAPPINGS_SEGMENT);
257
+ }
258
+ else {
259
+ durableStoreOperation = durableStore.getEntries(mappingIds, DRAFT_ID_MAPPINGS_SEGMENT);
260
+ }
261
+ const entries = await durableStoreOperation;
262
+ if (entries === undefined) {
263
+ return mappings;
264
+ }
265
+ const keys$1 = keys(entries);
266
+ for (const key of keys$1) {
267
+ const entry = entries[key].data;
268
+ if (isLegacyDraftIdMapping(key)) {
269
+ mappings.push({
270
+ draftKey: getRecordKeyForId(entry.draftId),
271
+ canonicalKey: getRecordKeyForId(entry.canonicalId),
272
+ });
273
+ }
274
+ else {
275
+ mappings.push(entry);
276
+ }
277
+ }
278
+ return mappings;
279
+ }
280
+
281
+ /**
282
+ * Generates a time-ordered, unique id to associate with a DraftAction. Ensures
283
+ * no collisions with existing draft action IDs.
284
+ */
285
+ function generateUniqueDraftActionId(existingIds) {
286
+ // new id in milliseconds with some extra digits for collisions
287
+ let newId = new Date().getTime() * 100;
288
+ const existingAsNumbers = existingIds
289
+ .map((id) => parseInt(id, 10))
290
+ .filter((parsed) => !isNaN(parsed));
291
+ let counter = 0;
292
+ while (existingAsNumbers.includes(newId)) {
293
+ newId += 1;
294
+ counter += 1;
295
+ // if the counter is 100+ then somehow this method has been called 100
296
+ // times in one millisecond
297
+ if (counter >= 100) {
298
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
299
+ throw new Error('Unable to generate unique new draft ID');
300
+ }
301
+ }
302
+ return newId.toString();
303
+ }
304
+
305
+ var CustomActionResultType;
306
+ (function (CustomActionResultType) {
307
+ CustomActionResultType["SUCCESS"] = "SUCCESS";
308
+ CustomActionResultType["FAILURE"] = "FAILURE";
309
+ })(CustomActionResultType || (CustomActionResultType = {}));
310
+ var CustomActionErrorType;
311
+ (function (CustomActionErrorType) {
312
+ CustomActionErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
313
+ CustomActionErrorType["CLIENT_ERROR"] = "CLIENT_ERROR";
314
+ })(CustomActionErrorType || (CustomActionErrorType = {}));
315
+ function isCustomActionSuccess(result) {
316
+ return result.type === CustomActionResultType.SUCCESS;
317
+ }
318
+ function isCustomActionFailed(result) {
319
+ return result.type === CustomActionResultType.FAILURE;
320
+ }
321
+ function customActionHandler(executor, id, draftQueue) {
322
+ const handle = (action, actionCompleted, actionErrored) => {
323
+ notifyCustomActionToExecute(action, actionCompleted, actionErrored);
324
+ return Promise.resolve(ProcessActionResult.CUSTOM_ACTION_WAITING);
325
+ };
326
+ const notifyCustomActionToExecute = (action, actionCompleted, actionErrored) => {
327
+ if (executor !== undefined) {
328
+ executor(action, executorCompleted(action, actionCompleted, actionErrored));
329
+ }
330
+ };
331
+ const executorCompleted = (action, actionCompleted, actionErrored) => (result) => {
332
+ if (isCustomActionSuccess(result)) {
333
+ actionCompleted({
334
+ ...action,
335
+ status: DraftActionStatus.Completed,
336
+ response: createOkResponse(undefined),
337
+ });
338
+ }
339
+ else if (isCustomActionFailed(result)) {
340
+ actionErrored({
341
+ ...action,
342
+ status: DraftActionStatus.Error,
343
+ error: result.error.message,
344
+ }, result.error.type === CustomActionErrorType.NETWORK_ERROR);
345
+ }
346
+ };
347
+ const buildPendingAction = (action, queue) => {
348
+ const { data, tag, targetId, handler } = action;
349
+ const id = generateUniqueDraftActionId(queue.map((a) => a.id));
350
+ return Promise.resolve({
351
+ id,
352
+ targetId,
353
+ status: DraftActionStatus.Pending,
354
+ data,
355
+ tag,
356
+ timestamp: Date.now(),
357
+ metadata: data,
358
+ handler,
359
+ });
360
+ };
361
+ const getQueueOperationsForCompletingDrafts = (_queue, action) => {
362
+ const { id } = action;
363
+ const queueOperations = [];
364
+ queueOperations.push({
365
+ type: QueueOperationType.Delete,
366
+ id: id,
367
+ });
368
+ return queueOperations;
369
+ };
370
+ const replaceAction = (actionId, _withActionId, _uploadingActionId, _actions) => {
371
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
372
+ throw new Error(`${actionId} does not support action replacing. You can only delete ${actionId}`);
373
+ };
374
+ const getRedirectMappings = (_action) => {
375
+ return undefined;
376
+ };
377
+ return {
378
+ handlerId: id,
379
+ enqueue: (data) => {
380
+ return draftQueue.enqueue(id, data);
381
+ },
382
+ handleAction: handle,
383
+ buildPendingAction,
384
+ getQueueOperationsForCompletingDrafts: getQueueOperationsForCompletingDrafts,
385
+ handleReplaceAction: replaceAction,
386
+ getRedirectMappings,
387
+ handleActionRemoved: () => Promise.resolve(),
388
+ handleActionCompleted: () => Promise.resolve(),
389
+ handleActionEnqueued: () => Promise.resolve(),
390
+ getDataForAction: () => Promise.resolve(undefined),
391
+ getDraftMetadata: () => {
392
+ throw Error('getDraftMetadata not supported for custom actions');
393
+ },
394
+ applyDraftsToIncomingData: () => {
395
+ throw Error('applyDraftsToIncomingData not supported for custom actions');
396
+ },
397
+ shouldDeleteActionByTagOnRemoval: () => false,
398
+ updateMetadata: (existing, incoming) => incoming,
399
+ canHandlePublish: () => false,
400
+ canRepresentationContainDraftMetadata: () => false,
401
+ mergeActions: () => {
402
+ throw Error('mergeActions not supported for custom actions');
403
+ },
404
+ };
405
+ }
406
+
407
+ const DRAFT_SEGMENT = 'DRAFT';
408
+ class DurableDraftQueue {
409
+ getHandler(id) {
410
+ const handler = this.handlers[id];
411
+ if (handler === undefined) {
412
+ throw Error(`No handler registered for ${id}`);
413
+ }
414
+ return handler;
415
+ }
416
+ constructor(draftStore) {
417
+ this.retryIntervalMilliseconds = 0;
418
+ this.minimumRetryInterval = 250;
419
+ this.maximumRetryInterval = 32000;
420
+ this.draftQueueChangedListeners = [];
421
+ this.state = DraftQueueState.Stopped;
422
+ this.userState = DraftQueueState.Stopped;
423
+ this.uploadingActionId = undefined;
424
+ this.timeoutHandler = undefined;
425
+ this.handlers = {};
426
+ this.draftStore = draftStore;
427
+ }
428
+ addHandler(handler) {
429
+ const id = handler.handlerId;
430
+ if (this.handlers[id] !== undefined) {
431
+ return Promise.reject(`Unable to add handler to id: ${id} because it already exists.`);
432
+ }
433
+ this.handlers[id] = handler;
434
+ return Promise.resolve();
435
+ }
436
+ removeHandler(id) {
437
+ delete this.handlers[id];
438
+ return Promise.resolve();
439
+ }
440
+ addCustomHandler(id, executor) {
441
+ const handler = customActionHandler(executor, id, this);
442
+ return this.addHandler(handler);
443
+ }
444
+ async getDataForAction(action) {
445
+ const handler = this.getHandler(action.handler);
446
+ return handler.getDataForAction(action);
447
+ }
448
+ getQueueState() {
449
+ return this.state;
450
+ }
451
+ async startQueue() {
452
+ this.userState = DraftQueueState.Started;
453
+ if (this.state === DraftQueueState.Started) {
454
+ // Do nothing if the queue state is already started
455
+ return Promise.resolve();
456
+ }
457
+ if (this.replacingAction !== undefined) {
458
+ // If we're replacing an action do nothing
459
+ // replace will restart the queue for us as long as the user
460
+ // has last set the queue to be started
461
+ return Promise.resolve();
462
+ }
463
+ this.retryIntervalMilliseconds = 0;
464
+ this.state = DraftQueueState.Started;
465
+ await this.notifyChangedListeners({
466
+ type: DraftQueueEventType.QueueStateChanged,
467
+ state: this.state,
468
+ });
469
+ const result = await this.processNextAction();
470
+ switch (result) {
471
+ case ProcessActionResult.BLOCKED_ON_ERROR:
472
+ this.state = DraftQueueState.Error;
473
+ return Promise.reject();
474
+ default:
475
+ return Promise.resolve();
476
+ }
477
+ }
478
+ stopQueue() {
479
+ this.userState = DraftQueueState.Stopped;
480
+ if (this.state === DraftQueueState.Stopped) {
481
+ // Do nothing if the queue state is already stopped
482
+ return Promise.resolve();
483
+ }
484
+ this.stopQueueManually();
485
+ return this.notifyChangedListeners({
486
+ type: DraftQueueEventType.QueueStateChanged,
487
+ state: DraftQueueState.Stopped,
488
+ });
489
+ }
490
+ /**
491
+ * Used to stop the queue within DraftQueue without user interaction
492
+ */
493
+ stopQueueManually() {
494
+ if (this.timeoutHandler) {
495
+ clearTimeout(this.timeoutHandler);
496
+ this.timeoutHandler = undefined;
497
+ }
498
+ this.state = DraftQueueState.Stopped;
499
+ }
500
+ async getQueueActions() {
501
+ const drafts = (await this.draftStore.getAllDrafts());
502
+ const queue = [];
503
+ if (drafts === undefined) {
504
+ return queue;
505
+ }
506
+ drafts.forEach((draft) => {
507
+ if (draft.id === this.uploadingActionId) {
508
+ draft.status = DraftActionStatus.Uploading;
509
+ }
510
+ queue.push(draft);
511
+ });
512
+ return queue.sort((a, b) => {
513
+ const aTime = parseInt(a.id, 10);
514
+ const bTime = parseInt(b.id, 10);
515
+ // safety check
516
+ if (isNaN(aTime)) {
517
+ return 1;
518
+ }
519
+ if (isNaN(bTime)) {
520
+ return -1;
521
+ }
522
+ return aTime - bTime;
523
+ });
524
+ }
525
+ async enqueue(handlerId, data) {
526
+ let queue = await this.getQueueActions();
527
+ const handler = this.getHandler(handlerId);
528
+ const pendingAction = (await handler.buildPendingAction(data, queue));
529
+ await this.draftStore.writeAction(pendingAction);
530
+ queue = await this.getQueueActions();
531
+ await this.notifyChangedListeners({
532
+ type: DraftQueueEventType.ActionAdded,
533
+ action: pendingAction,
534
+ });
535
+ await handler.handleActionEnqueued(pendingAction, queue);
536
+ if (this.state === DraftQueueState.Started) {
537
+ this.processNextAction();
538
+ }
539
+ return pendingAction;
540
+ }
541
+ registerOnChangedListener(listener) {
542
+ this.draftQueueChangedListeners.push(listener);
543
+ return () => {
544
+ this.draftQueueChangedListeners = this.draftQueueChangedListeners.filter((l) => {
545
+ return l !== listener;
546
+ });
547
+ return Promise.resolve();
548
+ };
549
+ }
550
+ async actionCompleted(action) {
551
+ const handler = this.getHandler(action.handler);
552
+ let queue = await this.getQueueActions();
553
+ const queueOperations = handler.getQueueOperationsForCompletingDrafts(queue, action);
554
+ const idAndKeyMappings = handler.getRedirectMappings(action);
555
+ const keyMappings = idAndKeyMappings === undefined
556
+ ? undefined
557
+ : idAndKeyMappings.map((m) => {
558
+ return { draftKey: m.draftKey, canonicalKey: m.canonicalKey };
559
+ });
560
+ await this.draftStore.completeAction(queueOperations, keyMappings);
561
+ queue = await this.getQueueActions();
562
+ this.retryIntervalMilliseconds = 0;
563
+ this.uploadingActionId = undefined;
564
+ await handler.handleActionCompleted(action, queueOperations, queue, values(this.handlers));
565
+ await this.notifyChangedListeners({
566
+ type: DraftQueueEventType.ActionCompleted,
567
+ action,
568
+ });
569
+ if (this.state === DraftQueueState.Started) {
570
+ this.processNextAction();
571
+ }
572
+ }
573
+ async actionFailed(action, retry) {
574
+ this.uploadingActionId = undefined;
575
+ if (retry && this.state !== DraftQueueState.Stopped) {
576
+ this.state = DraftQueueState.Waiting;
577
+ this.scheduleRetry();
578
+ }
579
+ else if (isDraftError(action)) {
580
+ return this.handleServerError(action, action.error);
581
+ }
582
+ }
583
+ handle(action) {
584
+ const handler = this.getHandler(action.handler);
585
+ if (handler === undefined) {
586
+ return Promise.reject(`No handler for ${action.handler}.`);
587
+ }
588
+ return handler.handleAction(action, this.actionCompleted.bind(this), this.actionFailed.bind(this));
589
+ }
590
+ async processNextAction() {
591
+ if (this.processingAction !== undefined) {
592
+ return this.processingAction;
593
+ }
594
+ const queue = await this.getQueueActions();
595
+ const action = queue[0];
596
+ if (action === undefined) {
597
+ this.processingAction = undefined;
598
+ return ProcessActionResult.NO_ACTION_TO_PROCESS;
599
+ }
600
+ const { status, id } = action;
601
+ if (status === DraftActionStatus.Error) {
602
+ this.state = DraftQueueState.Error;
603
+ this.processingAction = undefined;
604
+ return ProcessActionResult.BLOCKED_ON_ERROR;
605
+ }
606
+ if (id === this.uploadingActionId) {
607
+ this.state = DraftQueueState.Started;
608
+ this.processingAction = undefined;
609
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
610
+ }
611
+ this.uploadingActionId = id;
612
+ this.processingAction = undefined;
613
+ if (this.state === DraftQueueState.Waiting) {
614
+ this.state = DraftQueueState.Started;
615
+ }
616
+ return this.handle(action);
617
+ }
618
+ async handleServerError(action, error) {
619
+ const queue = await this.getQueueActions();
620
+ const localAction = queue.filter((qAction) => qAction.id === action.id)[0];
621
+ let newMetadata = {};
622
+ if (localAction !== undefined) {
623
+ newMetadata = localAction.metadata || {};
624
+ }
625
+ const errorAction = {
626
+ ...action,
627
+ status: DraftActionStatus.Error,
628
+ error,
629
+ metadata: newMetadata,
630
+ };
631
+ await this.draftStore.writeAction(errorAction);
632
+ this.state = DraftQueueState.Error;
633
+ return this.notifyChangedListeners({
634
+ type: DraftQueueEventType.ActionFailed,
635
+ action: errorAction,
636
+ });
637
+ }
638
+ async notifyChangedListeners(event) {
639
+ const results = [];
640
+ const { draftQueueChangedListeners } = this;
641
+ const { length: draftQueueLen } = draftQueueChangedListeners;
642
+ for (let i = 0; i < draftQueueLen; i++) {
643
+ const listener = draftQueueChangedListeners[i];
644
+ results.push(listener(event));
645
+ }
646
+ await Promise.all(results);
647
+ }
648
+ /**
649
+ * only starts the queue if user state is "Started" and if queue not already
650
+ * started
651
+ */
652
+ async startQueueSafe() {
653
+ if (this.userState === DraftQueueState.Started && this.state !== DraftQueueState.Started) {
654
+ await this.startQueue();
655
+ }
656
+ }
657
+ async removeDraftAction(actionId) {
658
+ const queue = await this.getQueueActions();
659
+ //Get the store key for the removed action
660
+ const actions = queue.filter((action) => action.id === actionId);
661
+ if (actions.length === 0) {
662
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
663
+ throw new Error(`No removable action with id ${actionId}`);
664
+ }
665
+ const action = actions[0];
666
+ if (action.id === this.uploadingActionId) {
667
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
668
+ throw new Error(`Cannot remove an uploading draft action with ID ${actionId}`);
669
+ }
670
+ const handler = this.getHandler(action.handler);
671
+ const shouldDeleteRelated = handler.shouldDeleteActionByTagOnRemoval(action);
672
+ if (shouldDeleteRelated) {
673
+ await this.draftStore.deleteByTag(action.tag);
674
+ }
675
+ else {
676
+ await this.draftStore.deleteDraft(action.id);
677
+ }
678
+ await handler.handleActionRemoved(action, queue.filter((x) => x.id !== actionId));
679
+ await this.notifyChangedListeners({
680
+ type: DraftQueueEventType.ActionDeleted,
681
+ action,
682
+ });
683
+ if (this.userState === DraftQueueState.Started &&
684
+ this.state !== DraftQueueState.Started &&
685
+ this.replacingAction === undefined) {
686
+ await this.startQueue();
687
+ }
688
+ }
689
+ replaceAction(actionId, withActionId) {
690
+ // ids must be unique
691
+ if (actionId === withActionId) {
692
+ return Promise.reject('Swapped and swapping action ids cannot be the same');
693
+ }
694
+ // cannot have a replace action already in progress
695
+ if (this.replacingAction !== undefined) {
696
+ return Promise.reject('Cannot replace actions while a replace action is in progress');
697
+ }
698
+ this.stopQueueManually();
699
+ const replacing = this.getQueueActions().then(async (actions) => {
700
+ const first = actions.filter((action) => action.id === actionId)[0];
701
+ if (first === undefined) {
702
+ this.replacingAction = undefined;
703
+ await this.startQueueSafe();
704
+ return Promise.reject('No action to replace');
705
+ }
706
+ const { actionToReplace, replacingAction } = this.getHandler(first.handler).handleReplaceAction(actionId, withActionId, this.uploadingActionId, actions);
707
+ // TODO [W-8873834]: Will add batching support to durable store
708
+ // we should use that here to remove and set both actions in one operation
709
+ await this.removeDraftAction(replacingAction.id);
710
+ await this.draftStore.writeAction(actionToReplace);
711
+ await this.notifyChangedListeners({
712
+ type: DraftQueueEventType.ActionUpdated,
713
+ action: actionToReplace,
714
+ });
715
+ this.replacingAction = undefined;
716
+ await this.startQueueSafe();
717
+ return actionToReplace;
718
+ });
719
+ this.replacingAction = replacing;
720
+ return replacing;
721
+ }
722
+ mergeAction(targetActionId, sourceActionId) {
723
+ // ids must be unique
724
+ if (targetActionId === sourceActionId) {
725
+ return Promise.reject(new Error('target and source action ids cannot be the same'));
726
+ }
727
+ // cannot have a replace action already in progress
728
+ if (this.replacingAction !== undefined) {
729
+ return Promise.reject(new Error('Cannot replace actions while a replace action is in progress'));
730
+ }
731
+ this.stopQueueManually();
732
+ const promise = this.getQueueActions().then(async (actions) => {
733
+ const target = actions.find((action) => action.id === targetActionId);
734
+ if (target === undefined) {
735
+ this.replacingAction = undefined;
736
+ await this.startQueueSafe();
737
+ throw Error('No action to replace');
738
+ }
739
+ const source = actions.find((action) => action.id === sourceActionId);
740
+ if (source === undefined) {
741
+ this.replacingAction = undefined;
742
+ await this.startQueueSafe();
743
+ throw Error('No action to replace');
744
+ }
745
+ const merged = this.getHandler(target.handler).mergeActions(target, source);
746
+ // update the target
747
+ await this.draftStore.writeAction(merged);
748
+ await this.notifyChangedListeners({
749
+ type: DraftQueueEventType.ActionUpdated,
750
+ action: merged,
751
+ });
752
+ // remove the source from queue
753
+ await this.removeDraftAction(sourceActionId);
754
+ this.replacingAction = undefined;
755
+ await this.startQueueSafe();
756
+ return merged;
757
+ });
758
+ this.replacingAction = promise;
759
+ return promise;
760
+ }
761
+ async setMetadata(actionId, metadata) {
762
+ const keys$1 = keys(metadata);
763
+ const compatibleKeys = keys$1.filter((key) => {
764
+ const value = metadata[key];
765
+ return typeof key === 'string' && typeof value === 'string';
766
+ });
767
+ if (keys$1.length !== compatibleKeys.length) {
768
+ return Promise.reject('Cannot save incompatible metadata');
769
+ }
770
+ const queue = await this.getQueueActions();
771
+ const actions = queue.filter((action) => action.id === actionId);
772
+ if (actions.length === 0) {
773
+ return Promise.reject('cannot save metadata to non-existent action');
774
+ }
775
+ const action = actions[0];
776
+ const handler = this.getHandler(action.handler);
777
+ action.metadata = handler.updateMetadata(action.metadata, metadata);
778
+ await this.draftStore.writeAction(action);
779
+ await this.notifyChangedListeners({
780
+ type: DraftQueueEventType.ActionUpdated,
781
+ action: action,
782
+ });
783
+ return action;
784
+ }
785
+ scheduleRetry() {
786
+ const newInterval = this.retryIntervalMilliseconds * 2;
787
+ this.retryIntervalMilliseconds = Math.min(Math.max(newInterval, this.minimumRetryInterval), this.maximumRetryInterval);
788
+ this.timeoutHandler = setTimeout(() => {
789
+ if (this.state !== DraftQueueState.Stopped) {
790
+ this.processNextAction();
791
+ }
792
+ }, this.retryIntervalMilliseconds);
793
+ }
794
+ }
795
+
796
+ const DRAFT_ACTION_KEY_JUNCTION = '__DraftAction__';
797
+ function buildDraftDurableStoreKey(recordKey, draftActionId) {
798
+ return `${recordKey}${DRAFT_ACTION_KEY_JUNCTION}${draftActionId}`;
799
+ }
800
+ /**
801
+ * Implements a write-through InMemoryStore for Drafts, storing all drafts in a
802
+ * in-memory store with a write through to the DurableStore.
803
+ *
804
+ * Before any reads or writes come in from the draft queue, we need to revive the draft
805
+ * queue into memory. During this initial revive, any writes are queued up and operated on the
806
+ * queue once it's in memory. Similarly any reads are delayed until the queue is in memory.
807
+ *
808
+ */
809
+ class DurableDraftStore {
810
+ constructor(durableStore) {
811
+ this.draftStore = {};
812
+ // queue of writes that were made during the initial sync
813
+ this.writeQueue = [];
814
+ this.durableStore = durableStore;
815
+ this.resyncDraftStore();
816
+ }
817
+ writeAction(action) {
818
+ const addAction = () => {
819
+ const { id, tag } = action;
820
+ this.draftStore[id] = action;
821
+ const durableEntryKey = buildDraftDurableStoreKey(tag, id);
822
+ const entry = {
823
+ data: action,
824
+ };
825
+ const entries = { [durableEntryKey]: entry };
826
+ return this.durableStore.setEntries(entries, DRAFT_SEGMENT);
827
+ };
828
+ return this.enqueueAction(addAction);
829
+ }
830
+ getAllDrafts() {
831
+ const waitForOngoingSync = this.syncPromise || Promise.resolve();
832
+ return waitForOngoingSync.then(() => {
833
+ const { draftStore } = this;
834
+ const keys$1 = keys(draftStore);
835
+ const actionArray = [];
836
+ for (let i = 0, len = keys$1.length; i < len; i++) {
837
+ const key = keys$1[i];
838
+ actionArray.push(draftStore[key]);
839
+ }
840
+ return actionArray;
841
+ });
842
+ }
843
+ deleteDraft(id) {
844
+ const deleteAction = () => {
845
+ const draft = this.draftStore[id];
846
+ if (draft !== undefined) {
847
+ delete this.draftStore[id];
848
+ const durableKey = buildDraftDurableStoreKey(draft.tag, draft.id);
849
+ return this.durableStore.evictEntries([durableKey], DRAFT_SEGMENT);
850
+ }
851
+ return Promise.resolve();
852
+ };
853
+ return this.enqueueAction(deleteAction);
854
+ }
855
+ deleteByTag(tag) {
856
+ const deleteAction = () => {
857
+ const { draftStore } = this;
858
+ const keys$1 = keys(draftStore);
859
+ const durableKeys = [];
860
+ for (let i = 0, len = keys$1.length; i < len; i++) {
861
+ const key = keys$1[i];
862
+ const action = draftStore[key];
863
+ if (action.tag === tag) {
864
+ delete draftStore[action.id];
865
+ durableKeys.push(buildDraftDurableStoreKey(action.tag, action.id));
866
+ }
867
+ }
868
+ return this.durableStore.evictEntries(durableKeys, DRAFT_SEGMENT);
869
+ };
870
+ return this.enqueueAction(deleteAction);
871
+ }
872
+ completeAction(queueOperations, mappings) {
873
+ const action = () => {
874
+ const durableStoreOperations = [];
875
+ const { draftStore } = this;
876
+ for (let i = 0, len = queueOperations.length; i < len; i++) {
877
+ const operation = queueOperations[i];
878
+ if (operation.type === QueueOperationType.Delete) {
879
+ const action = draftStore[operation.id];
880
+ if (action !== undefined) {
881
+ delete draftStore[operation.id];
882
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
883
+ durableStoreOperations.push({
884
+ ids: [key],
885
+ type: 'evictEntries',
886
+ segment: DRAFT_SEGMENT,
887
+ });
888
+ }
889
+ }
890
+ else {
891
+ const { action } = operation;
892
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
893
+ draftStore[action.id] = action;
894
+ durableStoreOperations.push({
895
+ type: 'setEntries',
896
+ segment: DRAFT_SEGMENT,
897
+ entries: {
898
+ [key]: {
899
+ data: operation.action,
900
+ },
901
+ },
902
+ });
903
+ }
904
+ }
905
+ if (mappings !== undefined) {
906
+ const entries = {};
907
+ for (const mapping of mappings) {
908
+ const mappingKey = generateDraftIdMappingKey(mapping);
909
+ entries[mappingKey] = { data: mapping };
910
+ }
911
+ durableStoreOperations.push({
912
+ entries,
913
+ type: 'setEntries',
914
+ segment: DRAFT_ID_MAPPINGS_SEGMENT,
915
+ });
916
+ }
917
+ return this.durableStore.batchOperations(durableStoreOperations);
918
+ };
919
+ return this.enqueueAction(action);
920
+ }
921
+ /**
922
+ * Runs a write operation against the draft store, if the initial
923
+ * revive is still in progress, the action gets enqueued to run once the
924
+ * initial revive is complete
925
+ * @param action
926
+ * @returns a promise that is resolved once the action has run
927
+ */
928
+ enqueueAction(action) {
929
+ const { syncPromise, writeQueue: pendingMerges } = this;
930
+ // if the initial sync is done and existing operations have been run, no need to queue, just run
931
+ if (syncPromise === undefined && pendingMerges.length === 0) {
932
+ return action();
933
+ }
934
+ const deferred = new Promise((resolve, reject) => {
935
+ this.writeQueue.push(() => {
936
+ return action()
937
+ .then((x) => {
938
+ resolve(x);
939
+ })
940
+ .catch((err) => reject(err));
941
+ });
942
+ });
943
+ return deferred;
944
+ }
945
+ /**
946
+ * Revives the draft store from the durable store. Once the draft store is
947
+ * revived, executes any queued up draft store operations that came in while
948
+ * reviving
949
+ */
950
+ resyncDraftStore() {
951
+ const sync = () => {
952
+ this.syncPromise = this.durableStore
953
+ .getAllEntries(DRAFT_SEGMENT)
954
+ .then((durableEntries) => {
955
+ if (durableEntries === undefined) {
956
+ this.draftStore = {};
957
+ return this.runQueuedOperations();
958
+ }
959
+ const { draftStore } = this;
960
+ const keys$1 = keys(durableEntries);
961
+ for (let i = 0, len = keys$1.length; i < len; i++) {
962
+ const entry = durableEntries[keys$1[i]];
963
+ const action = entry.data;
964
+ if (action !== undefined) {
965
+ if (process.env.NODE_ENV !== 'production') {
966
+ // the `version` property was introduced in 242, we should assert version
967
+ // exists once we are sure there are no durable stores that contain
968
+ // versionless actions
969
+ if (action.version && action.version !== '242.0.0') {
970
+ return Promise.reject('Unexpected draft action version found in the durable store');
971
+ }
972
+ }
973
+ draftStore[action.id] = action;
974
+ }
975
+ else {
976
+ if (process.env.NODE_ENV !== 'production') {
977
+ const err = new Error('Expected draft action to be defined in the durable store');
978
+ return Promise.reject(err);
979
+ }
980
+ }
981
+ }
982
+ return this.runQueuedOperations();
983
+ })
984
+ .finally(() => {
985
+ this.syncPromise = undefined;
986
+ });
987
+ return this.syncPromise;
988
+ };
989
+ // if there's an ongoing sync populating the in memory store, wait for it to complete before re-syncing
990
+ const { syncPromise } = this;
991
+ if (syncPromise === undefined) {
992
+ return sync();
993
+ }
994
+ return syncPromise.then(() => {
995
+ return sync();
996
+ });
997
+ }
998
+ /**
999
+ * Runs the operations that were queued up while reviving the
1000
+ * draft store from the durable store
1001
+ */
1002
+ runQueuedOperations() {
1003
+ const { writeQueue } = this;
1004
+ if (writeQueue.length > 0) {
1005
+ const queueItem = writeQueue.shift();
1006
+ if (queueItem !== undefined) {
1007
+ return queueItem().then(() => {
1008
+ return this.runQueuedOperations();
1009
+ });
1010
+ }
1011
+ }
1012
+ return Promise.resolve();
1013
+ }
1014
+ }
1015
+
1016
+ class AbstractResourceRequestActionHandler {
1017
+ constructor(draftQueue, networkAdapter, getLuvio) {
1018
+ this.draftQueue = draftQueue;
1019
+ this.networkAdapter = networkAdapter;
1020
+ this.getLuvio = getLuvio;
1021
+ }
1022
+ enqueue(data) {
1023
+ return this.draftQueue.enqueue(this.handlerId, data);
1024
+ }
1025
+ async handleAction(action, actionCompleted, actionErrored) {
1026
+ const { data: request } = action;
1027
+ // no context is stored in draft action
1028
+ try {
1029
+ const response = await this.networkAdapter(request, {});
1030
+ if (response.ok) {
1031
+ await actionCompleted({
1032
+ ...action,
1033
+ response,
1034
+ status: DraftActionStatus.Completed,
1035
+ });
1036
+ return ProcessActionResult.ACTION_SUCCEEDED;
1037
+ }
1038
+ await actionErrored({
1039
+ ...action,
1040
+ error: response,
1041
+ status: DraftActionStatus.Error,
1042
+ }, false);
1043
+ return ProcessActionResult.ACTION_ERRORED;
1044
+ }
1045
+ catch (_a) {
1046
+ await actionErrored(action, true);
1047
+ return ProcessActionResult.NETWORK_ERROR;
1048
+ }
1049
+ }
1050
+ async buildPendingAction(request, queue) {
1051
+ const targetId = await this.getIdFromRequest(request);
1052
+ if (targetId === undefined) {
1053
+ return Promise.reject(new Error('Cannot determine target id from the resource request'));
1054
+ }
1055
+ const tag = this.buildTagForTargetId(targetId);
1056
+ const handlerActions = queue.filter((x) => x.handler === this.handlerId);
1057
+ if (request.method === 'post' && actionsForTag(tag, handlerActions).length > 0) {
1058
+ return Promise.reject(new Error('Cannot enqueue a POST draft action with an existing tag'));
1059
+ }
1060
+ if (deleteActionsForTag(tag, handlerActions).length > 0) {
1061
+ return Promise.reject(new Error('Cannot enqueue a draft action for a deleted record'));
1062
+ }
1063
+ return {
1064
+ handler: this.handlerId,
1065
+ targetId,
1066
+ tag,
1067
+ data: request,
1068
+ status: DraftActionStatus.Pending,
1069
+ id: generateUniqueDraftActionId(queue.map((x) => x.id)),
1070
+ timestamp: Date.now(),
1071
+ metadata: {},
1072
+ version: '242.0.0',
1073
+ };
1074
+ }
1075
+ async handleActionEnqueued(action) {
1076
+ const { method } = action.data;
1077
+ // delete adapters don't get a value back to ingest so
1078
+ // we ingest it for them here
1079
+ if (method === 'delete') {
1080
+ await this.reingestRecord(action);
1081
+ }
1082
+ }
1083
+ handleActionRemoved(action) {
1084
+ return this.reingestRecord(action);
1085
+ }
1086
+ getQueueOperationsForCompletingDrafts(queue, action) {
1087
+ const queueOperations = [];
1088
+ if (action.data.method === 'post') {
1089
+ const { length } = queue;
1090
+ for (let i = 0; i < length; i++) {
1091
+ const queueAction = queue[i];
1092
+ // if this queueAction is the action that is completing we can move on,
1093
+ // it is about to be deleted and won't have the draft ID in it
1094
+ if (queueAction.id === action.id) {
1095
+ continue;
1096
+ }
1097
+ if (isResourceRequestAction(queueAction)) {
1098
+ const redirects = this.getRedirectMappings(action);
1099
+ if (redirects !== undefined) {
1100
+ let queueOperationMutated = false;
1101
+ let updatedActionTag = undefined;
1102
+ let updatedActionTargetId = undefined;
1103
+ const { tag: queueActionTag, data: queueActionRequest, id: queueActionId, } = queueAction;
1104
+ let { basePath, body } = queueActionRequest;
1105
+ let stringifiedBody = stringify(body);
1106
+ // for each redirected ID/key we loop over the operation to see if it needs
1107
+ // to be updated
1108
+ for (const { draftId, draftKey, canonicalId, canonicalKey } of redirects) {
1109
+ if (basePath.search(draftId) >= 0 ||
1110
+ stringifiedBody.search(draftId) >= 0) {
1111
+ basePath = basePath.replace(draftId, canonicalId);
1112
+ stringifiedBody = stringifiedBody.replace(draftId, canonicalId);
1113
+ queueOperationMutated = true;
1114
+ }
1115
+ // if the action is performed on a previous draft id, we need to replace the action
1116
+ // with a new one at the updated canonical key
1117
+ if (queueActionTag === draftKey) {
1118
+ updatedActionTag = canonicalKey;
1119
+ updatedActionTargetId = canonicalId;
1120
+ }
1121
+ }
1122
+ if (queueOperationMutated) {
1123
+ if (updatedActionTag !== undefined &&
1124
+ updatedActionTargetId !== undefined) {
1125
+ const updatedAction = {
1126
+ ...queueAction,
1127
+ tag: updatedActionTag,
1128
+ targetId: updatedActionTargetId,
1129
+ data: {
1130
+ ...queueActionRequest,
1131
+ basePath: basePath,
1132
+ body: parse(stringifiedBody),
1133
+ },
1134
+ };
1135
+ // item needs to be replaced with a new item at the new record key
1136
+ queueOperations.push({
1137
+ type: QueueOperationType.Delete,
1138
+ id: queueActionId,
1139
+ });
1140
+ queueOperations.push({
1141
+ type: QueueOperationType.Add,
1142
+ action: updatedAction,
1143
+ });
1144
+ }
1145
+ else {
1146
+ const updatedAction = {
1147
+ ...queueAction,
1148
+ data: {
1149
+ ...queueActionRequest,
1150
+ basePath: basePath,
1151
+ body: parse(stringifiedBody),
1152
+ },
1153
+ };
1154
+ // item needs to be updated
1155
+ queueOperations.push({
1156
+ type: QueueOperationType.Update,
1157
+ id: queueActionId,
1158
+ action: updatedAction,
1159
+ });
1160
+ }
1161
+ }
1162
+ }
1163
+ }
1164
+ }
1165
+ }
1166
+ // delete completed action
1167
+ queueOperations.push({
1168
+ type: QueueOperationType.Delete,
1169
+ id: action.id,
1170
+ });
1171
+ return queueOperations;
1172
+ }
1173
+ getRedirectMappings(action) {
1174
+ if (action.data.method !== 'post') {
1175
+ return undefined;
1176
+ }
1177
+ const body = action.response.body;
1178
+ const canonicalId = this.getIdFromResponseBody(body);
1179
+ const draftId = action.targetId;
1180
+ return [
1181
+ {
1182
+ draftId,
1183
+ canonicalId,
1184
+ draftKey: this.buildTagForTargetId(draftId),
1185
+ canonicalKey: this.buildTagForTargetId(canonicalId),
1186
+ },
1187
+ ];
1188
+ }
1189
+ async handleActionCompleted(action, queueOperations, _queue, allHandlers) {
1190
+ const { data: request, tag } = action;
1191
+ const { method } = request;
1192
+ if (method === 'delete') {
1193
+ return this.evictKey(tag);
1194
+ }
1195
+ const recordsToIngest = [];
1196
+ recordsToIngest.push({
1197
+ response: action.response.body,
1198
+ synchronousIngest: this.synchronousIngest.bind(this),
1199
+ buildCacheKeysForResponse: this.buildCacheKeysFromResponse.bind(this),
1200
+ });
1201
+ const recordsNeedingReplay = queueOperations.filter((x) => x.type === QueueOperationType.Update);
1202
+ for (const recordNeedingReplay of recordsNeedingReplay) {
1203
+ const { action } = recordNeedingReplay;
1204
+ if (isResourceRequestAction(action)) {
1205
+ // We can't assume the queue operation is for our handler, have to find the handler.
1206
+ const handler = allHandlers.find((h) => h.handlerId === action.handler);
1207
+ if (handler !== undefined) {
1208
+ const record = await handler.getDataForAction(action);
1209
+ if (record !== undefined) {
1210
+ recordsToIngest.push({
1211
+ response: record,
1212
+ synchronousIngest: handler.synchronousIngest.bind(handler),
1213
+ buildCacheKeysForResponse: handler.buildCacheKeysFromResponse.bind(handler),
1214
+ });
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ await this.ingestResponses(recordsToIngest, action);
1220
+ }
1221
+ handleReplaceAction(actionId, withActionId, uploadingActionId, actions) {
1222
+ // get the action to replace
1223
+ const actionToReplace = actions.filter((action) => action.id === actionId)[0];
1224
+ // get the replacing action
1225
+ const replacingAction = actions.filter((action) => action.id === withActionId)[0];
1226
+ // reject if either action is undefined
1227
+ if (actionToReplace === undefined || replacingAction === undefined) {
1228
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1229
+ throw new Error('One or both actions does not exist');
1230
+ }
1231
+ // reject if either action is uploading
1232
+ if (actionToReplace.id === uploadingActionId || replacingAction.id === uploadingActionId) {
1233
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1234
+ throw new Error('Cannot replace an draft action that is uploading');
1235
+ }
1236
+ // reject if these two draft actions aren't acting on the same target
1237
+ if (actionToReplace.tag !== replacingAction.tag) {
1238
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1239
+ throw new Error('Cannot swap actions targeting different targets');
1240
+ }
1241
+ // reject if the replacing action is not pending
1242
+ if (replacingAction.status !== DraftActionStatus.Pending) {
1243
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1244
+ throw new Error('Cannot replace with a non-pending action');
1245
+ }
1246
+ //reject if the action to replace is a POST action
1247
+ const pendingAction = actionToReplace;
1248
+ if (pendingAction.data.method === 'post') {
1249
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1250
+ throw new Error('Cannot replace a POST action');
1251
+ }
1252
+ if (this.isActionOfType(actionToReplace) &&
1253
+ this.isActionOfType(replacingAction)) {
1254
+ const actionToReplaceCopy = {
1255
+ ...actionToReplace,
1256
+ status: DraftActionStatus.Pending,
1257
+ };
1258
+ actionToReplace.status = DraftActionStatus.Pending;
1259
+ actionToReplace.data = replacingAction.data;
1260
+ return {
1261
+ original: actionToReplaceCopy,
1262
+ actionToReplace: actionToReplace,
1263
+ replacingAction: replacingAction,
1264
+ };
1265
+ }
1266
+ else {
1267
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1268
+ throw new Error('Incompatible Action types to replace one another');
1269
+ }
1270
+ }
1271
+ shouldDeleteActionByTagOnRemoval(action) {
1272
+ return action.data.method === 'post';
1273
+ }
1274
+ updateMetadata(_existingMetadata, incomingMetadata) {
1275
+ return incomingMetadata;
1276
+ }
1277
+ isActionOfType(action) {
1278
+ return action.handler === this.handlerId;
1279
+ }
1280
+ async reingestRecord(action) {
1281
+ const record = await this.getDataForAction(action);
1282
+ if (record !== undefined) {
1283
+ await this.ingestResponses([
1284
+ {
1285
+ response: record,
1286
+ synchronousIngest: this.synchronousIngest.bind(this),
1287
+ buildCacheKeysForResponse: this.buildCacheKeysFromResponse.bind(this),
1288
+ },
1289
+ ], action);
1290
+ }
1291
+ else {
1292
+ await this.evictKey(action.tag);
1293
+ }
1294
+ }
1295
+ // Given an action for this handler this method should return the draft IDs.
1296
+ // Most of the time it will simply be the targetId, but certain handlers might
1297
+ // have multiple draft-created IDs so they would override this to return them.
1298
+ getDraftIdsFromAction(action) {
1299
+ return [action.targetId];
1300
+ }
1301
+ async ingestResponses(responses, action) {
1302
+ const luvio = this.getLuvio();
1303
+ await luvio.handleSuccessResponse(() => {
1304
+ for (const entry of responses) {
1305
+ const { response, synchronousIngest } = entry;
1306
+ synchronousIngest(response, action);
1307
+ }
1308
+ // ingestAndBroadcastFunction can return Promise<void>, that's easiest
1309
+ // to return since it's unused in this function
1310
+ return Promise.resolve();
1311
+ },
1312
+ // getTypeCacheKeysRecord uses the response, not the full path factory
1313
+ // so 2nd parameter will be unused
1314
+ () => {
1315
+ const keySet = new StoreKeyMap();
1316
+ for (const entry of responses) {
1317
+ const { response, buildCacheKeysForResponse } = entry;
1318
+ const set = buildCacheKeysForResponse(response);
1319
+ for (const key of set.keys()) {
1320
+ const value = set.get(key);
1321
+ if (value !== undefined) {
1322
+ keySet.set(key, value);
1323
+ }
1324
+ }
1325
+ }
1326
+ return keySet;
1327
+ });
1328
+ }
1329
+ async evictKey(key) {
1330
+ const luvio = this.getLuvio();
1331
+ await luvio.handleSuccessResponse(() => {
1332
+ luvio.storeEvict(key);
1333
+ return luvio.storeBroadcast();
1334
+ }, () => {
1335
+ return new StoreKeyMap();
1336
+ });
1337
+ }
1338
+ }
1339
+ function actionsForTag(tag, queue) {
1340
+ return queue.filter((action) => action.tag === tag);
1341
+ }
1342
+ function deleteActionsForTag(tag, queue) {
1343
+ return queue.filter((action) => action.tag === tag && action.data.method === 'delete');
1344
+ }
1345
+ function isResourceRequestAction(action) {
1346
+ const dataAsAny = action.data;
1347
+ return (dataAsAny !== undefined && dataAsAny.method !== undefined && dataAsAny.body !== undefined);
1348
+ }
1349
+
1350
+ /**
1351
+ * Denotes what kind of operation a DraftQueueItem represents.
1352
+ */
1353
+ var DraftActionOperationType;
1354
+ (function (DraftActionOperationType) {
1355
+ DraftActionOperationType["Create"] = "create";
1356
+ DraftActionOperationType["Update"] = "update";
1357
+ DraftActionOperationType["Delete"] = "delete";
1358
+ DraftActionOperationType["Custom"] = "custom";
1359
+ })(DraftActionOperationType || (DraftActionOperationType = {}));
1360
+ var DraftQueueOperationType;
1361
+ (function (DraftQueueOperationType) {
1362
+ DraftQueueOperationType["ItemAdded"] = "added";
1363
+ DraftQueueOperationType["ItemDeleted"] = "deleted";
1364
+ DraftQueueOperationType["ItemCompleted"] = "completed";
1365
+ DraftQueueOperationType["ItemFailed"] = "failed";
1366
+ DraftQueueOperationType["ItemUpdated"] = "updated";
1367
+ DraftQueueOperationType["QueueStarted"] = "started";
1368
+ DraftQueueOperationType["QueueStopped"] = "stopped";
1369
+ })(DraftQueueOperationType || (DraftQueueOperationType = {}));
1370
+ /**
1371
+ * Converts the internal DraftAction's ResourceRequest into
1372
+ * a DraftActionOperationType.
1373
+ * Returns a DraftActionOperationType as long as the http request is a
1374
+ * valid method type for DraftQueue or else it is undefined.
1375
+ * @param action
1376
+ */
1377
+ function getOperationTypeFrom(action) {
1378
+ if (isResourceRequestAction(action)) {
1379
+ if (action.data !== undefined && action.data.method !== undefined) {
1380
+ switch (action.data.method) {
1381
+ case 'put':
1382
+ case 'patch':
1383
+ return DraftActionOperationType.Update;
1384
+ case 'post':
1385
+ return DraftActionOperationType.Create;
1386
+ case 'delete':
1387
+ return DraftActionOperationType.Delete;
1388
+ default:
1389
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1390
+ throw new Error(`${action.data.method} is an unsupported request method type for DraftQueue.`);
1391
+ }
1392
+ }
1393
+ else {
1394
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1395
+ throw new Error(`action has no data found`);
1396
+ }
1397
+ }
1398
+ else {
1399
+ return DraftActionOperationType.Custom;
1400
+ }
1401
+ }
1402
+ function toQueueState(queue) {
1403
+ return (states) => {
1404
+ return {
1405
+ queueState: queue.getQueueState(),
1406
+ items: states,
1407
+ };
1408
+ };
1409
+ }
1410
+ class DraftManager {
1411
+ constructor(draftQueue) {
1412
+ this.listeners = [];
1413
+ this.draftQueue = draftQueue;
1414
+ draftQueue.registerOnChangedListener((event) => {
1415
+ if (this.shouldEmitDraftEvent(event)) {
1416
+ return this.callListeners(event);
1417
+ }
1418
+ return Promise.resolve();
1419
+ });
1420
+ }
1421
+ shouldEmitDraftEvent(event) {
1422
+ const { type } = event;
1423
+ return [
1424
+ DraftQueueEventType.ActionAdded,
1425
+ DraftQueueEventType.ActionCompleted,
1426
+ DraftQueueEventType.ActionDeleted,
1427
+ DraftQueueEventType.ActionFailed,
1428
+ DraftQueueEventType.ActionUpdated,
1429
+ DraftQueueEventType.QueueStateChanged,
1430
+ ].includes(type);
1431
+ }
1432
+ draftQueueEventTypeToOperationType(type) {
1433
+ switch (type) {
1434
+ case DraftQueueEventType.ActionAdded:
1435
+ return DraftQueueOperationType.ItemAdded;
1436
+ case DraftQueueEventType.ActionCompleted:
1437
+ return DraftQueueOperationType.ItemCompleted;
1438
+ case DraftQueueEventType.ActionDeleted:
1439
+ return DraftQueueOperationType.ItemDeleted;
1440
+ case DraftQueueEventType.ActionFailed:
1441
+ return DraftQueueOperationType.ItemFailed;
1442
+ case DraftQueueEventType.ActionUpdated:
1443
+ return DraftQueueOperationType.ItemUpdated;
1444
+ default:
1445
+ throw Error('Unsupported event type');
1446
+ }
1447
+ }
1448
+ draftQueueStateToOperationType(state) {
1449
+ switch (state) {
1450
+ case DraftQueueState.Started:
1451
+ return DraftQueueOperationType.QueueStarted;
1452
+ case DraftQueueState.Stopped:
1453
+ return DraftQueueOperationType.QueueStopped;
1454
+ default:
1455
+ throw Error('Unsupported event type');
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Enqueue a custom action on the DraftQueue for a handler
1460
+ * @param handler the handler's id
1461
+ * @param targetId
1462
+ * @param tag - the key to group with in durable store
1463
+ * @param metadata
1464
+ * @returns
1465
+ */
1466
+ addCustomAction(handler, targetId, tag, metadata) {
1467
+ return this.draftQueue
1468
+ .enqueue(handler, {
1469
+ data: metadata,
1470
+ handler,
1471
+ targetId,
1472
+ tag,
1473
+ })
1474
+ .then(this.buildDraftQueueItem);
1475
+ }
1476
+ /**
1477
+ * Get the current state of each of the DraftActions in the DraftQueue
1478
+ * @returns A promise of an array of the state of each item in the DraftQueue
1479
+ */
1480
+ getQueue() {
1481
+ return this.draftQueue
1482
+ .getQueueActions()
1483
+ .then((queueActions) => {
1484
+ return queueActions.map(this.buildDraftQueueItem);
1485
+ })
1486
+ .then(toQueueState(this.draftQueue));
1487
+ }
1488
+ /**
1489
+ * Starts the draft queue and begins processing the first item in the queue.
1490
+ */
1491
+ startQueue() {
1492
+ return this.draftQueue.startQueue();
1493
+ }
1494
+ /**
1495
+ * Stops the draft queue from processing more draft items after any current
1496
+ * in progress items are finished.
1497
+ */
1498
+ stopQueue() {
1499
+ return this.draftQueue.stopQueue();
1500
+ }
1501
+ /**
1502
+ * Subscribes the listener to changes to the draft queue.
1503
+ *
1504
+ * Returns a closure to invoke in order to unsubscribe the listener
1505
+ * from changes to the draft queue.
1506
+ *
1507
+ * @param listener The listener closure to subscribe to changes
1508
+ */
1509
+ registerDraftQueueChangedListener(listener) {
1510
+ this.listeners.push(listener);
1511
+ return () => {
1512
+ this.listeners = this.listeners.filter((l) => {
1513
+ return l !== listener;
1514
+ });
1515
+ return Promise.resolve();
1516
+ };
1517
+ }
1518
+ /**
1519
+ * Creates a custom action handler for the given handler
1520
+ * @param handlerId
1521
+ * @param executor
1522
+ * @returns
1523
+ */
1524
+ setCustomActionExecutor(handlerId, executor) {
1525
+ return this.draftQueue
1526
+ .addCustomHandler(handlerId, (action, completed) => {
1527
+ executor(this.buildDraftQueueItem(action), completed);
1528
+ })
1529
+ .then(() => {
1530
+ return () => {
1531
+ this.draftQueue.removeHandler(handlerId);
1532
+ return Promise.resolve();
1533
+ };
1534
+ });
1535
+ }
1536
+ buildDraftQueueItem(action) {
1537
+ const operationType = getOperationTypeFrom(action);
1538
+ const { id, status, timestamp, targetId, metadata } = action;
1539
+ const item = {
1540
+ id,
1541
+ targetId,
1542
+ state: status,
1543
+ timestamp,
1544
+ operationType,
1545
+ metadata,
1546
+ };
1547
+ if (isDraftError(action)) {
1548
+ // We should always return an array, if the body is just a dictionary,
1549
+ // stick it in an array
1550
+ const body = isArray(action.error.body) ? action.error.body : [action.error.body];
1551
+ const bodyString = stringify(body);
1552
+ item.error = {
1553
+ status: action.error.status || 0,
1554
+ ok: action.error.ok || false,
1555
+ headers: action.error.headers || {},
1556
+ statusText: action.error.statusText || '',
1557
+ bodyString,
1558
+ };
1559
+ }
1560
+ return item;
1561
+ }
1562
+ async callListeners(event) {
1563
+ if (this.listeners.length < 1) {
1564
+ return;
1565
+ }
1566
+ const managerState = await this.getQueue();
1567
+ let operationType, item;
1568
+ if (isDraftQueueStateChangeEvent(event)) {
1569
+ operationType = this.draftQueueStateToOperationType(event.state);
1570
+ }
1571
+ else {
1572
+ const { action, type } = event;
1573
+ item = this.buildDraftQueueItem(action);
1574
+ operationType = this.draftQueueEventTypeToOperationType(type);
1575
+ }
1576
+ for (let i = 0, len = this.listeners.length; i < len; i++) {
1577
+ const listener = this.listeners[i];
1578
+ listener(managerState, operationType, item);
1579
+ }
1580
+ }
1581
+ /**
1582
+ * Removes the draft action identified by actionId from the draft queue.
1583
+ *
1584
+ * @param actionId The action identifier
1585
+ *
1586
+ * @returns The current state of the draft queue
1587
+ */
1588
+ removeDraftAction(actionId) {
1589
+ return this.draftQueue.removeDraftAction(actionId).then(() => this.getQueue());
1590
+ }
1591
+ /**
1592
+ * Replaces the resource request of `withAction` for the resource request
1593
+ * of `actionId`. Action ids cannot be equal. Both actions must be acting
1594
+ * on the same target object, and neither can currently be in progress.
1595
+ *
1596
+ * @param actionId The id of the draft action to replace
1597
+ * @param withActionId The id of the draft action that will replace the other
1598
+ */
1599
+ replaceAction(actionId, withActionId) {
1600
+ return this.draftQueue.replaceAction(actionId, withActionId).then((replaced) => {
1601
+ return this.buildDraftQueueItem(replaced);
1602
+ });
1603
+ }
1604
+ /**
1605
+ * Merges two actions into a single target action. The target action maintains
1606
+ * its position in the queue, while the source action is removed from the queue.
1607
+ * Action ids cannot be equal. Both actions must be acting on the same target
1608
+ * object, and neither can currently be in progress.
1609
+ *
1610
+ * @param targetActionId The draft action id of the target action. This action
1611
+ * will be replaced with the merged result.
1612
+ * @param sourceActionId The draft action id to merge onto the target. This
1613
+ * action will be removed after the merge.
1614
+ */
1615
+ mergeAction(targetActionId, sourceActionId) {
1616
+ return this.draftQueue.mergeAction(targetActionId, sourceActionId).then((merged) => {
1617
+ return this.buildDraftQueueItem(merged);
1618
+ });
1619
+ }
1620
+ /**
1621
+ * Sets the metadata object of the specified action to the
1622
+ * provided metadata
1623
+ * @param actionId The id of the action to set the metadata on
1624
+ * @param metadata The metadata to set on the specified action
1625
+ */
1626
+ setMetadata(actionId, metadata) {
1627
+ return this.draftQueue.setMetadata(actionId, metadata).then((updatedAction) => {
1628
+ return this.buildDraftQueueItem(updatedAction);
1629
+ });
1630
+ }
1631
+ }
1632
+
1633
+ function makeEnvironmentDraftAware(luvio, env, durableStore, handlers, draftQueue) {
1634
+ let draftMetadata = null;
1635
+ // setup existing store redirects when bootstrapping the environment
1636
+ (async () => {
1637
+ const mappings = await getDraftIdMappings(durableStore);
1638
+ mappings.forEach((mapping) => {
1639
+ const { draftKey, canonicalKey } = mapping;
1640
+ env.storeRedirect(draftKey, canonicalKey);
1641
+ });
1642
+ })();
1643
+ durableStore.registerOnChangedListener(async (changes) => {
1644
+ const draftIdMappingsIds = [];
1645
+ for (let i = 0, len = changes.length; i < len; i++) {
1646
+ const change = changes[i];
1647
+ if (change.segment === DRAFT_ID_MAPPINGS_SEGMENT) {
1648
+ draftIdMappingsIds.push(...change.ids);
1649
+ }
1650
+ }
1651
+ if (draftIdMappingsIds.length > 0) {
1652
+ const mappings = await getDraftIdMappings(durableStore, draftIdMappingsIds);
1653
+ mappings.forEach((mapping) => {
1654
+ const { draftKey, canonicalKey } = mapping;
1655
+ env.storeRedirect(draftKey, canonicalKey);
1656
+ });
1657
+ }
1658
+ });
1659
+ const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
1660
+ const queue = await draftQueue.getQueueActions();
1661
+ if (queue.length === 0) {
1662
+ return env.handleSuccessResponse(ingestAndBroadcastFunc, getResponseCacheKeysFunc);
1663
+ }
1664
+ const ingestMetadata = {};
1665
+ const cacheKeySet = getResponseCacheKeysFunc();
1666
+ for (const possibleKey of cacheKeySet.keys()) {
1667
+ const key = typeof possibleKey === 'string' ? possibleKey : '';
1668
+ const cacheKey = cacheKeySet.get(key);
1669
+ for (const handler of handlers) {
1670
+ if (cacheKey !== undefined &&
1671
+ handler.canRepresentationContainDraftMetadata(cacheKey.representationName)) {
1672
+ const metadata = await handler.getDraftMetadata(key);
1673
+ if (metadata !== undefined) {
1674
+ // if this key is related to a draft then mark it mergeable so
1675
+ // base environment revives it to staging store before ingestion
1676
+ cacheKey.mergeable = true;
1677
+ ingestMetadata[key] = metadata;
1678
+ }
1679
+ break;
1680
+ }
1681
+ }
1682
+ }
1683
+ draftMetadata = keys(ingestMetadata).length > 0 ? ingestMetadata : null;
1684
+ return env.handleSuccessResponse(ingestAndBroadcastFunc, () => cacheKeySet);
1685
+ };
1686
+ const storePublish = function (key, data) {
1687
+ if (draftMetadata === null) {
1688
+ // no drafts for this response
1689
+ return env.storePublish(key, data);
1690
+ }
1691
+ for (const handler of handlers) {
1692
+ if (handler.canHandlePublish(key)) {
1693
+ handler.applyDraftsToIncomingData(key, data, draftMetadata[key], env.storePublish);
1694
+ return;
1695
+ }
1696
+ }
1697
+ // no handler could handle it so publish
1698
+ env.storePublish(key, data);
1699
+ };
1700
+ const storeBroadcast = function (rebuildSnapshot, snapshotAvailable) {
1701
+ draftMetadata = create(null);
1702
+ return env.storeBroadcast(rebuildSnapshot, snapshotAvailable);
1703
+ };
1704
+ // note the makeEnvironmentUiApiRecordDraftAware will eventually go away once the adapters become draft aware
1705
+ return create(env, {
1706
+ storePublish: { value: storePublish },
1707
+ storeBroadcast: { value: storeBroadcast },
1708
+ handleSuccessResponse: { value: handleSuccessResponse },
1709
+ });
1710
+ }
1711
+
1712
+ export { AbstractResourceRequestActionHandler, CustomActionResultType, DRAFT_ERROR_CODE, DRAFT_ID_MAPPINGS_SEGMENT, DRAFT_SEGMENT, DraftActionOperationType, DraftActionStatus, DraftErrorFetchResponse, DraftFetchResponse, DraftManager, DraftQueueEventType, DraftQueueState, DraftSynthesisError, DurableDraftQueue, DurableDraftStore, ProcessActionResult, buildLuvioOverrideForDraftAdapters, createBadRequestResponse, createDeletedResponse, createDraftSynthesisErrorResponse, createInternalErrorResponse, createNotFoundResponse, createOkResponse, generateUniqueDraftActionId, isDraftSynthesisError, makeEnvironmentDraftAware, transformErrorToDraftSynthesisError };