@warp-drive-mirror/json-api 5.6.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/LICENSE.md +23 -0
  3. package/README.md +54 -0
  4. package/addon-main.cjs +5 -0
  5. package/declarations/-private/cache.d.ts +514 -0
  6. package/declarations/-private/cache.d.ts.map +1 -0
  7. package/declarations/-private/validate-document-fields.d.ts +4 -0
  8. package/declarations/-private/validate-document-fields.d.ts.map +1 -0
  9. package/declarations/-private/validator/1.1/7.1_top-level-document-members.d.ts +13 -0
  10. package/declarations/-private/validator/1.1/7.1_top-level-document-members.d.ts.map +1 -0
  11. package/declarations/-private/validator/1.1/7.2_resource-objects.d.ts +14 -0
  12. package/declarations/-private/validator/1.1/7.2_resource-objects.d.ts.map +1 -0
  13. package/declarations/-private/validator/1.1/links.d.ts +24 -0
  14. package/declarations/-private/validator/1.1/links.d.ts.map +1 -0
  15. package/declarations/-private/validator/index.d.ts +5 -0
  16. package/declarations/-private/validator/index.d.ts.map +1 -0
  17. package/declarations/-private/validator/utils.d.ts +76 -0
  18. package/declarations/-private/validator/utils.d.ts.map +1 -0
  19. package/declarations/index.d.ts +85 -0
  20. package/declarations/index.d.ts.map +1 -0
  21. package/dist/index.js +3157 -0
  22. package/dist/index.js.map +1 -0
  23. package/logos/NCC-1701-a-blue.svg +4 -0
  24. package/logos/NCC-1701-a-gold.svg +4 -0
  25. package/logos/NCC-1701-a-gold_100.svg +1 -0
  26. package/logos/NCC-1701-a-gold_base-64.txt +1 -0
  27. package/logos/NCC-1701-a.svg +4 -0
  28. package/logos/README.md +4 -0
  29. package/logos/docs-badge.svg +2 -0
  30. package/logos/ember-data-logo-dark.svg +12 -0
  31. package/logos/ember-data-logo-light.svg +12 -0
  32. package/logos/github-header.svg +444 -0
  33. package/logos/social1.png +0 -0
  34. package/logos/social2.png +0 -0
  35. package/logos/warp-drive-logo-dark.svg +4 -0
  36. package/logos/warp-drive-logo-gold.svg +4 -0
  37. package/package.json +71 -0
package/dist/index.js ADDED
@@ -0,0 +1,3157 @@
1
+ import { graphFor, peekGraph, isBelongsTo } from '@warp-drive-mirror/core/graph/-private';
2
+ import { logGroup, isStableIdentifier, isDocumentIdentifier } from '@warp-drive-mirror/core/store/-private';
3
+ import Fuse from 'fuse.js';
4
+ import jsonToAst from 'json-to-ast';
5
+ import { macroCondition, getGlobalConfig } from '@embroider/macros';
6
+ function validateDocumentFields(schema, jsonApiDoc) {
7
+ const {
8
+ data,
9
+ included
10
+ } = jsonApiDoc;
11
+ if (data === null) {
12
+ return;
13
+ }
14
+ if (typeof jsonApiDoc.data !== 'object') {
15
+ throw new Error(`Expected a resource object in the 'data' property in the document provided to the cache, but was ${typeof jsonApiDoc.data}`);
16
+ }
17
+ if (Array.isArray(data)) {
18
+ for (const resource of data) {
19
+ validateResourceFields(schema, resource, {
20
+ verifyIncluded: true,
21
+ included
22
+ });
23
+ }
24
+ } else {
25
+ validateResourceFields(schema, data, {
26
+ verifyIncluded: true,
27
+ included
28
+ });
29
+ }
30
+ if (included) {
31
+ for (const resource of included) {
32
+ validateResourceFields(schema, resource, {
33
+ verifyIncluded: false
34
+ });
35
+ }
36
+ }
37
+ }
38
+ function validateResourceFields(schema, resource, options) {
39
+ if (!resource.relationships) {
40
+ return;
41
+ }
42
+ const resourceType = resource.type;
43
+ const fields = schema.fields({
44
+ type: resource.type
45
+ });
46
+ for (const [type, relationshipDoc] of Object.entries(resource.relationships)) {
47
+ const field = fields.get(type);
48
+ if (!field) {
49
+ return;
50
+ }
51
+ switch (field.kind) {
52
+ case 'belongsTo':
53
+ {
54
+ if (field.options.linksMode) {
55
+ validateBelongsToLinksMode(resourceType, field, relationshipDoc, options);
56
+ }
57
+ break;
58
+ }
59
+ case 'hasMany':
60
+ {
61
+ if (field.options.linksMode) {
62
+ validateHasManyToLinksMode(resourceType, field);
63
+ }
64
+ break;
65
+ }
66
+ }
67
+ }
68
+ }
69
+ function validateBelongsToLinksMode(resourceType, field, relationshipDoc, options) {
70
+ if (field.options.async) {
71
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but async is not yet supported`);
72
+ }
73
+ if (!relationshipDoc.links?.related) {
74
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the related link is missing`);
75
+ }
76
+ const relationshipData = relationshipDoc.data;
77
+ if (Array.isArray(relationshipData)) {
78
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the relationship data for a belongsTo relationship is unexpectedly an array`);
79
+ }
80
+ // Explicitly allow `null`! Missing key or `undefined` are always invalid.
81
+ if (relationshipData === undefined) {
82
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the relationship data is undefined`);
83
+ }
84
+ if (relationshipData === null) {
85
+ return;
86
+ }
87
+ if (!options.verifyIncluded) {
88
+ return;
89
+ }
90
+ const includedDoc = options.included?.find(doc => doc.type === relationshipData.type && doc.id === relationshipData.id);
91
+ if (!includedDoc) {
92
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but the related data is not included`);
93
+ }
94
+ }
95
+ function validateHasManyToLinksMode(resourceType, field, _relationshipDoc, _options) {
96
+ if (field.options.async) {
97
+ throw new Error(`Cannot fetch ${resourceType}.${field.name} because the field is in linksMode but async hasMany is not yet supported`);
98
+ }
99
+ }
100
+ function inspectType(obj) {
101
+ if (obj === null) {
102
+ return 'null';
103
+ }
104
+ if (Array.isArray(obj)) {
105
+ return 'array';
106
+ }
107
+ if (typeof obj === 'object') {
108
+ const proto = Object.getPrototypeOf(obj);
109
+ if (proto === null) {
110
+ return 'object';
111
+ }
112
+ if (proto === Object.prototype) {
113
+ return 'object';
114
+ }
115
+ return `object (${proto.constructor?.name})`;
116
+ }
117
+ if (typeof obj === 'function') {
118
+ return 'function';
119
+ }
120
+ if (typeof obj === 'string') {
121
+ return 'string';
122
+ }
123
+ if (typeof obj === 'number') {
124
+ return 'number';
125
+ }
126
+ if (typeof obj === 'boolean') {
127
+ return 'boolean';
128
+ }
129
+ if (typeof obj === 'symbol') {
130
+ return 'symbol';
131
+ }
132
+ if (typeof obj === 'bigint') {
133
+ return 'bigint';
134
+ }
135
+ if (typeof obj === 'undefined') {
136
+ return 'undefined';
137
+ }
138
+ return 'unknown';
139
+ }
140
+ function isSimpleObject(obj) {
141
+ if (obj === null) {
142
+ return false;
143
+ }
144
+ if (Array.isArray(obj)) {
145
+ return false;
146
+ }
147
+ if (typeof obj !== 'object') {
148
+ return false;
149
+ }
150
+ const proto = Object.getPrototypeOf(obj);
151
+ if (proto === null) {
152
+ return true;
153
+ }
154
+ if (proto === Object.prototype) {
155
+ return true;
156
+ }
157
+ return false;
158
+ }
159
+ const RELATIONSHIP_FIELD_KINDS = ['belongsTo', 'hasMany', 'resource', 'collection'];
160
+ class Reporter {
161
+ capabilities;
162
+ contextDocument;
163
+ errors = [];
164
+ ast;
165
+ jsonStr;
166
+
167
+ // TODO @runspired make this configurable to consuming apps before
168
+ // activating by default
169
+ strict = {
170
+ linkage: true,
171
+ unknownType: true,
172
+ unknownAttribute: true,
173
+ unknownRelationship: true
174
+ };
175
+ constructor(capabilities, doc) {
176
+ this.capabilities = capabilities;
177
+ this.contextDocument = doc;
178
+ this.jsonStr = JSON.stringify(doc.content, null, 2);
179
+ this.ast = jsonToAst(this.jsonStr, {
180
+ loc: true
181
+ });
182
+ }
183
+ searchTypes(type) {
184
+ if (!this._typeFilter) {
185
+ const allTypes = this.schema.resourceTypes();
186
+ this._typeFilter = new Fuse(allTypes);
187
+ }
188
+ const result = this._typeFilter.search(type);
189
+ return result;
190
+ }
191
+ _fieldFilters = new Map();
192
+ searchFields(type, field) {
193
+ if (!this._fieldFilters.has(type)) {
194
+ const allFields = this.schema.fields({
195
+ type
196
+ });
197
+ const attrs = Array.from(allFields.values()).filter(isRemoteField).map(v => v.name);
198
+ this._fieldFilters.set(type, new Fuse(attrs));
199
+ }
200
+ const result = this._fieldFilters.get(type).search(field);
201
+ return result;
202
+ }
203
+ get schema() {
204
+ return this.capabilities.schema;
205
+ }
206
+ getLocation(path, kind) {
207
+ if (path.length === 0) {
208
+ return this.ast.loc;
209
+ }
210
+ let priorNode = this.ast;
211
+ let node = this.ast;
212
+ for (const segment of path) {
213
+ //
214
+ // handle array paths
215
+ //
216
+ if (typeof segment === 'number') {
217
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
218
+ if (!test) {
219
+ throw new Error(`Because the segment is a number, expected a node of type Array`);
220
+ }
221
+ })(node.type === 'Array') : {};
222
+ if (node.children && node.children[segment]) {
223
+ priorNode = node;
224
+ const childNode = node.children[segment];
225
+ if (childNode.type === 'Object' || childNode.type === 'Array') {
226
+ node = childNode;
227
+ } else {
228
+ // set to the closest node we can find
229
+ return node.loc;
230
+ }
231
+ } else {
232
+ // set to the closest node we can find
233
+ // as we had no children
234
+ return priorNode.loc;
235
+ }
236
+
237
+ //
238
+ // handle object paths
239
+ //
240
+ } else {
241
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
242
+ if (!test) {
243
+ throw new Error(`Because the segment is a string, expected a node of type Object`);
244
+ }
245
+ })(node.type === 'Object') : {};
246
+ const child = node.children.find(childCandidate => {
247
+ if (childCandidate.type === 'Property') {
248
+ return childCandidate.key.type === 'Identifier' && childCandidate.key.value === segment;
249
+ }
250
+ return false;
251
+ });
252
+ if (child) {
253
+ if (child.value.type === 'Object' || child.value.type === 'Array') {
254
+ priorNode = node;
255
+ node = child.value;
256
+ } else {
257
+ // set to the closest node we can find
258
+ return kind === 'key' ? child.key.loc : child.value.loc;
259
+ }
260
+ } else {
261
+ // set to the closest node we can find
262
+ return priorNode.loc;
263
+ }
264
+ }
265
+ }
266
+ return node.loc;
267
+ }
268
+ error(path, message, kind = 'key') {
269
+ const loc = this.getLocation(path, kind);
270
+ this.errors.push({
271
+ path,
272
+ message,
273
+ loc,
274
+ type: 'error',
275
+ kind
276
+ });
277
+ }
278
+ warn(path, message, kind = 'key') {
279
+ const loc = this.getLocation(path, kind);
280
+ this.errors.push({
281
+ path,
282
+ message,
283
+ loc,
284
+ type: 'warning',
285
+ kind
286
+ });
287
+ }
288
+ info(path, message, kind = 'key') {
289
+ const loc = this.getLocation(path, kind);
290
+ this.errors.push({
291
+ path,
292
+ message,
293
+ loc,
294
+ type: 'info',
295
+ kind
296
+ });
297
+ }
298
+ hasExtension(extensionName) {
299
+ return REGISTERED_EXTENSIONS.has(extensionName);
300
+ }
301
+ getExtension(extensionName) {
302
+ return REGISTERED_EXTENSIONS.get(extensionName);
303
+ }
304
+ report(colorize = true) {
305
+ const lines = this.jsonStr.split('\n');
306
+
307
+ // sort the errors by line, then by column, then by type
308
+ const {
309
+ errors
310
+ } = this;
311
+ if (!errors.length) {
312
+ return;
313
+ }
314
+ errors.sort((a, b) => {
315
+ return a.loc.end.line < b.loc.end.line ? -1 : a.loc.end.column < b.loc.end.column ? -1 : compareType(a.type, b.type);
316
+ });
317
+
318
+ // store the errors in a map by line
319
+ const errorMap = new Map();
320
+ for (const error of errors) {
321
+ const line = error.loc.end.line;
322
+ if (!errorMap.has(line)) {
323
+ errorMap.set(line, []);
324
+ }
325
+ errorMap.get(line).push(error);
326
+ }
327
+
328
+ // splice the errors into the lines
329
+ const errorLines = [];
330
+ const colors = [];
331
+ const counts = {
332
+ error: 0,
333
+ warning: 0,
334
+ info: 0
335
+ };
336
+ const LINE_SIZE = String(lines.length).length;
337
+ for (let i = 0; i < lines.length; i++) {
338
+ const line = lines[i];
339
+ errorLines.push(colorize ? `${String(i + 1).padEnd(LINE_SIZE, ' ')} \t%c${line}%c` : `${String(i + 1).padEnd(LINE_SIZE, ' ')} \t${line}`);
340
+ colors.push(`color: grey; background-color: transparent;`,
341
+ // first color sets color
342
+ `color: inherit; background-color: transparent;` // second color resets the color profile
343
+ );
344
+ if (errorMap.has(i + 1)) {
345
+ const errorsForLine = errorMap.get(i + 1);
346
+ for (const error of errorsForLine) {
347
+ counts[error.type]++;
348
+ const {
349
+ loc,
350
+ message
351
+ } = error;
352
+ const start = loc.end.line === loc.start.line ? loc.start.column - 1 : loc.end.column - 1;
353
+ const end = loc.end.column - 1;
354
+ const symbol = error.type === 'error' ? '❌' : error.type === 'warning' ? '⚠️' : 'ℹ️';
355
+ const errorLine = colorize ? `${''.padStart(LINE_SIZE, ' ') + symbol}\t${' '.repeat(start)}%c^${'~'.repeat(end - start)} %c//%c ${message}%c` : `${''.padStart(LINE_SIZE, ' ') + symbol}\t${' '.repeat(start)}^${'~'.repeat(end - start)} // ${message}`;
356
+ errorLines.push(errorLine);
357
+ colors.push(error.type === 'error' ? 'color: red;' : error.type === 'warning' ? 'color: orange;' : 'color: blue;', 'color: grey;', error.type === 'error' ? 'color: red;' : error.type === 'warning' ? 'color: orange;' : 'color: blue;', 'color: inherit; background-color: transparent;' // reset color
358
+ );
359
+ }
360
+ }
361
+ }
362
+ const contextStr = `${counts.error} errors and ${counts.warning} warnings found in the {JSON:API} document returned by ${this.contextDocument.request?.method} ${this.contextDocument.request?.url}`;
363
+ const errorString = contextStr + `\n\n` + errorLines.join('\n');
364
+
365
+ // eslint-disable-next-line no-console, @typescript-eslint/no-unused-expressions
366
+ colorize ? console.log(errorString, ...colors) : console.log(errorString);
367
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.features.JSON_API_CACHE_VALIDATION_ERRORS)) {
368
+ if (counts.error > 0) {
369
+ throw new Error(contextStr);
370
+ }
371
+ }
372
+ }
373
+ }
374
+
375
+ // we always want to sort errors first, then warnings, then info
376
+ function compareType(a, b) {
377
+ if (a === b) {
378
+ return 0;
379
+ }
380
+ if (a === 'error') {
381
+ return -1;
382
+ }
383
+ if (b === 'error') {
384
+ return 1;
385
+ }
386
+ if (a === 'warning') {
387
+ return -1;
388
+ }
389
+ if (b === 'warning') {
390
+ return 1;
391
+ }
392
+ return 0;
393
+ }
394
+ const REGISTERED_EXTENSIONS = new Map();
395
+ function isMetaDocument(doc) {
396
+ return !(doc instanceof Error) && doc.content && !('data' in doc.content) && !('included' in doc.content) && 'meta' in doc.content;
397
+ }
398
+ function isErrorDocument(doc) {
399
+ return doc instanceof Error;
400
+ }
401
+ function isPushedDocument(doc) {
402
+ return !!doc && typeof doc === 'object' && 'content' in doc && !('request' in doc) && !('response' in doc);
403
+ }
404
+ function logPotentialMatches(matches, kind) {
405
+ if (matches.length === 0) {
406
+ return '';
407
+ }
408
+ if (matches.length === 1) {
409
+ return ` Did you mean this available ${kind} "${matches[0].item}"?`;
410
+ }
411
+ const potentialMatches = matches.map(match => match.item).join('", "');
412
+ return ` Did you mean one of these available ${kind}s: "${potentialMatches}"?`;
413
+ }
414
+ function isRemoteField(v) {
415
+ return !(v.kind === '@local' || v.kind === 'alias' || v.kind === 'derived');
416
+ }
417
+ function getRemoteField(fields, key) {
418
+ const field = fields.get(key);
419
+ if (!field) {
420
+ return undefined;
421
+ }
422
+ if (!isRemoteField(field)) {
423
+ return undefined;
424
+ }
425
+ return field;
426
+ }
427
+ const VALID_TOP_LEVEL_MEMBERS = ['data', 'included', 'meta', 'jsonapi', 'links'];
428
+
429
+ /**
430
+ * Reports issues which violate the JSON:API spec for top-level members.
431
+ *
432
+ * Version: 1.1
433
+ * Section: 7.1
434
+ * Link: https://jsonapi.org/format/#document-top-level
435
+ *
436
+ * @internal
437
+ */
438
+ function validateTopLevelDocumentMembers(reporter, doc) {
439
+ const keys = Object.keys(doc);
440
+ for (const key of keys) {
441
+ if (!VALID_TOP_LEVEL_MEMBERS.includes(key)) {
442
+ if (key.includes(':')) {
443
+ // TODO @runspired expose the API to enable folks to add validation for their own extensions
444
+ const extensionName = key.split(':')[0];
445
+ if (reporter.hasExtension(extensionName)) {
446
+ const extension = reporter.getExtension(extensionName);
447
+ extension(reporter, [key]);
448
+ } else {
449
+ reporter.warn([key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {JSON:API} member`);
450
+ }
451
+ } else {
452
+ reporter.error([key], `Unrecognized top-level member. The data it provides is ignored as it is not a valid {JSON:API} member`);
453
+ }
454
+ }
455
+ }
456
+
457
+ // additional rules for top-level members
458
+ // ======================================
459
+
460
+ // 1. MUST have either `data`, `errors`, or `meta`
461
+ if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
462
+ reporter.error([], 'A {JSON:API} Document must contain one-of `data` `errors` or `meta`');
463
+ }
464
+
465
+ // 2. MUST NOT have both `data` and `errors`
466
+ if ('data' in doc && 'errors' in doc) {
467
+ reporter.error(['data'], 'A {JSON:API} Document MUST NOT contain both `data` and `errors` members');
468
+ }
469
+
470
+ // 3. MUST NOT have both `included` and `errors`
471
+ // while not explicitly stated in the spec, this is a logical extension of the above rule
472
+ // since `included` is only valid when `data` is present.
473
+ if ('included' in doc && 'errors' in doc) {
474
+ reporter.error(['included'], 'A {JSON:API} Document MUST NOT contain both `included` and `errors` members');
475
+ }
476
+
477
+ // 4. MUST NOT have `included` if `data` is not present
478
+ if ('included' in doc && !('data' in doc)) {
479
+ reporter.error(['included'], 'A {JSON:API} Document MUST NOT contain `included` if `data` is not present');
480
+ }
481
+
482
+ // 5. MUST NOT have `included` if `data` is null
483
+ // when strictly enforcing full linkage, we need to ensure that `included` is not present if `data` is null
484
+ // however, most APIs will ignore this rule for DELETE requests, so unless strict linkage is enabled, we will only warn
485
+ // about this issue.
486
+ if ('included' in doc && doc.data === null) {
487
+ const isMaybeDelete = reporter.contextDocument.request?.method?.toUpperCase() === 'DELETE' || reporter.contextDocument.request?.op === 'deleteRecord';
488
+ const method = !reporter.strict.linkage && isMaybeDelete ? 'warn' : 'error';
489
+ reporter[method](['included'], 'A {JSON:API} Document MUST NOT contain `included` if `data` is null');
490
+ }
491
+
492
+ // Simple Validation of Top-Level Members
493
+ // ==========================================
494
+ // 1. `data` MUST be a single resource object or an array of resource objects or `null`
495
+ if ('data' in doc) {
496
+ const dataMemberHasAppropriateForm = doc.data === null || Array.isArray(doc.data) || isSimpleObject(doc.data);
497
+ if (!dataMemberHasAppropriateForm) {
498
+ reporter.error(['data'], `The 'data' member MUST be a single resource object or an array of resource objects or null. Received data of type "${inspectType(doc.data)}"`);
499
+ }
500
+ }
501
+
502
+ // 2. `included` MUST be an array of resource objects
503
+ if ('included' in doc) {
504
+ if (!Array.isArray(doc.included)) {
505
+ reporter.error(['included'], `The 'included' member MUST be an array of resource objects. Received data of type "${inspectType(doc.included)}"`);
506
+ }
507
+ }
508
+
509
+ // 3. `meta` MUST be a simple object
510
+ if ('meta' in doc) {
511
+ if (!isSimpleObject(doc.meta)) {
512
+ reporter.error(['meta'], `The 'meta' member MUST be a simple object. Received data of type "${inspectType(doc.meta)}"`);
513
+ }
514
+ }
515
+
516
+ // 4. `jsonapi` MUST be a simple object
517
+ if ('jsonapi' in doc) {
518
+ if (!isSimpleObject(doc.jsonapi)) {
519
+ reporter.error(['jsonapi'], `The 'jsonapi' member MUST be a simple object. Received data of type "${inspectType(doc.jsonapi)}"`);
520
+ }
521
+ }
522
+
523
+ // 5. `links` MUST be a simple object
524
+ if ('links' in doc) {
525
+ if (!isSimpleObject(doc.links)) {
526
+ reporter.error(['links'], `The 'links' member MUST be a simple object. Received data of type "${inspectType(doc.links)}"`);
527
+ }
528
+ }
529
+
530
+ // 6. `errors` MUST be an array of error objects
531
+ if ('errors' in doc) {
532
+ if (!Array.isArray(doc.errors)) {
533
+ reporter.error(['errors'], `The 'errors' member MUST be an array of error objects. Received data of type "${inspectType(doc.errors)}"`);
534
+ }
535
+ }
536
+ }
537
+ const VALID_COLLECTION_LINKS = ['self', 'related', 'first', 'last', 'prev', 'next'];
538
+ const VALID_RESOURCE_RELATIONSHIP_LINKS = ['self', 'related'];
539
+ const VALID_RESOURCE_LINKS = ['self'];
540
+
541
+ /**
542
+ * Validates the links object in a top-level JSON API document or resource object
543
+ *
544
+ * Version: 1.1
545
+ *
546
+ * Section: 7.1 Top Level
547
+ * Link: https://jsonapi.org/format/#document-top-level
548
+ *
549
+ * Section: 7.2.3 Resource Objects
550
+ * Link: https://jsonapi.org/format/#document-resource-object-links
551
+ *
552
+ * Section: 7.2.2.2 Resource Relationships
553
+ * Link: https://jsonapi.org/format/#document-resource-object-relationships
554
+ *
555
+ * Section: 7.6 Document Links
556
+ * Link: https://jsonapi.org/format/#document-links
557
+ *
558
+ * @internal
559
+ */
560
+ function validateLinks(reporter, doc, type, path = ['links']) {
561
+ if (!('links' in doc)) {
562
+ return;
563
+ }
564
+ if (!isSimpleObject(doc.links)) {
565
+ // this is a violation but we report it when validating section 7.1
566
+ return;
567
+ }
568
+
569
+ // prettier-ignore
570
+ const VALID_TOP_LEVEL_LINKS = type === 'collection-document' || type === 'collection-relationship' ? VALID_COLLECTION_LINKS : type === 'resource-document' || type === 'resource-relationship' ? VALID_RESOURCE_RELATIONSHIP_LINKS : type === 'resource' ? VALID_RESOURCE_LINKS : [];
571
+ const links = doc.links;
572
+ const keys = Object.keys(links);
573
+ for (const key of keys) {
574
+ if (!VALID_TOP_LEVEL_LINKS.includes(key)) {
575
+ reporter.warn([...path, key], `Unrecognized top-level link. The data it provides may be ignored as it is not a valid {JSON:API} link for a ${type}`);
576
+ }
577
+ // links may be either a string or an object with an href property or null
578
+ if (links[key] === null) ;else if (typeof links[key] === 'string') {
579
+ if (links[key].length === 0) {
580
+ reporter.warn([...path, key], `Expected a non-empty string, but received an empty string`);
581
+ }
582
+ // valid, though we should potentially validate the URL here
583
+ } else if (isSimpleObject(links[key])) {
584
+ if ('href' in links[key]) {
585
+ const linksKeys = Object.keys(links[key]);
586
+ if (linksKeys.length > 1) {
587
+ reporter.warn([...path, key], `Expected the links object to only have an href property, but received unknown keys ${linksKeys.filter(k => k !== 'href').join(', ')}`);
588
+ }
589
+ if (typeof links[key].href !== 'string') {
590
+ reporter.error([...path, key, 'href'], `Expected a string value, but received ${inspectType(links[key].href)}`);
591
+ } else {
592
+ if (links[key].href.length === 0) {
593
+ reporter.warn([...path, key, 'href'], `Expected a non-empty string, but received an empty string`);
594
+ }
595
+ // valid, though we should potentially validate the URL here
596
+ }
597
+ } else {
598
+ const linksKeys = Object.keys(links[key]);
599
+ if (linksKeys.length > 0) {
600
+ reporter.error([...path, key], `Expected the links object to have an href property, but received only the unknown keys ${linksKeys.join(', ')}`);
601
+ } else {
602
+ reporter.error([...path, key], `Expected the links object to have an href property`);
603
+ }
604
+ }
605
+ } else {
606
+ // invalid
607
+ reporter.error([...path, key], `Expected a string, null, or an object with an href property for the link "${key}", but received ${inspectType(links[key])}`);
608
+ }
609
+ }
610
+ }
611
+ const SINGULAR_OPS = ['createRecord', 'updateRecord', 'deleteRecord', 'findRecord', 'queryRecord'];
612
+
613
+ /**
614
+ * Validates the resource objects in either the `data` or `included` members of
615
+ * JSON:API document.
616
+ *
617
+ * Version: 1.1
618
+ * Section: 7.2
619
+ * Link: https://jsonapi.org/format/#document-resource-objects
620
+ *
621
+ * @internal
622
+ */
623
+ function validateDocumentResources(reporter, doc) {
624
+ if ('data' in doc) {
625
+ // scan for common mistakes of single vs multiple resource objects
626
+ const op = reporter.contextDocument.request?.op;
627
+ if (op && SINGULAR_OPS.includes(op)) {
628
+ if (Array.isArray(doc.data)) {
629
+ reporter.error(['data'], `"${op}" requests expect a single resource object in the returned data, but received an array`);
630
+ }
631
+ }
632
+
633
+ // guard for a common mistake around deleteRecord
634
+ if (op === 'deleteRecord') {
635
+ if (doc.data !== null) {
636
+ reporter.warn(['data'], `"deleteRecord" requests expect the data member to be null, but received ${inspectType(doc.data)}. This can sometimes cause unexpected resurrection of the deleted record.`);
637
+ }
638
+ }
639
+ if (Array.isArray(doc.data)) {
640
+ doc.data.forEach((resource, index) => {
641
+ if (!isSimpleObject(resource)) {
642
+ reporter.error(['data', index], `Expected a resource object, but received ${inspectType(resource)}`);
643
+ } else {
644
+ validateResourceObject(reporter, resource, ['data', index]);
645
+ }
646
+ });
647
+ } else if (doc.data !== null) {
648
+ if (!isSimpleObject(doc.data)) {
649
+ reporter.error(['data'], `Expected a resource object, but received ${inspectType(doc.data)}`);
650
+ } else {
651
+ validateResourceObject(reporter, doc.data, ['data']);
652
+ }
653
+ }
654
+ }
655
+ if ('included' in doc && Array.isArray(doc.included)) {
656
+ doc.included.forEach((resource, index) => {
657
+ if (!isSimpleObject(resource)) {
658
+ reporter.error(['included', index], `Expected a resource object, but received ${inspectType(resource)}`);
659
+ } else {
660
+ validateResourceObject(reporter, resource, ['included', index]);
661
+ }
662
+ });
663
+ }
664
+ }
665
+ function validateResourceObject(reporter, resource, path) {
666
+ validateTopLevelResourceShape(reporter, resource, path);
667
+ }
668
+ const VALID_TOP_LEVEL_RESOURCE_KEYS = ['lid', 'id', 'type', 'attributes', 'relationships', 'meta', 'links'];
669
+ function validateTopLevelResourceShape(reporter, resource, path) {
670
+ // a resource MUST have a string type
671
+ if (!('type' in resource)) {
672
+ reporter.error([...path, 'type'], `Expected a ResourceObject to have a type property`);
673
+ } else if (typeof resource.type !== 'string') {
674
+ reporter.error([...path, 'type'], `Expected a string value for the type property, but received ${inspectType(resource.type)}`, 'value');
675
+ } else if (resource.type.length === 0) {
676
+ reporter.error([...path, 'type'], `Expected a non-empty string value for the type property, but received an empty string`, 'value');
677
+ } else if (!reporter.schema.hasResource({
678
+ type: resource.type
679
+ })) {
680
+ const method = reporter.strict.unknownType ? 'error' : 'warn';
681
+ const potentialTypes = reporter.searchTypes(resource.type);
682
+ reporter[method]([...path, 'type'], `Expected a schema to be available for the ResourceType "${resource.type}" but none was found.${logPotentialMatches(potentialTypes, 'ResourceType')}`, 'value');
683
+ }
684
+
685
+ // a resource MUST have a string ID
686
+ if (!('id' in resource)) {
687
+ reporter.error([...path, 'id'], `Expected a ResourceObject to have an id property`);
688
+ } else if (typeof resource.id !== 'string') {
689
+ reporter.error([...path, 'id'], `Expected a string value for the id property, but received ${inspectType(resource.id)}`, 'value');
690
+ } else if (resource.id.length === 0) {
691
+ reporter.error([...path, 'id'], `Expected a non-empty string value for the id property, but received an empty string`, 'value');
692
+ }
693
+
694
+ // a resource MAY have a lid property
695
+ if ('lid' in resource && typeof resource.lid !== 'string') {
696
+ reporter.error([...path, 'lid'], `Expected a string value for the lid property, but received ${inspectType(resource.lid)}`, 'value');
697
+ }
698
+
699
+ // a resource MAY have a meta property
700
+ if ('meta' in resource && !isSimpleObject(resource.meta)) {
701
+ reporter.error([...path, 'meta'], `Expected a simple object for the meta property, but received ${inspectType(resource.meta)}`, 'value');
702
+ }
703
+
704
+ // a resource MAY have a links property
705
+ if ('links' in resource && !isSimpleObject(resource.links)) {
706
+ reporter.error([...path, 'links'], `Expected a simple object for the links property, but received ${inspectType(resource.links)}`, 'value');
707
+ } else if ('links' in resource) {
708
+ validateLinks(reporter, resource, 'resource', [...path, 'links']);
709
+ }
710
+ const hasAttributes = 'attributes' in resource && isSimpleObject(resource.attributes);
711
+ const hasRelationships = 'relationships' in resource && isSimpleObject(resource.relationships);
712
+
713
+ // We expect at least one of attributes or relationships to be present
714
+ if (!hasAttributes && !hasRelationships) {
715
+ reporter.warn(path, `Expected a ResourceObject to have either attributes or relationships`);
716
+ }
717
+
718
+ // we expect at least one of attributes or relationships to be non-empty
719
+ const attributesLength = hasAttributes ? Object.keys(resource.attributes).length : 0;
720
+ const relationshipsLength = hasRelationships ? Object.keys(resource.relationships).length : 0;
721
+ if ((hasAttributes || hasRelationships) && attributesLength === 0 && relationshipsLength === 0) {
722
+ reporter.warn([...path, hasAttributes ? 'attributes' : hasRelationships ? 'relationships' : 'attributes'], `Expected a ResourceObject to have either non-empty attributes or non-empty relationships`);
723
+ }
724
+
725
+ // check for unknown keys on the resource object
726
+ const keys = Object.keys(resource);
727
+ for (const key of keys) {
728
+ if (!VALID_TOP_LEVEL_RESOURCE_KEYS.includes(key)) {
729
+ // check for extension keys
730
+ if (key.includes(':')) {
731
+ const extensionName = key.split(':')[0];
732
+ if (reporter.hasExtension(extensionName)) {
733
+ const extension = reporter.getExtension(extensionName);
734
+ extension(reporter, [...path, key]);
735
+ } else {
736
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {JSON:API} ResourceObject member`);
737
+ }
738
+ } else {
739
+ // check if this is an attribute or relationship
740
+ let didYouMean = ' Likely this field should have been inside of either "attributes" or "relationships"';
741
+ const type = 'type' in resource ? resource.type : undefined;
742
+ if (type && reporter.schema.hasResource({
743
+ type
744
+ })) {
745
+ const fields = reporter.schema.fields({
746
+ type
747
+ });
748
+ const field = getRemoteField(fields, key);
749
+ if (field) {
750
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(field.kind);
751
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely a ${field.kind} and belongs inside of ${isRelationship ? 'relationships' : 'attributes'}, e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${key}": { ... } }`;
752
+ } else {
753
+ const fieldMatches = reporter.searchFields(type, key);
754
+ if (fieldMatches.length === 1) {
755
+ const matchedField = fields.get(fieldMatches[0].item);
756
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(matchedField.kind);
757
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely a ${matchedField.kind} and belongs inside of ${isRelationship ? 'relationships' : 'attributes'}, e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${matchedField.name}": { ... } }`;
758
+ } else if (fieldMatches.length > 1) {
759
+ const matchedField = fields.get(fieldMatches[0].item);
760
+ const isRelationship = RELATIONSHIP_FIELD_KINDS.includes(matchedField.kind);
761
+ didYouMean = ` Based on the ResourceSchema for "${type}" this field is likely one of "${fieldMatches.map(v => v.item).join('", "')}" and belongs inside of either "attributes" or "relationships", e.g. "${isRelationship ? 'relationships' : 'attributes'}": { "${matchedField.name}": { ... } }`;
762
+ }
763
+ }
764
+ }
765
+ reporter.error([...path, key], `Unrecognized ResourceObject member. The data it provides is ignored as it is not a valid {JSON:API} ResourceObject member.${didYouMean}`);
766
+ }
767
+ }
768
+ }
769
+
770
+ // if we have a schema, validate the individual attributes and relationships
771
+ const type = 'type' in resource ? resource.type : undefined;
772
+ if (type && reporter.schema.hasResource({
773
+ type
774
+ })) {
775
+ if ('attributes' in resource) {
776
+ validateResourceAttributes(reporter, type, resource.attributes, [...path, 'attributes']);
777
+ }
778
+ if ('relationships' in resource) {
779
+ validateResourceRelationships(reporter, type, resource.relationships, [...path, 'relationships']);
780
+ }
781
+ }
782
+ }
783
+ function validateResourceAttributes(reporter, type, resource, path) {
784
+ const schema = reporter.schema.fields({
785
+ type
786
+ });
787
+ for (const [key] of Object.entries(resource)) {
788
+ const field = getRemoteField(schema, key);
789
+ const actualField = schema.get(key);
790
+ if (!field && actualField) {
791
+ reporter.warn([...path, key], `Expected the ${actualField.kind} field to not have its own resource data. Likely this field should either not be returned in this payload or the field definition should be updated in the schema.`);
792
+ } else if (!field) {
793
+ if (key.includes(':')) {
794
+ const extensionName = key.split(':')[0];
795
+ if (reporter.hasExtension(extensionName)) {
796
+ const extension = reporter.getExtension(extensionName);
797
+ extension(reporter, [...path, key]);
798
+ } else {
799
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {JSON:API} ResourceObject member`);
800
+ }
801
+ } else {
802
+ const method = reporter.strict.unknownAttribute ? 'error' : 'warn';
803
+
804
+ // TODO @runspired when we check for fuzzy matches we can adjust the message to say
805
+ // whether the expected field is an attribute or a relationship
806
+ const potentialFields = reporter.searchFields(type, key);
807
+ reporter[method]([...path, key], `Unrecognized attribute. The data it provides is ignored as it is not part of the ResourceSchema for "${type}".${logPotentialMatches(potentialFields, 'field')}`);
808
+ }
809
+ } else if (field && RELATIONSHIP_FIELD_KINDS.includes(field.kind)) {
810
+ reporter.error([...path, key], `Expected the "${key}" field to be in "relationships" as it has kind "${field.kind}", but received data for it in "attributes".`);
811
+ }
812
+ }
813
+
814
+ // TODO @runspired we should also deep-validate the field value
815
+ // TODO @runspired we should validate that field values are valid JSON and not instances
816
+ }
817
+ function validateResourceRelationships(reporter, type, resource, path) {
818
+ const schema = reporter.schema.fields({
819
+ type
820
+ });
821
+ for (const [key] of Object.entries(resource)) {
822
+ const field = getRemoteField(schema, key);
823
+ const actualField = schema.get(key);
824
+ if (!field && actualField) {
825
+ reporter.warn([...path, key], `Expected the ${actualField.kind} field to not have its own resource data. Likely this field should either not be returned in this payload or the field definition should be updated in the schema.`);
826
+ } else if (!field) {
827
+ if (key.includes(':')) {
828
+ const extensionName = key.split(':')[0];
829
+ if (reporter.hasExtension(extensionName)) {
830
+ const extension = reporter.getExtension(extensionName);
831
+ extension(reporter, [...path, key]);
832
+ } else {
833
+ reporter.warn([...path, key], `Unrecognized extension ${extensionName}. The data provided by "${key}" will be ignored as it is not a valid {JSON:API} ResourceObject member`);
834
+ }
835
+ } else {
836
+ const method = reporter.strict.unknownRelationship ? 'error' : 'warn';
837
+
838
+ // TODO @runspired when we check for fuzzy matches we can adjust the message to say
839
+ // whether the expected field is an attribute or a relationship
840
+ const potentialFields = reporter.searchFields(type, key);
841
+ reporter[method]([...path, key], `Unrecognized relationship. The data it provides is ignored as it is not part of the ResourceSchema for "${type}".${logPotentialMatches(potentialFields, 'field')}`);
842
+ }
843
+ } else if (field && !RELATIONSHIP_FIELD_KINDS.includes(field.kind)) {
844
+ reporter.error([...path, key], `Expected the "${key}" field to be in "attributes" as it has kind "${field.kind}", but received data for it in "relationships".`);
845
+ }
846
+ }
847
+
848
+ // TODO @runspired we should also deep-validate the relationship payload
849
+ // TODO @runspired we should validate linksMode requirements for both Polaris and Legacy modes
850
+ // TODO @runspired we should warn if the discovered resource-type in a relationship is the abstract
851
+ // type instead of the concrete type.
852
+ }
853
+ function validateDocument(capabilities, doc) {
854
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
855
+ if (!test) {
856
+ throw new Error(`Expected a JSON:API Document as the content provided to the cache, received ${typeof doc.content}`);
857
+ }
858
+ })(doc instanceof Error || typeof doc.content === 'object' && doc.content !== null) : {};
859
+
860
+ // if the feature is not active and the payloads are not being logged
861
+ // we don't need to validate the payloads
862
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.features.JSON_API_CACHE_VALIDATION_ERRORS)) {
863
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
864
+ if (!(getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE)) {
865
+ return;
866
+ }
867
+ }
868
+ }
869
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
870
+ if (!(getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE)) {
871
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.features.JSON_API_CACHE_VALIDATION_ERRORS)) {
872
+ return;
873
+ }
874
+ }
875
+ }
876
+ if (isErrorDocument(doc)) {
877
+ return; // return validateErrorDocument(reporter, doc);
878
+ } else if (isMetaDocument(doc)) {
879
+ return; // return validateMetaDocument(reporter, doc);
880
+ } else if (isPushedDocument(doc)) {
881
+ return; // return validatePushedDocument(reporter, doc);
882
+ }
883
+ const reporter = new Reporter(capabilities, doc);
884
+ return validateResourceDocument(reporter, doc);
885
+ }
886
+
887
+ // function validateErrorDocument(reporter: Reporter, doc: StructuredErrorDocument) {}
888
+
889
+ // function validateMetaDocument(reporter: Reporter, doc: StructuredDataDocument<ResourceMetaDocument>) {}
890
+
891
+ // function validatePushedDocument(reporter: Reporter, doc: StructuredDataDocument<ResourceDocument>) {}
892
+
893
+ function validateResourceDocument(reporter, doc) {
894
+ validateTopLevelDocumentMembers(reporter, doc.content);
895
+ validateLinks(reporter, doc.content, 'data' in doc.content && Array.isArray(doc.content?.data) ? 'collection-document' : 'resource-document');
896
+ validateDocumentResources(reporter, doc.content);
897
+
898
+ // TODO @runspired - validateMeta on document
899
+ // TODO @runspired - validateMeta on resource
900
+ // TODO @runspired - validateMeta on resource relationships
901
+ // TODO @runspired - validate no-meta on resource identifiers
902
+ //
903
+ // ---------------------------------
904
+ // super-strict-mode
905
+ //
906
+ // TODO @runspired - validate that all referenced resource identifiers are present in the document (full linkage)
907
+ // TODO @runspired - validate that all included resources have a path back to `data` (full linkage)
908
+ //
909
+ // ---------------------------------
910
+ // nice-to-haves
911
+ //
912
+ // TODO @runspired - validate links objects more thoroughly for spec props we don't use
913
+ // TODO @runspired - validate request includes are in fact included
914
+ // TODO @runspired - validate request fields are in fact present
915
+ // TODO @runspired - MAYBE validate request sort is in fact sorted? (useful for catching Mocking bugs)
916
+ // TODO @runspired - MAYBE validate request pagination is in fact paginated? (useful for catching Mocking bugs)
917
+
918
+ reporter.report();
919
+ }
920
+ function isImplicit(relationship) {
921
+ return relationship.definition.isImplicit;
922
+ }
923
+ function upgradeCapabilities(obj) {}
924
+ const EMPTY_ITERATOR = {
925
+ iterator() {
926
+ return {
927
+ next() {
928
+ return {
929
+ done: true,
930
+ value: undefined
931
+ };
932
+ }
933
+ };
934
+ }
935
+ };
936
+ function makeCache() {
937
+ return {
938
+ id: null,
939
+ remoteAttrs: null,
940
+ localAttrs: null,
941
+ defaultAttrs: null,
942
+ inflightAttrs: null,
943
+ changes: null,
944
+ errors: null,
945
+ isNew: false,
946
+ isDeleted: false,
947
+ isDeletionCommitted: false
948
+ };
949
+ }
950
+
951
+ /**
952
+ A JSON:API Cache implementation.
953
+
954
+ What cache the store uses is configurable. Using a different
955
+ implementation can be achieved by implementing the store's
956
+ createCache hook.
957
+
958
+ This is the cache implementation used by `ember-data`.
959
+
960
+ ```js
961
+ import Cache from '@ember-data-mirror/json-api';
962
+ import Store from '@ember-data-mirror/store';
963
+
964
+ export default class extends Store {
965
+ createCache(wrapper) {
966
+ return new Cache(wrapper);
967
+ }
968
+ }
969
+ ```
970
+
971
+ @class Cache
972
+ @public
973
+ */
974
+
975
+ class JSONAPICache {
976
+ /**
977
+ * The Cache Version that this implementation implements.
978
+ *
979
+ * @type {'2'}
980
+ * @public
981
+ * @property version
982
+ */
983
+
984
+ /** @internal */
985
+
986
+ /** @internal */
987
+
988
+ /** @internal */
989
+
990
+ /** @internal */
991
+
992
+ /** @internal */
993
+
994
+ constructor(capabilities) {
995
+ this.version = '2';
996
+ this._capabilities = capabilities;
997
+ this.__cache = new Map();
998
+ this.__graph = graphFor(capabilities);
999
+ this.__destroyedCache = new Map();
1000
+ this.__documents = new Map();
1001
+ }
1002
+
1003
+ // Cache Management
1004
+ // ================
1005
+
1006
+ /**
1007
+ * Cache the response to a request
1008
+ *
1009
+ * Implements `Cache.put`.
1010
+ *
1011
+ * Expects a StructuredDocument whose `content` member is a JsonApiDocument.
1012
+ *
1013
+ * ```js
1014
+ * cache.put({
1015
+ * request: { url: 'https://api.example.com/v1/user/1' },
1016
+ * content: {
1017
+ * data: {
1018
+ * type: 'user',
1019
+ * id: '1',
1020
+ * attributes: {
1021
+ * name: 'Chris'
1022
+ * }
1023
+ * }
1024
+ * }
1025
+ * })
1026
+ * ```
1027
+ *
1028
+ * > **Note**
1029
+ * > The nested `content` and `data` members are not a mistake. This is because
1030
+ * > there are two separate concepts involved here, the `StructuredDocument` which contains
1031
+ * > the context of a given Request that has been issued with the returned contents as its
1032
+ * > `content` property, and a `JSON:API Document` which is the json contents returned by
1033
+ * > this endpoint and which uses its `data` property to signify which resources are the
1034
+ * > primary resources associated with the request.
1035
+ *
1036
+ * StructuredDocument's with urls will be cached as full documents with
1037
+ * associated resource membership order and contents preserved but linked
1038
+ * into the cache.
1039
+ *
1040
+ * @param {StructuredDocument} doc
1041
+ * @return {ResourceDocument}
1042
+ * @public
1043
+ */
1044
+
1045
+ put(doc) {
1046
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
1047
+ validateDocument(this._capabilities, doc);
1048
+ }
1049
+ if (isErrorDocument(doc)) {
1050
+ return this._putDocument(doc, undefined, undefined);
1051
+ } else if (isMetaDocument(doc)) {
1052
+ return this._putDocument(doc, undefined, undefined);
1053
+ }
1054
+ const jsonApiDoc = doc.content;
1055
+ const included = jsonApiDoc.included;
1056
+ let i, length;
1057
+ const {
1058
+ identifierCache
1059
+ } = this._capabilities;
1060
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
1061
+ validateDocumentFields(this._capabilities.schema, jsonApiDoc);
1062
+ }
1063
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1064
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1065
+ const Counts = new Map();
1066
+ let totalCount = 0;
1067
+ if (included) {
1068
+ for (i = 0, length = included.length; i < length; i++) {
1069
+ const type = included[i].type;
1070
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1071
+ totalCount++;
1072
+ }
1073
+ }
1074
+ if (Array.isArray(jsonApiDoc.data)) {
1075
+ for (i = 0, length = jsonApiDoc.data.length; i < length; i++) {
1076
+ const type = jsonApiDoc.data[i].type;
1077
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1078
+ totalCount++;
1079
+ }
1080
+ } else if (jsonApiDoc.data) {
1081
+ const type = jsonApiDoc.data.type;
1082
+ Counts.set(type, (Counts.get(type) || 0) + 1);
1083
+ totalCount++;
1084
+ }
1085
+ logGroup('cache', 'put', '<@document>', doc.content?.lid || doc.request?.url || 'unknown-request', `(${totalCount}) records`, '');
1086
+ let str = `\tContent Counts:`;
1087
+ Counts.forEach((count, type) => {
1088
+ str += `\n\t\t${type}: ${count} record${count > 1 ? 's' : ''}`;
1089
+ });
1090
+ if (Counts.size === 0) {
1091
+ str += `\t(empty)`;
1092
+ }
1093
+ // eslint-disable-next-line no-console
1094
+ console.log(str);
1095
+ // eslint-disable-next-line no-console
1096
+ console.log({
1097
+ lid: doc.content?.lid,
1098
+ content: structuredClone(doc.content),
1099
+ // we may need a specialized copy here
1100
+ request: doc.request,
1101
+ // structuredClone(doc.request),
1102
+ response: doc.response // structuredClone(doc.response),
1103
+ });
1104
+ // eslint-disable-next-line no-console
1105
+ console.groupEnd();
1106
+ }
1107
+ }
1108
+ if (included) {
1109
+ for (i = 0, length = included.length; i < length; i++) {
1110
+ included[i] = putOne(this, identifierCache, included[i]);
1111
+ }
1112
+ }
1113
+ if (Array.isArray(jsonApiDoc.data)) {
1114
+ length = jsonApiDoc.data.length;
1115
+ const identifiers = [];
1116
+ for (i = 0; i < length; i++) {
1117
+ identifiers.push(putOne(this, identifierCache, jsonApiDoc.data[i]));
1118
+ }
1119
+ return this._putDocument(doc, identifiers, included);
1120
+ }
1121
+ if (jsonApiDoc.data === null) {
1122
+ return this._putDocument(doc, null, included);
1123
+ }
1124
+ const identifier = putOne(this, identifierCache, jsonApiDoc.data);
1125
+ return this._putDocument(doc, identifier, included);
1126
+ }
1127
+
1128
+ /** @internal */
1129
+
1130
+ _putDocument(doc, data, included) {
1131
+ // @ts-expect-error narrowing within is just horrible in TS :/
1132
+ const resourceDocument = isErrorDocument(doc) ? fromStructuredError(doc) : fromBaseDocument(doc);
1133
+ if (data !== undefined) {
1134
+ resourceDocument.data = data;
1135
+ }
1136
+ if (included !== undefined) {
1137
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1138
+ if (!test) {
1139
+ throw new Error(`There should not be included data on an Error document`);
1140
+ }
1141
+ })(!isErrorDocument(doc)) : {};
1142
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1143
+ if (!test) {
1144
+ throw new Error(`There should not be included data on a Meta document`);
1145
+ }
1146
+ })(!isMetaDocument(doc)) : {};
1147
+ resourceDocument.included = included;
1148
+ }
1149
+ const request = doc.request;
1150
+ const identifier = request ? this._capabilities.identifierCache.getOrCreateDocumentIdentifier(request) : null;
1151
+ if (identifier) {
1152
+ resourceDocument.lid = identifier.lid;
1153
+
1154
+ // @ts-expect-error
1155
+ doc.content = resourceDocument;
1156
+ const hasExisting = this.__documents.has(identifier.lid);
1157
+ this.__documents.set(identifier.lid, doc);
1158
+ this._capabilities.notifyChange(identifier, hasExisting ? 'updated' : 'added', null);
1159
+ }
1160
+ if (doc.request?.op === 'findHasMany') {
1161
+ const parentIdentifier = doc.request.options?.identifier;
1162
+ const parentField = doc.request.options?.field;
1163
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1164
+ if (!test) {
1165
+ throw new Error(`Expected a hasMany field`);
1166
+ }
1167
+ })(parentField?.kind === 'hasMany') : {};
1168
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1169
+ if (!test) {
1170
+ throw new Error(`Expected a parent identifier for a findHasMany request`);
1171
+ }
1172
+ })(parentIdentifier && isStableIdentifier(parentIdentifier)) : {};
1173
+ if (parentField && parentIdentifier) {
1174
+ this.__graph.push({
1175
+ op: 'updateRelationship',
1176
+ record: parentIdentifier,
1177
+ field: parentField.name,
1178
+ value: resourceDocument
1179
+ });
1180
+ }
1181
+ }
1182
+ return resourceDocument;
1183
+ }
1184
+
1185
+ /**
1186
+ * Update the "remote" or "canonical" (persisted) state of the Cache
1187
+ * by merging new information into the existing state.
1188
+ *
1189
+ * @public
1190
+ * @param {Operation|Operation[]} op the operation or list of operations to perform
1191
+ * @return {void}
1192
+ */
1193
+ patch(op) {
1194
+ if (Array.isArray(op)) {
1195
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1196
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1197
+ logGroup('cache', 'patch', '<BATCH>', String(op.length) + ' operations', '', '');
1198
+ }
1199
+ }
1200
+ upgradeCapabilities(this._capabilities);
1201
+ this._capabilities._store._join(() => {
1202
+ for (const operation of op) {
1203
+ patchCache(this, operation);
1204
+ }
1205
+ });
1206
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1207
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1208
+ // eslint-disable-next-line no-console
1209
+ console.groupEnd();
1210
+ }
1211
+ }
1212
+ } else {
1213
+ patchCache(this, op);
1214
+ }
1215
+ }
1216
+
1217
+ /**
1218
+ * Update the "local" or "current" (unpersisted) state of the Cache
1219
+ *
1220
+ * @param {Mutation} mutation
1221
+ * @return {void}
1222
+ * @public
1223
+ */
1224
+ mutate(mutation) {
1225
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1226
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1227
+ logGroup('cache', 'mutate', mutation.record.type, mutation.record.lid, mutation.field, mutation.op);
1228
+ try {
1229
+ const _data = JSON.parse(JSON.stringify(mutation));
1230
+ // eslint-disable-next-line no-console
1231
+ console.log(_data);
1232
+ } catch {
1233
+ // eslint-disable-next-line no-console
1234
+ console.log(mutation);
1235
+ }
1236
+ }
1237
+ }
1238
+ this.__graph.update(mutation, false);
1239
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1240
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1241
+ // eslint-disable-next-line no-console
1242
+ console.groupEnd();
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ /**
1248
+ * Peek resource data from the Cache.
1249
+ *
1250
+ * In development, if the return value
1251
+ * is JSON the return value
1252
+ * will be deep-cloned and deep-frozen
1253
+ * to prevent mutation thereby enforcing cache
1254
+ * Immutability.
1255
+ *
1256
+ * This form of peek is useful for implementations
1257
+ * that want to feed raw-data from cache to the UI
1258
+ * or which want to interact with a blob of data
1259
+ * directly from the presentation cache.
1260
+ *
1261
+ * An implementation might want to do this because
1262
+ * de-referencing records which read from their own
1263
+ * blob is generally safer because the record does
1264
+ * not require retainining connections to the Store
1265
+ * and Cache to present data on a per-field basis.
1266
+ *
1267
+ * This generally takes the place of `getAttr` as
1268
+ * an API and may even take the place of `getRelationship`
1269
+ * depending on implementation specifics, though this
1270
+ * latter usage is less recommended due to the advantages
1271
+ * of the Graph handling necessary entanglements and
1272
+ * notifications for relational data.
1273
+ *
1274
+ * @public
1275
+ * @param {StableRecordIdentifier | StableDocumentIdentifier} identifier
1276
+ * @return {ResourceDocument | ResourceObject | null} the known resource data
1277
+ */
1278
+
1279
+ peek(identifier) {
1280
+ if ('type' in identifier) {
1281
+ const peeked = this.__safePeek(identifier, false);
1282
+ if (!peeked) {
1283
+ return null;
1284
+ }
1285
+ const {
1286
+ type,
1287
+ id,
1288
+ lid
1289
+ } = identifier;
1290
+ const attributes = Object.assign({}, peeked.remoteAttrs, peeked.inflightAttrs, peeked.localAttrs);
1291
+ const relationships = {};
1292
+ const rels = this.__graph.identifiers.get(identifier);
1293
+ if (rels) {
1294
+ Object.keys(rels).forEach(key => {
1295
+ const rel = rels[key];
1296
+ if (rel.definition.isImplicit) {
1297
+ return;
1298
+ } else {
1299
+ relationships[key] = this.__graph.getData(identifier, key);
1300
+ }
1301
+ });
1302
+ }
1303
+ upgradeCapabilities(this._capabilities);
1304
+ const store = this._capabilities._store;
1305
+ const attrs = this._capabilities.schema.fields(identifier);
1306
+ attrs.forEach((attr, key) => {
1307
+ if (attr.kind === 'alias') {
1308
+ return;
1309
+ }
1310
+ if (key in attributes && attributes[key] !== undefined) {
1311
+ return;
1312
+ }
1313
+ const defaultValue = getDefaultValue(attr, identifier, store);
1314
+ if (defaultValue !== undefined) {
1315
+ attributes[key] = defaultValue;
1316
+ }
1317
+ });
1318
+ return {
1319
+ type,
1320
+ id,
1321
+ lid,
1322
+ attributes,
1323
+ relationships
1324
+ };
1325
+ }
1326
+ const document = this.peekRequest(identifier);
1327
+ if (document) {
1328
+ if ('content' in document) return document.content;
1329
+ }
1330
+ return null;
1331
+ }
1332
+ peekRemoteState(identifier) {
1333
+ if ('type' in identifier) {
1334
+ const peeked = this.__safePeek(identifier, false);
1335
+ if (!peeked) {
1336
+ return null;
1337
+ }
1338
+ const {
1339
+ type,
1340
+ id,
1341
+ lid
1342
+ } = identifier;
1343
+ const attributes = Object.assign({}, peeked.remoteAttrs);
1344
+ const relationships = {};
1345
+ const rels = this.__graph.identifiers.get(identifier);
1346
+ if (rels) {
1347
+ Object.keys(rels).forEach(key => {
1348
+ const rel = rels[key];
1349
+ if (rel.definition.isImplicit) {
1350
+ return;
1351
+ } else {
1352
+ relationships[key] = this.__graph.getData(identifier, key);
1353
+ }
1354
+ });
1355
+ }
1356
+ upgradeCapabilities(this._capabilities);
1357
+ const store = this._capabilities._store;
1358
+ const attrs = this._capabilities.schema.fields(identifier);
1359
+ attrs.forEach((attr, key) => {
1360
+ if (key in attributes && attributes[key] !== undefined) {
1361
+ return;
1362
+ }
1363
+ const defaultValue = getDefaultValue(attr, identifier, store);
1364
+ if (defaultValue !== undefined) {
1365
+ attributes[key] = defaultValue;
1366
+ }
1367
+ });
1368
+ return {
1369
+ type,
1370
+ id,
1371
+ lid,
1372
+ attributes,
1373
+ relationships
1374
+ };
1375
+ }
1376
+ const document = this.peekRequest(identifier);
1377
+ if (document) {
1378
+ if ('content' in document) return document.content;
1379
+ }
1380
+ return null;
1381
+ }
1382
+ /**
1383
+ * Peek the Cache for the existing request data associated with
1384
+ * a cacheable request.
1385
+ *
1386
+ * This is effectively the reverse of `put` for a request in
1387
+ * that it will return the the request, response, and content
1388
+ * whereas `peek` will return just the `content`.
1389
+ *
1390
+ * @param {StableDocumentIdentifier}
1391
+ * @return {StructuredDocument<ResourceDocument> | null}
1392
+ * @public
1393
+ */
1394
+ peekRequest(identifier) {
1395
+ return this.__documents.get(identifier.lid) || null;
1396
+ }
1397
+
1398
+ /**
1399
+ * Push resource data from a remote source into the cache for this identifier
1400
+ *
1401
+ * @public
1402
+ * @param identifier
1403
+ * @param data
1404
+ * @param hasRecord
1405
+ * @return {void | string[]} if `hasRecord` is true then calculated key changes should be returned
1406
+ */
1407
+ upsert(identifier, data, calculateChanges) {
1408
+ upgradeCapabilities(this._capabilities);
1409
+ const store = this._capabilities._store;
1410
+ if (!store._cbs) {
1411
+ let result = undefined;
1412
+ store._run(() => {
1413
+ result = cacheUpsert(this, identifier, data, calculateChanges);
1414
+ });
1415
+ return result;
1416
+ }
1417
+ return cacheUpsert(this, identifier, data, calculateChanges);
1418
+ }
1419
+
1420
+ // Cache Forking Support
1421
+ // =====================
1422
+
1423
+ /**
1424
+ * Create a fork of the cache from the current state.
1425
+ *
1426
+ * Applications should typically not call this method themselves,
1427
+ * preferring instead to fork at the Store level, which will
1428
+ * utilize this method to fork the cache.
1429
+ *
1430
+ * @internal
1431
+ * @return {Promise<Cache>}
1432
+ */
1433
+ fork() {
1434
+ throw new Error(`Not Implemented`);
1435
+ }
1436
+
1437
+ /**
1438
+ * Merge a fork back into a parent Cache.
1439
+ *
1440
+ * Applications should typically not call this method themselves,
1441
+ * preferring instead to merge at the Store level, which will
1442
+ * utilize this method to merge the caches.
1443
+ *
1444
+ * @param {Cache} cache
1445
+ * @public
1446
+ * @return {Promise<void>}
1447
+ */
1448
+ merge(cache) {
1449
+ throw new Error(`Not Implemented`);
1450
+ }
1451
+
1452
+ /**
1453
+ * Generate the list of changes applied to all
1454
+ * record in the store.
1455
+ *
1456
+ * Each individual resource or document that has
1457
+ * been mutated should be described as an individual
1458
+ * `Change` entry in the returned array.
1459
+ *
1460
+ * A `Change` is described by an object containing up to
1461
+ * three properties: (1) the `identifier` of the entity that
1462
+ * changed; (2) the `op` code of that change being one of
1463
+ * `upsert` or `remove`, and if the op is `upsert` a `patch`
1464
+ * containing the data to merge into the cache for the given
1465
+ * entity.
1466
+ *
1467
+ * This `patch` is opaque to the Store but should be understood
1468
+ * by the Cache and may expect to be utilized by an Adapter
1469
+ * when generating data during a `save` operation.
1470
+ *
1471
+ * It is generally recommended that the `patch` contain only
1472
+ * the updated state, ignoring fields that are unchanged
1473
+ *
1474
+ * ```ts
1475
+ * interface Change {
1476
+ * identifier: StableRecordIdentifier | StableDocumentIdentifier;
1477
+ * op: 'upsert' | 'remove';
1478
+ * patch?: unknown;
1479
+ * }
1480
+ * ```
1481
+ *
1482
+ * @public
1483
+ */
1484
+ diff() {
1485
+ throw new Error(`Not Implemented`);
1486
+ }
1487
+
1488
+ // SSR Support
1489
+ // ===========
1490
+
1491
+ /**
1492
+ * Serialize the entire contents of the Cache into a Stream
1493
+ * which may be fed back into a new instance of the same Cache
1494
+ * via `cache.hydrate`.
1495
+ *
1496
+ * @return {Promise<ReadableStream>}
1497
+ * @public
1498
+ */
1499
+ dump() {
1500
+ throw new Error(`Not Implemented`);
1501
+ }
1502
+
1503
+ /**
1504
+ * hydrate a Cache from a Stream with content previously serialized
1505
+ * from another instance of the same Cache, resolving when hydration
1506
+ * is complete.
1507
+ *
1508
+ * This method should expect to be called both in the context of restoring
1509
+ * the Cache during application rehydration after SSR **AND** at unknown
1510
+ * times during the lifetime of an already booted application when it is
1511
+ * desired to bulk-load additional information into the cache. This latter
1512
+ * behavior supports optimizing pre/fetching of data for route transitions
1513
+ * via data-only SSR modes.
1514
+ *
1515
+ * @param {ReadableStream} stream
1516
+ * @return {Promise<void>}
1517
+ * @public
1518
+ */
1519
+ hydrate(stream) {
1520
+ throw new Error('Not Implemented');
1521
+ }
1522
+
1523
+ // Resource Support
1524
+ // ================
1525
+
1526
+ /**
1527
+ * [LIFECYCLE] Signal to the cache that a new record has been instantiated on the client
1528
+ *
1529
+ * It returns properties from options that should be set on the record during the create
1530
+ * process. This return value behavior is deprecated.
1531
+ *
1532
+ * @public
1533
+ * @param identifier
1534
+ * @param createArgs
1535
+ */
1536
+ clientDidCreate(identifier, options) {
1537
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1538
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1539
+ try {
1540
+ const _data = options ? JSON.parse(JSON.stringify(options)) : options;
1541
+ // eslint-disable-next-line no-console
1542
+ console.log(`WarpDrive | Mutation - clientDidCreate ${identifier.lid}`, _data);
1543
+ } catch {
1544
+ // eslint-disable-next-line no-console
1545
+ console.log(`WarpDrive | Mutation - clientDidCreate ${identifier.lid}`, options);
1546
+ }
1547
+ }
1548
+ }
1549
+ const cached = this._createCache(identifier);
1550
+ cached.isNew = true;
1551
+ const createOptions = {};
1552
+ if (options !== undefined) {
1553
+ const storeWrapper = this._capabilities;
1554
+ const fields = storeWrapper.schema.fields(identifier);
1555
+ const graph = this.__graph;
1556
+ const propertyNames = Object.keys(options);
1557
+ for (let i = 0; i < propertyNames.length; i++) {
1558
+ const name = propertyNames[i];
1559
+ const propertyValue = options[name];
1560
+ if (name === 'id') {
1561
+ continue;
1562
+ }
1563
+ const fieldType = fields.get(name);
1564
+ const kind = fieldType !== undefined ? 'kind' in fieldType ? fieldType.kind : 'attribute' : null;
1565
+ let relationship;
1566
+ switch (kind) {
1567
+ case 'attribute':
1568
+ this.setAttr(identifier, name, propertyValue);
1569
+ createOptions[name] = propertyValue;
1570
+ break;
1571
+ case 'belongsTo':
1572
+ this.mutate({
1573
+ op: 'replaceRelatedRecord',
1574
+ field: name,
1575
+ record: identifier,
1576
+ value: propertyValue
1577
+ });
1578
+ relationship = graph.get(identifier, name);
1579
+ relationship.state.hasReceivedData = true;
1580
+ relationship.state.isEmpty = false;
1581
+ break;
1582
+ case 'hasMany':
1583
+ this.mutate({
1584
+ op: 'replaceRelatedRecords',
1585
+ field: name,
1586
+ record: identifier,
1587
+ value: propertyValue
1588
+ });
1589
+ relationship = graph.get(identifier, name);
1590
+ relationship.state.hasReceivedData = true;
1591
+ relationship.state.isEmpty = false;
1592
+ break;
1593
+ default:
1594
+ // reflect back (pass-thru) unknown properties
1595
+ createOptions[name] = propertyValue;
1596
+ }
1597
+ }
1598
+ }
1599
+ this._capabilities.notifyChange(identifier, 'added', null);
1600
+ return createOptions;
1601
+ }
1602
+
1603
+ /**
1604
+ * [LIFECYCLE] Signals to the cache that a resource
1605
+ * will be part of a save transaction.
1606
+ *
1607
+ * @public
1608
+ * @param identifier
1609
+ */
1610
+ willCommit(identifier) {
1611
+ const cached = this.__peek(identifier, false);
1612
+
1613
+ /*
1614
+ if we have multiple saves in flight at once then
1615
+ we have information loss no matter what. This
1616
+ attempts to lose the least information.
1617
+ If we were to clear inflightAttrs, previous requests
1618
+ would not be able to use it during their didCommit.
1619
+ If we upsert inflightattrs, previous requests incorrectly
1620
+ see more recent inflight changes as part of their own and
1621
+ will incorrectly mark the new state as the correct remote state.
1622
+ We choose this latter behavior to avoid accidentally removing
1623
+ earlier changes.
1624
+ If apps do not want this behavior they can either
1625
+ - chain save requests serially vs allowing concurrent saves
1626
+ - move to using a request handler that caches the inflight state
1627
+ on a per-request basis
1628
+ - change their save requests to only send a "PATCH" instead of a "PUT"
1629
+ so that only latest changes are involved in each request, and then also
1630
+ ensure that the API or their handler reflects only those changes back
1631
+ for upsert into the cache.
1632
+ */
1633
+ if (cached.inflightAttrs) {
1634
+ if (cached.localAttrs) {
1635
+ Object.assign(cached.inflightAttrs, cached.localAttrs);
1636
+ }
1637
+ } else {
1638
+ cached.inflightAttrs = cached.localAttrs;
1639
+ }
1640
+ cached.localAttrs = null;
1641
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
1642
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.deprecations.DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE)) {
1643
+ // save off info about saved relationships
1644
+ const fields = this._capabilities.schema.fields(identifier);
1645
+ fields.forEach((schema, name) => {
1646
+ if (schema.kind === 'belongsTo') {
1647
+ if (this.__graph._isDirty(identifier, name)) {
1648
+ const relationshipData = this.__graph.getData(identifier, name);
1649
+ const inFlight = cached.inflightRelationships = cached.inflightRelationships || Object.create(null);
1650
+ inFlight[name] = relationshipData;
1651
+ }
1652
+ }
1653
+ });
1654
+ }
1655
+ }
1656
+ }
1657
+
1658
+ /**
1659
+ * [LIFECYCLE] Signals to the cache that a resource
1660
+ * was successfully updated as part of a save transaction.
1661
+ *
1662
+ * @public
1663
+ * @param identifier
1664
+ * @param data
1665
+ */
1666
+ didCommit(committedIdentifier, result) {
1667
+ const payload = result.content;
1668
+ const operation = result.request.op;
1669
+ const data = payload && payload.data;
1670
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
1671
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
1672
+ try {
1673
+ const payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
1674
+ // eslint-disable-next-line no-console
1675
+ console.log(`WarpDrive | Payload - ${operation}`, payloadCopy);
1676
+ } catch {
1677
+ // eslint-disable-next-line no-console
1678
+ console.log(`WarpDrive | Payload - ${operation}`, payload);
1679
+ }
1680
+ }
1681
+ }
1682
+ if (!data) {
1683
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1684
+ if (!test) {
1685
+ throw new Error(`Your ${committedIdentifier.type} record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.`);
1686
+ }
1687
+ })(committedIdentifier.id) : {};
1688
+ }
1689
+ const {
1690
+ identifierCache
1691
+ } = this._capabilities;
1692
+ const existingId = committedIdentifier.id;
1693
+ const identifier = operation !== 'deleteRecord' && data ? identifierCache.updateRecordIdentifier(committedIdentifier, data) : committedIdentifier;
1694
+ const cached = this.__peek(identifier, false);
1695
+ if (cached.isDeleted) {
1696
+ this.__graph.push({
1697
+ op: 'deleteRecord',
1698
+ record: identifier,
1699
+ isNew: false
1700
+ });
1701
+ cached.isDeletionCommitted = true;
1702
+ this._capabilities.notifyChange(identifier, 'removed', null);
1703
+ // TODO @runspired should we early exit here?
1704
+ }
1705
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
1706
+ if (cached.isNew && !identifier.id && (typeof data?.id !== 'string' || data.id.length > 0)) {
1707
+ const error = new Error(`Expected an id ${String(identifier)} in response ${JSON.stringify(data)}`);
1708
+ //@ts-expect-error
1709
+ error.isAdapterError = true;
1710
+ //@ts-expect-error
1711
+ error.code = 'InvalidError';
1712
+ throw error;
1713
+ }
1714
+ }
1715
+ const fields = this._capabilities.schema.fields(identifier);
1716
+ cached.isNew = false;
1717
+ let newCanonicalAttributes;
1718
+ if (data) {
1719
+ if (data.id && !cached.id) {
1720
+ cached.id = data.id;
1721
+ }
1722
+ if (identifier === committedIdentifier && identifier.id !== existingId) {
1723
+ this._capabilities.notifyChange(identifier, 'identity', null);
1724
+ }
1725
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1726
+ if (!test) {
1727
+ throw new Error(`Expected the ID received for the primary '${identifier.type}' resource being saved to match the current id '${cached.id}' but received '${identifier.id}'.`);
1728
+ }
1729
+ })(identifier.id === cached.id) : {};
1730
+ if (data.relationships) {
1731
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
1732
+ if (macroCondition(!getGlobalConfig().WarpDriveMirror.deprecations.DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE)) {
1733
+ // assert against bad API behavior where a belongsTo relationship
1734
+ // is saved but the return payload indicates a different final state.
1735
+ fields.forEach((field, name) => {
1736
+ if (field.kind === 'belongsTo') {
1737
+ const relationshipData = data.relationships[name]?.data;
1738
+ if (relationshipData !== undefined) {
1739
+ const inFlightData = cached.inflightRelationships?.[name];
1740
+ if (!inFlightData || !('data' in inFlightData)) {
1741
+ return;
1742
+ }
1743
+ const actualData = relationshipData ? this._capabilities.identifierCache.getOrCreateRecordIdentifier(relationshipData) : null;
1744
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1745
+ if (!test) {
1746
+ throw new Error(`Expected the resource relationship '<${identifier.type}>.${name}' on ${identifier.lid} to be saved as ${inFlightData.data ? inFlightData.data.lid : '<null>'} but it was saved as ${actualData ? actualData.lid : '<null>'}`);
1747
+ }
1748
+ })(inFlightData.data === actualData) : {};
1749
+ }
1750
+ }
1751
+ });
1752
+ cached.inflightRelationships = null;
1753
+ }
1754
+ }
1755
+ setupRelationships(this.__graph, fields, identifier, data);
1756
+ }
1757
+ newCanonicalAttributes = data.attributes;
1758
+ }
1759
+ const changedKeys = newCanonicalAttributes && calculateChangedKeys(cached, newCanonicalAttributes, fields);
1760
+ cached.remoteAttrs = Object.assign(cached.remoteAttrs || Object.create(null), cached.inflightAttrs, newCanonicalAttributes);
1761
+ cached.inflightAttrs = null;
1762
+ patchLocalAttributes(cached, changedKeys);
1763
+ if (cached.errors) {
1764
+ cached.errors = null;
1765
+ this._capabilities.notifyChange(identifier, 'errors', null);
1766
+ }
1767
+ if (changedKeys?.size) notifyAttributes(this._capabilities, identifier, changedKeys);
1768
+ this._capabilities.notifyChange(identifier, 'state', null);
1769
+ const included = payload && payload.included;
1770
+ if (included) {
1771
+ for (let i = 0, length = included.length; i < length; i++) {
1772
+ putOne(this, identifierCache, included[i]);
1773
+ }
1774
+ }
1775
+ return {
1776
+ data: identifier
1777
+ };
1778
+ }
1779
+
1780
+ /**
1781
+ * [LIFECYCLE] Signals to the cache that a resource
1782
+ * was update via a save transaction failed.
1783
+ *
1784
+ * @public
1785
+ * @param identifier
1786
+ * @param errors
1787
+ */
1788
+ commitWasRejected(identifier, errors) {
1789
+ const cached = this.__peek(identifier, false);
1790
+ if (cached.inflightAttrs) {
1791
+ const keys = Object.keys(cached.inflightAttrs);
1792
+ if (keys.length > 0) {
1793
+ const attrs = cached.localAttrs = cached.localAttrs || Object.create(null);
1794
+ for (let i = 0; i < keys.length; i++) {
1795
+ if (attrs[keys[i]] === undefined) {
1796
+ attrs[keys[i]] = cached.inflightAttrs[keys[i]];
1797
+ }
1798
+ }
1799
+ }
1800
+ cached.inflightAttrs = null;
1801
+ }
1802
+ if (errors) {
1803
+ cached.errors = errors;
1804
+ }
1805
+ this._capabilities.notifyChange(identifier, 'errors', null);
1806
+ }
1807
+
1808
+ /**
1809
+ * [LIFECYCLE] Signals to the cache that all data for a resource
1810
+ * should be cleared.
1811
+ *
1812
+ * This method is a candidate to become a mutation
1813
+ *
1814
+ * @public
1815
+ * @param identifier
1816
+ */
1817
+ unloadRecord(identifier) {
1818
+ const storeWrapper = this._capabilities;
1819
+ // TODO this is necessary because
1820
+ // we maintain memebership inside InstanceCache
1821
+ // for peekAll, so even though we haven't created
1822
+ // any data we think this exists.
1823
+ // TODO can we eliminate that membership now?
1824
+ if (!this.__cache.has(identifier)) {
1825
+ // the graph may still need to unload identity
1826
+ peekGraph(storeWrapper)?.unload(identifier);
1827
+ return;
1828
+ }
1829
+ const removeFromRecordArray = !this.isDeletionCommitted(identifier);
1830
+ let removed = false;
1831
+ const cached = this.__peek(identifier, false);
1832
+ if (cached.isNew || cached.isDeletionCommitted) {
1833
+ peekGraph(storeWrapper)?.push({
1834
+ op: 'deleteRecord',
1835
+ record: identifier,
1836
+ isNew: cached.isNew
1837
+ });
1838
+ } else {
1839
+ peekGraph(storeWrapper)?.unload(identifier);
1840
+ }
1841
+
1842
+ // effectively clearing these is ensuring that
1843
+ // we report as `isEmpty` during teardown.
1844
+ cached.localAttrs = null;
1845
+ cached.remoteAttrs = null;
1846
+ cached.defaultAttrs = null;
1847
+ cached.inflightAttrs = null;
1848
+ const relatedIdentifiers = _allRelatedIdentifiers(storeWrapper, identifier);
1849
+ if (areAllModelsUnloaded(storeWrapper, relatedIdentifiers)) {
1850
+ for (let i = 0; i < relatedIdentifiers.length; ++i) {
1851
+ const relatedIdentifier = relatedIdentifiers[i];
1852
+ storeWrapper.notifyChange(relatedIdentifier, 'removed', null);
1853
+ removed = true;
1854
+ storeWrapper.disconnectRecord(relatedIdentifier);
1855
+ }
1856
+ }
1857
+ this.__cache.delete(identifier);
1858
+ this.__destroyedCache.set(identifier, cached);
1859
+
1860
+ /*
1861
+ * The destroy cache is a hack to prevent applications
1862
+ * from blowing up during teardown. Accessing state
1863
+ * on a destroyed record is not safe, but historically
1864
+ * was possible due to a combination of teardown timing
1865
+ * and retention of cached state directly on the
1866
+ * record itself.
1867
+ *
1868
+ * Once we have deprecated accessing state on a destroyed
1869
+ * instance we may remove this. The timing isn't a huge deal
1870
+ * as momentarily retaining the objects outside the bounds
1871
+ * of a test won't cause issues.
1872
+ */
1873
+ if (this.__destroyedCache.size === 1) {
1874
+ // TODO do we still need this?
1875
+ setTimeout(() => {
1876
+ this.__destroyedCache.clear();
1877
+ }, 100);
1878
+ }
1879
+ if (!removed && removeFromRecordArray) {
1880
+ storeWrapper.notifyChange(identifier, 'removed', null);
1881
+ }
1882
+ }
1883
+
1884
+ // Granular Resource Data APIs
1885
+ // ===========================
1886
+
1887
+ /**
1888
+ * Retrieve the data for an attribute from the cache
1889
+ *
1890
+ * @public
1891
+ * @param identifier
1892
+ * @param field
1893
+ * @return {unknown}
1894
+ */
1895
+ getAttr(identifier, attr) {
1896
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
1897
+ if (Array.isArray(attr) && attr.length === 1) {
1898
+ attr = attr[0];
1899
+ }
1900
+ if (isSimplePath) {
1901
+ const attribute = attr;
1902
+ const cached = this.__peek(identifier, true);
1903
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1904
+ if (!test) {
1905
+ throw new Error(`Cannot retrieve attributes for identifier ${String(identifier)} as it is not present in the cache`);
1906
+ }
1907
+ })(cached) : {};
1908
+
1909
+ // in Prod we try to recover when accessing something that
1910
+ // doesn't exist
1911
+ if (!cached) {
1912
+ return undefined;
1913
+ }
1914
+ if (cached.localAttrs && attribute in cached.localAttrs) {
1915
+ return cached.localAttrs[attribute];
1916
+ } else if (cached.inflightAttrs && attribute in cached.inflightAttrs) {
1917
+ return cached.inflightAttrs[attribute];
1918
+ } else if (cached.remoteAttrs && attribute in cached.remoteAttrs) {
1919
+ return cached.remoteAttrs[attribute];
1920
+ } else if (cached.defaultAttrs && attribute in cached.defaultAttrs) {
1921
+ return cached.defaultAttrs[attribute];
1922
+ } else {
1923
+ const attrSchema = this._capabilities.schema.fields(identifier).get(attribute);
1924
+ upgradeCapabilities(this._capabilities);
1925
+ const defaultValue = getDefaultValue(attrSchema, identifier, this._capabilities._store);
1926
+ if (schemaHasLegacyDefaultValueFn(attrSchema)) {
1927
+ cached.defaultAttrs = cached.defaultAttrs || Object.create(null);
1928
+ cached.defaultAttrs[attribute] = defaultValue;
1929
+ }
1930
+ return defaultValue;
1931
+ }
1932
+ }
1933
+
1934
+ // TODO @runspired consider whether we need a defaultValue cache in ReactiveResource
1935
+ // like we do for the simple case above.
1936
+ const path = attr;
1937
+ const cached = this.__peek(identifier, true);
1938
+ const basePath = path[0];
1939
+ let current = cached.localAttrs && basePath in cached.localAttrs ? cached.localAttrs[basePath] : undefined;
1940
+ if (current === undefined) {
1941
+ current = cached.inflightAttrs && basePath in cached.inflightAttrs ? cached.inflightAttrs[basePath] : undefined;
1942
+ }
1943
+ if (current === undefined) {
1944
+ current = cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
1945
+ }
1946
+ if (current === undefined) {
1947
+ return undefined;
1948
+ }
1949
+ for (let i = 1; i < path.length; i++) {
1950
+ current = current[path[i]];
1951
+ if (current === undefined) {
1952
+ return undefined;
1953
+ }
1954
+ }
1955
+ return current;
1956
+ }
1957
+ getRemoteAttr(identifier, attr) {
1958
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
1959
+ if (Array.isArray(attr) && attr.length === 1) {
1960
+ attr = attr[0];
1961
+ }
1962
+ if (isSimplePath) {
1963
+ const attribute = attr;
1964
+ const cached = this.__peek(identifier, true);
1965
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1966
+ if (!test) {
1967
+ throw new Error(`Cannot retrieve remote attributes for identifier ${String(identifier)} as it is not present in the cache`);
1968
+ }
1969
+ })(cached) : {};
1970
+
1971
+ // in Prod we try to recover when accessing something that
1972
+ // doesn't exist
1973
+ if (!cached) {
1974
+ return undefined;
1975
+ }
1976
+ if (cached.remoteAttrs && attribute in cached.remoteAttrs) {
1977
+ return cached.remoteAttrs[attribute];
1978
+
1979
+ // we still show defaultValues in the case of a remoteAttr access
1980
+ } else if (cached.defaultAttrs && attribute in cached.defaultAttrs) {
1981
+ return cached.defaultAttrs[attribute];
1982
+ } else {
1983
+ const attrSchema = this._capabilities.schema.fields(identifier).get(attribute);
1984
+ upgradeCapabilities(this._capabilities);
1985
+ const defaultValue = getDefaultValue(attrSchema, identifier, this._capabilities._store);
1986
+ if (schemaHasLegacyDefaultValueFn(attrSchema)) {
1987
+ cached.defaultAttrs = cached.defaultAttrs || Object.create(null);
1988
+ cached.defaultAttrs[attribute] = defaultValue;
1989
+ }
1990
+ return defaultValue;
1991
+ }
1992
+ }
1993
+
1994
+ // TODO @runspired consider whether we need a defaultValue cache in ReactiveResource
1995
+ // like we do for the simple case above.
1996
+ const path = attr;
1997
+ const cached = this.__peek(identifier, true);
1998
+ const basePath = path[0];
1999
+ let current = cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
2000
+ if (current === undefined) {
2001
+ return undefined;
2002
+ }
2003
+ for (let i = 1; i < path.length; i++) {
2004
+ current = current[path[i]];
2005
+ if (current === undefined) {
2006
+ return undefined;
2007
+ }
2008
+ }
2009
+ return current;
2010
+ }
2011
+
2012
+ /**
2013
+ * Mutate the data for an attribute in the cache
2014
+ *
2015
+ * This method is a candidate to become a mutation
2016
+ *
2017
+ * @public
2018
+ * @param identifier
2019
+ * @param field
2020
+ * @param value
2021
+ */
2022
+ setAttr(identifier, attr, value) {
2023
+ // this assert works to ensure we have a non-empty string and/or a non-empty array
2024
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2025
+ if (!test) {
2026
+ throw new Error('setAttr must receive at least one attribute path');
2027
+ }
2028
+ })(attr.length > 0) : {};
2029
+ const isSimplePath = !Array.isArray(attr) || attr.length === 1;
2030
+ if (Array.isArray(attr) && attr.length === 1) {
2031
+ attr = attr[0];
2032
+ }
2033
+ if (isSimplePath) {
2034
+ const cached = this.__peek(identifier, false);
2035
+ const currentAttr = attr;
2036
+ const existing = cached.inflightAttrs && currentAttr in cached.inflightAttrs ? cached.inflightAttrs[currentAttr] : cached.remoteAttrs && currentAttr in cached.remoteAttrs ? cached.remoteAttrs[currentAttr] : undefined;
2037
+ if (existing !== value) {
2038
+ cached.localAttrs = cached.localAttrs || Object.create(null);
2039
+ cached.localAttrs[currentAttr] = value;
2040
+ cached.changes = cached.changes || Object.create(null);
2041
+ cached.changes[currentAttr] = [existing, value];
2042
+ } else if (cached.localAttrs) {
2043
+ delete cached.localAttrs[currentAttr];
2044
+ delete cached.changes[currentAttr];
2045
+ }
2046
+ if (cached.defaultAttrs && currentAttr in cached.defaultAttrs) {
2047
+ delete cached.defaultAttrs[currentAttr];
2048
+ }
2049
+ this._capabilities.notifyChange(identifier, 'attributes', currentAttr);
2050
+ return;
2051
+ }
2052
+
2053
+ // get current value from local else inflight else remote
2054
+ // structuredClone current if not local (or always?)
2055
+ // traverse path, update value at path
2056
+ // notify change at first link in path.
2057
+ // second pass optimization is change notifyChange signature to take an array path
2058
+
2059
+ // guaranteed that we have path of at least 2 in length
2060
+ const path = attr;
2061
+ const cached = this.__peek(identifier, false);
2062
+
2063
+ // get existing cache record for base path
2064
+ const basePath = path[0];
2065
+ const existing = cached.inflightAttrs && basePath in cached.inflightAttrs ? cached.inflightAttrs[basePath] : cached.remoteAttrs && basePath in cached.remoteAttrs ? cached.remoteAttrs[basePath] : undefined;
2066
+ let existingAttr;
2067
+ if (existing) {
2068
+ existingAttr = existing[path[1]];
2069
+ for (let i = 2; i < path.length; i++) {
2070
+ // the specific change we're making is at path[length - 1]
2071
+ existingAttr = existingAttr[path[i]];
2072
+ }
2073
+ }
2074
+ if (existingAttr !== value) {
2075
+ cached.localAttrs = cached.localAttrs || Object.create(null);
2076
+ cached.localAttrs[basePath] = cached.localAttrs[basePath] || structuredClone(existing);
2077
+ cached.changes = cached.changes || Object.create(null);
2078
+ let currentLocal = cached.localAttrs[basePath];
2079
+ let nextLink = 1;
2080
+ while (nextLink < path.length - 1) {
2081
+ currentLocal = currentLocal[path[nextLink++]];
2082
+ }
2083
+ currentLocal[path[nextLink]] = value;
2084
+ cached.changes[basePath] = [existing, cached.localAttrs[basePath]];
2085
+
2086
+ // since we initiaize the value as basePath as a clone of the value at the remote basePath
2087
+ // then in theory we can use JSON.stringify to compare the two values as key insertion order
2088
+ // ought to be consistent.
2089
+ // we try/catch this because users have a habit of doing "Bad Things"TM wherein the cache contains
2090
+ // stateful values that are not JSON serializable correctly such as Dates.
2091
+ // in the case that we error, we fallback to not removing the local value
2092
+ // so that any changes we don't understand are preserved. Thse objects would then sometimes
2093
+ // appear to be dirty unnecessarily, and for folks that open an issue we can guide them
2094
+ // to make their cache data less stateful.
2095
+ } else if (cached.localAttrs) {
2096
+ try {
2097
+ if (!existing) {
2098
+ return;
2099
+ }
2100
+ const existingStr = JSON.stringify(existing);
2101
+ const newStr = JSON.stringify(cached.localAttrs[basePath]);
2102
+ if (existingStr !== newStr) {
2103
+ delete cached.localAttrs[basePath];
2104
+ delete cached.changes[basePath];
2105
+ }
2106
+ } catch {
2107
+ // noop
2108
+ }
2109
+ }
2110
+ this._capabilities.notifyChange(identifier, 'attributes', basePath);
2111
+ }
2112
+
2113
+ /**
2114
+ * Query the cache for the changed attributes of a resource.
2115
+ *
2116
+ * @public
2117
+ * @param identifier
2118
+ * @return {ChangedAttributesHash} `{ <field>: [<old>, <new>] }`
2119
+ */
2120
+ changedAttrs(identifier) {
2121
+ const cached = this.__peek(identifier, false);
2122
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2123
+ if (!test) {
2124
+ throw new Error(`Cannot retrieve changed attributes for identifier ${String(identifier)} as it is not present in the cache`);
2125
+ }
2126
+ })(cached) : {};
2127
+
2128
+ // in Prod we try to recover when accessing something that
2129
+ // doesn't exist
2130
+ if (!cached) {
2131
+ return Object.create(null);
2132
+ }
2133
+
2134
+ // TODO freeze in dev
2135
+ return cached.changes || Object.create(null);
2136
+ }
2137
+
2138
+ /**
2139
+ * Query the cache for whether any mutated attributes exist
2140
+ *
2141
+ * @public
2142
+ * @param identifier
2143
+ * @return {Boolean}
2144
+ */
2145
+ hasChangedAttrs(identifier) {
2146
+ const cached = this.__peek(identifier, true);
2147
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2148
+ if (!test) {
2149
+ throw new Error(`Cannot retrieve changed attributes for identifier ${String(identifier)} as it is not present in the cache`);
2150
+ }
2151
+ })(cached) : {};
2152
+
2153
+ // in Prod we try to recover when accessing something that
2154
+ // doesn't exist
2155
+ if (!cached) {
2156
+ return false;
2157
+ }
2158
+ return cached.inflightAttrs !== null && Object.keys(cached.inflightAttrs).length > 0 || cached.localAttrs !== null && Object.keys(cached.localAttrs).length > 0;
2159
+ }
2160
+
2161
+ /**
2162
+ * Tell the cache to discard any uncommitted mutations to attributes
2163
+ *
2164
+ * This method is a candidate to become a mutation
2165
+ *
2166
+ * @public
2167
+ * @param identifier
2168
+ * @return {String[]} the names of fields that were restored
2169
+ */
2170
+ rollbackAttrs(identifier) {
2171
+ const cached = this.__peek(identifier, false);
2172
+ let dirtyKeys;
2173
+ cached.isDeleted = false;
2174
+ if (cached.localAttrs !== null) {
2175
+ dirtyKeys = Object.keys(cached.localAttrs);
2176
+ cached.localAttrs = null;
2177
+ cached.changes = null;
2178
+ }
2179
+ if (cached.isNew) {
2180
+ // > Note: Graph removal handled by unloadRecord
2181
+ cached.isDeletionCommitted = true;
2182
+ cached.isDeleted = true;
2183
+ cached.isNew = false;
2184
+ }
2185
+ cached.inflightAttrs = null;
2186
+ cached.defaultAttrs = null;
2187
+ if (cached.errors) {
2188
+ cached.errors = null;
2189
+ this._capabilities.notifyChange(identifier, 'errors', null);
2190
+ }
2191
+ this._capabilities.notifyChange(identifier, 'state', null);
2192
+ if (dirtyKeys && dirtyKeys.length) {
2193
+ notifyAttributes(this._capabilities, identifier, new Set(dirtyKeys));
2194
+ }
2195
+ return dirtyKeys || [];
2196
+ }
2197
+
2198
+ /**
2199
+ * Query the cache for the changes to relationships of a resource.
2200
+ *
2201
+ * Returns a map of relationship names to RelationshipDiff objects.
2202
+ *
2203
+ * ```ts
2204
+ * type RelationshipDiff =
2205
+ | {
2206
+ kind: 'collection';
2207
+ remoteState: StableRecordIdentifier[];
2208
+ additions: Set<StableRecordIdentifier>;
2209
+ removals: Set<StableRecordIdentifier>;
2210
+ localState: StableRecordIdentifier[];
2211
+ reordered: boolean;
2212
+ }
2213
+ | {
2214
+ kind: 'resource';
2215
+ remoteState: StableRecordIdentifier | null;
2216
+ localState: StableRecordIdentifier | null;
2217
+ };
2218
+ ```
2219
+ *
2220
+ * @public
2221
+ * @param {StableRecordIdentifier} identifier
2222
+ * @return {Map<string, RelationshipDiff>}
2223
+ */
2224
+ changedRelationships(identifier) {
2225
+ return this.__graph.getChanged(identifier);
2226
+ }
2227
+
2228
+ /**
2229
+ * Query the cache for whether any mutated relationships exist
2230
+ *
2231
+ * @public
2232
+ * @param {StableRecordIdentifier} identifier
2233
+ * @return {Boolean}
2234
+ */
2235
+ hasChangedRelationships(identifier) {
2236
+ return this.__graph.hasChanged(identifier);
2237
+ }
2238
+
2239
+ /**
2240
+ * Tell the cache to discard any uncommitted mutations to relationships.
2241
+ *
2242
+ * This will also discard the change on any appropriate inverses.
2243
+ *
2244
+ * This method is a candidate to become a mutation
2245
+ *
2246
+ * @public
2247
+ * @param {StableRecordIdentifier} identifier
2248
+ * @return {String[]} the names of relationships that were restored
2249
+ */
2250
+ rollbackRelationships(identifier) {
2251
+ upgradeCapabilities(this._capabilities);
2252
+ let result;
2253
+ this._capabilities._store._join(() => {
2254
+ result = this.__graph.rollback(identifier);
2255
+ });
2256
+ return result;
2257
+ }
2258
+
2259
+ /**
2260
+ * Query the cache for the current state of a relationship property
2261
+ *
2262
+ * @public
2263
+ * @param identifier
2264
+ * @param field
2265
+ * @return resource relationship object
2266
+ */
2267
+ getRelationship(identifier, field) {
2268
+ return this.__graph.getData(identifier, field);
2269
+ }
2270
+ getRemoteRelationship(identifier, field) {
2271
+ return this.__graph.getRemoteData(identifier, field);
2272
+ }
2273
+
2274
+ // Resource State
2275
+ // ===============
2276
+
2277
+ /**
2278
+ * Update the cache state for the given resource to be marked
2279
+ * as locally deleted, or remove such a mark.
2280
+ *
2281
+ * This method is a candidate to become a mutation
2282
+ *
2283
+ * @public
2284
+ * @param identifier
2285
+ * @param {Boolean} isDeleted
2286
+ */
2287
+ setIsDeleted(identifier, isDeleted) {
2288
+ const cached = this.__peek(identifier, false);
2289
+ cached.isDeleted = isDeleted;
2290
+ // > Note: Graph removal for isNew handled by unloadRecord
2291
+ this._capabilities.notifyChange(identifier, 'state', null);
2292
+ }
2293
+
2294
+ /**
2295
+ * Query the cache for any validation errors applicable to the given resource.
2296
+ *
2297
+ * @public
2298
+ * @param identifier
2299
+ * @return {JsonApiError[]}
2300
+ */
2301
+ getErrors(identifier) {
2302
+ return this.__peek(identifier, true).errors || [];
2303
+ }
2304
+
2305
+ /**
2306
+ * Query the cache for whether a given resource has any available data
2307
+ *
2308
+ * @public
2309
+ * @param identifier
2310
+ * @return {Boolean}
2311
+ */
2312
+ isEmpty(identifier) {
2313
+ const cached = this.__safePeek(identifier, true);
2314
+ return cached ? cached.remoteAttrs === null && cached.inflightAttrs === null && cached.localAttrs === null : true;
2315
+ }
2316
+
2317
+ /**
2318
+ * Query the cache for whether a given resource was created locally and not
2319
+ * yet persisted.
2320
+ *
2321
+ * @public
2322
+ * @param identifier
2323
+ * @return {Boolean}
2324
+ */
2325
+ isNew(identifier) {
2326
+ // TODO can we assert here?
2327
+ return this.__safePeek(identifier, true)?.isNew || false;
2328
+ }
2329
+
2330
+ /**
2331
+ * Query the cache for whether a given resource is marked as deleted (but not
2332
+ * necessarily persisted yet).
2333
+ *
2334
+ * @public
2335
+ * @param identifier
2336
+ * @return {Boolean}
2337
+ */
2338
+ isDeleted(identifier) {
2339
+ // TODO can we assert here?
2340
+ return this.__safePeek(identifier, true)?.isDeleted || false;
2341
+ }
2342
+
2343
+ /**
2344
+ * Query the cache for whether a given resource has been deleted and that deletion
2345
+ * has also been persisted.
2346
+ *
2347
+ * @public
2348
+ * @param identifier
2349
+ * @return {Boolean}
2350
+ */
2351
+ isDeletionCommitted(identifier) {
2352
+ // TODO can we assert here?
2353
+ return this.__safePeek(identifier, true)?.isDeletionCommitted || false;
2354
+ }
2355
+
2356
+ /**
2357
+ * Private method used to populate an entry for the identifier
2358
+ *
2359
+ * @internal
2360
+ * @param {StableRecordIdentifier} identifier
2361
+ * @return {CachedResource}
2362
+ */
2363
+ _createCache(identifier) {
2364
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2365
+ if (!test) {
2366
+ throw new Error(`Expected no resource data to yet exist in the cache`);
2367
+ }
2368
+ })(!this.__cache.has(identifier)) : {};
2369
+ const cache = makeCache();
2370
+ this.__cache.set(identifier, cache);
2371
+ return cache;
2372
+ }
2373
+
2374
+ /**
2375
+ * Peek whether we have cached resource data matching the identifier
2376
+ * without asserting if the resource data is missing.
2377
+ *
2378
+ * @param {StableRecordIdentifier} identifier
2379
+ * @param {Boolean} allowDestroyed
2380
+ * @internal
2381
+ * @return {CachedResource | undefined}
2382
+ */
2383
+ __safePeek(identifier, allowDestroyed) {
2384
+ let resource = this.__cache.get(identifier);
2385
+ if (!resource && allowDestroyed) {
2386
+ resource = this.__destroyedCache.get(identifier);
2387
+ }
2388
+ return resource;
2389
+ }
2390
+
2391
+ /**
2392
+ * Peek whether we have cached resource data matching the identifier
2393
+ * Asserts if the resource data is missing.
2394
+ *
2395
+ * @param {StableRecordIdentifier} identifier
2396
+ * @param {Boolean} allowDestroyed
2397
+ * @internal
2398
+ * @return {CachedResource}
2399
+ */
2400
+ __peek(identifier, allowDestroyed) {
2401
+ const resource = this.__safePeek(identifier, allowDestroyed);
2402
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2403
+ if (!test) {
2404
+ throw new Error(`Expected Cache to have a resource entry for the identifier ${String(identifier)} but none was found`);
2405
+ }
2406
+ })(resource) : {};
2407
+ return resource;
2408
+ }
2409
+ }
2410
+ function addResourceToDocument(cache, op) {
2411
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2412
+ if (!test) {
2413
+ throw new Error(`Expected field to be either 'data' or 'included'`);
2414
+ }
2415
+ })(op.field === 'data' || op.field === 'included') : {};
2416
+ const doc = cache.__documents.get(op.record.lid);
2417
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2418
+ if (!test) {
2419
+ throw new Error(`Expected to have a cached document on which to perform the add operation`);
2420
+ }
2421
+ })(doc) : {};
2422
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2423
+ if (!test) {
2424
+ throw new Error(`Expected to have content on the document`);
2425
+ }
2426
+ })(doc.content) : {};
2427
+ const {
2428
+ content
2429
+ } = doc;
2430
+ if (op.field === 'data') {
2431
+ let shouldNotify = false;
2432
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2433
+ if (!test) {
2434
+ throw new Error(`Expected to have a data property on the document`);
2435
+ }
2436
+ })('data' in content) : {};
2437
+
2438
+ // if data is not an array, we set the data property directly
2439
+ if (!Array.isArray(content.data)) {
2440
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2441
+ if (!test) {
2442
+ throw new Error(`Expected to have a single record as the operation value`);
2443
+ }
2444
+ })(op.value && !Array.isArray(op.value)) : {};
2445
+ shouldNotify = content.data !== op.value;
2446
+ if (shouldNotify) content.data = op.value;
2447
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2448
+ if (!test) {
2449
+ throw new Error(`The value '${op.value.lid}' cannot be added from the data of document '${op.record.lid}' as it is already the current value '${content.data ? content.data.lid : '<null>'}'`);
2450
+ }
2451
+ })(shouldNotify) : {};
2452
+ } else {
2453
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2454
+ if (!test) {
2455
+ throw new Error(`Expected to have a non-null operation value`);
2456
+ }
2457
+ })(op.value) : {};
2458
+ if (Array.isArray(op.value)) {
2459
+ if (op.index !== undefined) {
2460
+ // for collections, because we allow duplicates we are always changed.
2461
+ shouldNotify = true;
2462
+ content.data.splice(op.index, 0, ...op.value);
2463
+ } else {
2464
+ // for collections, because we allow duplicates we are always changed.
2465
+ shouldNotify = true;
2466
+ content.data.push(...op.value);
2467
+ }
2468
+ } else {
2469
+ if (op.index !== undefined) {
2470
+ // for collections, because we allow duplicates we are always changed.
2471
+ shouldNotify = true;
2472
+ content.data.splice(op.index, 0, op.value);
2473
+ } else {
2474
+ // for collections, because we allow duplicates we are always changed.
2475
+ shouldNotify = true;
2476
+ content.data.push(op.value);
2477
+ }
2478
+ }
2479
+ }
2480
+
2481
+ // notify
2482
+ if (shouldNotify) cache._capabilities.notifyChange(op.record, 'updated', null);
2483
+ return;
2484
+ }
2485
+ content.included = content.included || [];
2486
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2487
+ if (!test) {
2488
+ throw new Error(`Expected to have a non-null operation value`);
2489
+ }
2490
+ })(op.value) : {};
2491
+ if (Array.isArray(op.value)) {
2492
+ // included is not allowed to have duplicates, so we do a dirty check here
2493
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2494
+ if (!test) {
2495
+ throw new Error(`included should not contain duplicate members`);
2496
+ }
2497
+ })(new Set([...content.included, ...op.value]).size === content.included.length + op.value.length) : {};
2498
+ content.included = content.included.concat(op.value);
2499
+ } else {
2500
+ // included is not allowed to have duplicates, so we do a dirty check here
2501
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2502
+ if (!test) {
2503
+ throw new Error(`included should not contain duplicate members`);
2504
+ }
2505
+ })(content.included.includes(op.value) === false) : {};
2506
+ content.included.push(op.value);
2507
+ }
2508
+
2509
+ // we don't notify in the included case because this is not reactively
2510
+ // exposed. We should possibly consider doing so though for subscribers
2511
+ }
2512
+ function removeResourceFromDocument(cache, op) {
2513
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2514
+ if (!test) {
2515
+ throw new Error(`Expected field to be either 'data' or 'included'`);
2516
+ }
2517
+ })(op.field === 'data' || op.field === 'included') : {};
2518
+ const doc = cache.__documents.get(op.record.lid);
2519
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2520
+ if (!test) {
2521
+ throw new Error(`Expected to have a cached document on which to perform the remove operation`);
2522
+ }
2523
+ })(doc) : {};
2524
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2525
+ if (!test) {
2526
+ throw new Error(`Expected to have content on the document`);
2527
+ }
2528
+ })(doc.content) : {};
2529
+ const {
2530
+ content
2531
+ } = doc;
2532
+ if (op.field === 'data') {
2533
+ let shouldNotify = false;
2534
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2535
+ if (!test) {
2536
+ throw new Error(`Expected to have a data property on the document`);
2537
+ }
2538
+ })('data' in content) : {};
2539
+
2540
+ // if data is not an array, we set the data property directly
2541
+ if (!Array.isArray(content.data)) {
2542
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2543
+ if (!test) {
2544
+ throw new Error(`Expected to have a single record as the operation value`);
2545
+ }
2546
+ })(op.value && !Array.isArray(op.value)) : {};
2547
+ shouldNotify = content.data === op.value;
2548
+ // we only remove the value if it was our existing value
2549
+ if (shouldNotify) content.data = null;
2550
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2551
+ if (!test) {
2552
+ throw new Error(`The value '${op.value.lid}' cannot be removed from the data of document '${op.record.lid}' as it is not the current value '${content.data ? content.data.lid : '<null>'}'`);
2553
+ }
2554
+ })(shouldNotify) : {};
2555
+ } else {
2556
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2557
+ if (!test) {
2558
+ throw new Error(`Expected to have a non-null operation value`);
2559
+ }
2560
+ })(op.value) : {};
2561
+ const toRemove = Array.isArray(op.value) ? op.value : [op.value];
2562
+ for (let i = 0; i < toRemove.length; i++) {
2563
+ const value = toRemove[i];
2564
+ if (op.index !== undefined) {
2565
+ // in production we want to recover gracefully
2566
+ // so we fallback to first-index-of
2567
+ const index = op.index < content.data.length && content.data[op.index] === value ? op.index : content.data.indexOf(value);
2568
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2569
+ if (!test) {
2570
+ throw new Error(`Mismatched Index: Expected index '${op.index}' to contain the value '${value.lid}' but that value is at index '${index}'`);
2571
+ }
2572
+ })(op.index < content.data.length && content.data[op.index] === value) : {};
2573
+ if (index !== -1) {
2574
+ // we remove the first occurrence of the value
2575
+ shouldNotify = true;
2576
+ content.data.splice(index, 1);
2577
+ }
2578
+ } else {
2579
+ // we remove the first occurrence of the value
2580
+ const index = content.data.indexOf(value);
2581
+ if (index !== -1) {
2582
+ shouldNotify = true;
2583
+ content.data.splice(index, 1);
2584
+ }
2585
+ }
2586
+ }
2587
+ }
2588
+
2589
+ // notify
2590
+ if (shouldNotify) cache._capabilities.notifyChange(op.record, 'updated', null);
2591
+ } else {
2592
+ content.included = content.included || [];
2593
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2594
+ if (!test) {
2595
+ throw new Error(`Expected to have a non-null operation value`);
2596
+ }
2597
+ })(op.value) : {};
2598
+ const toRemove = Array.isArray(op.value) ? op.value : [op.value];
2599
+ for (const identifier of toRemove) {
2600
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2601
+ if (!test) {
2602
+ throw new Error(`attempted to remove a value from included that was not present in the included array`);
2603
+ }
2604
+ })(content.included.includes(identifier)) : {};
2605
+ const index = content.included.indexOf(identifier);
2606
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2607
+ if (!test) {
2608
+ throw new Error(`The value '${identifier.lid}' cannot be removed from the included of document '${op.record.lid}' as it is not present`);
2609
+ }
2610
+ })(index !== -1) : {};
2611
+ if (index !== -1) {
2612
+ content.included.splice(index, 1);
2613
+ }
2614
+ }
2615
+
2616
+ // we don't notify in the included case because this is not reactively
2617
+ // exposed. We should possibly consider doing so though for subscribers
2618
+ }
2619
+ }
2620
+ function areAllModelsUnloaded(wrapper, identifiers) {
2621
+ for (let i = 0; i < identifiers.length; ++i) {
2622
+ const identifier = identifiers[i];
2623
+ if (wrapper.hasRecord(identifier)) {
2624
+ return false;
2625
+ }
2626
+ }
2627
+ return true;
2628
+ }
2629
+ function getLocalState(rel) {
2630
+ if (isBelongsTo(rel)) {
2631
+ return rel.localState ? [rel.localState] : [];
2632
+ }
2633
+ return rel.additions ? [...rel.additions] : [];
2634
+ }
2635
+ function getRemoteState(rel) {
2636
+ if (isBelongsTo(rel)) {
2637
+ return rel.remoteState ? [rel.remoteState] : [];
2638
+ }
2639
+ return rel.remoteState;
2640
+ }
2641
+ function schemaHasLegacyDefaultValueFn(schema) {
2642
+ if (!schema) return false;
2643
+ return hasLegacyDefaultValueFn(schema.options);
2644
+ }
2645
+ function hasLegacyDefaultValueFn(options) {
2646
+ return !!options && typeof options.defaultValue === 'function';
2647
+ }
2648
+ function getDefaultValue(schema, identifier, store) {
2649
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2650
+ if (!test) {
2651
+ throw new Error(`AliasFields should not be directly accessed from the cache`);
2652
+ }
2653
+ })(schema?.kind !== 'alias') : {};
2654
+ const options = schema?.options;
2655
+ if (!schema || !options && !schema.type) {
2656
+ return;
2657
+ }
2658
+ if (schema.kind !== 'attribute' && schema.kind !== 'field') {
2659
+ return;
2660
+ }
2661
+
2662
+ // legacy support for defaultValues that are functions
2663
+ if (hasLegacyDefaultValueFn(options)) {
2664
+ // If anyone opens an issue for args not working right, we'll restore + deprecate it via a Proxy
2665
+ // that lazily instantiates the record. We don't want to provide any args here
2666
+ // because in a non @ember-data-mirror/model world they don't make sense.
2667
+ return options.defaultValue();
2668
+ // legacy support for defaultValues that are primitives
2669
+ } else if (options && 'defaultValue' in options) {
2670
+ const defaultValue = options.defaultValue;
2671
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2672
+ if (!test) {
2673
+ throw new Error(`Non primitive defaultValues are not supported because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.`);
2674
+ }
2675
+ })(typeof defaultValue !== 'object' || defaultValue === null) : {};
2676
+ return defaultValue;
2677
+
2678
+ // new style transforms
2679
+ } else if (schema.kind !== 'attribute' && schema.type) {
2680
+ const transform = store.schema.transformation(schema);
2681
+ if (transform?.defaultValue) {
2682
+ return transform.defaultValue(options || null, identifier);
2683
+ }
2684
+ }
2685
+ }
2686
+ function notifyAttributes(storeWrapper, identifier, keys) {
2687
+ if (!keys) {
2688
+ storeWrapper.notifyChange(identifier, 'attributes', null);
2689
+ return;
2690
+ }
2691
+ for (const key of keys) {
2692
+ storeWrapper.notifyChange(identifier, 'attributes', key);
2693
+ }
2694
+ }
2695
+
2696
+ /*
2697
+ TODO @deprecate IGOR DAVID
2698
+ There seems to be a potential bug here, where we will return keys that are not
2699
+ in the schema
2700
+ */
2701
+ function calculateChangedKeys(cached, updates, fields) {
2702
+ const changedKeys = new Set();
2703
+ const keys = Object.keys(updates);
2704
+ const length = keys.length;
2705
+ const localAttrs = cached.localAttrs;
2706
+ const original = Object.assign(Object.create(null), cached.remoteAttrs, cached.inflightAttrs);
2707
+ for (let i = 0; i < length; i++) {
2708
+ const key = keys[i];
2709
+ if (!fields.has(key)) {
2710
+ continue;
2711
+ }
2712
+ const value = updates[key];
2713
+
2714
+ // A value in localAttrs means the user has a local change to
2715
+ // this attribute. We never override this value when merging
2716
+ // updates from the backend so we should not sent a change
2717
+ // notification if the server value differs from the original.
2718
+ if (localAttrs && localAttrs[key] !== undefined) {
2719
+ continue;
2720
+ }
2721
+ if (original[key] !== value) {
2722
+ changedKeys.add(key);
2723
+ }
2724
+ }
2725
+ return changedKeys;
2726
+ }
2727
+ function cacheIsEmpty(cached) {
2728
+ return !cached || cached.remoteAttrs === null && cached.inflightAttrs === null && cached.localAttrs === null;
2729
+ }
2730
+ function _isEmpty(peeked) {
2731
+ if (!peeked) {
2732
+ return true;
2733
+ }
2734
+ const isNew = peeked.isNew;
2735
+ const isDeleted = peeked.isDeleted;
2736
+ const isEmpty = cacheIsEmpty(peeked);
2737
+ return (!isNew || isDeleted) && isEmpty;
2738
+ }
2739
+ function recordIsLoaded(cached, filterDeleted = false) {
2740
+ if (!cached) {
2741
+ return false;
2742
+ }
2743
+ const isNew = cached.isNew;
2744
+ const isEmpty = cacheIsEmpty(cached);
2745
+
2746
+ // if we are new we must consider ourselves loaded
2747
+ if (isNew) {
2748
+ return !cached.isDeleted;
2749
+ }
2750
+ // even if we have a past request, if we are now empty we are not loaded
2751
+ // typically this is true after an unloadRecord call
2752
+
2753
+ // if we are not empty, not new && we have a fulfilled request then we are loaded
2754
+ // we should consider allowing for something to be loaded that is simply "not empty".
2755
+ // which is how RecordState currently handles this case; however, RecordState is buggy
2756
+ // in that it does not account for unloading.
2757
+ return filterDeleted && cached.isDeletionCommitted ? false : !isEmpty;
2758
+ }
2759
+ function _isLoading(peeked, capabilities, identifier) {
2760
+ // TODO refactor things such that the cache is not required to know
2761
+ // about isLoading
2762
+ const req = capabilities._store.getRequestStateService();
2763
+ // const fulfilled = req.getLastRequestForRecord(identifier);
2764
+ const isLoaded = recordIsLoaded(peeked);
2765
+ return !isLoaded &&
2766
+ // fulfilled === null &&
2767
+ req.getPendingRequestsForRecord(identifier).some(r => r.type === 'query');
2768
+ }
2769
+ function setupRelationships(graph, fields, identifier, data) {
2770
+ for (const name in data.relationships) {
2771
+ const relationshipData = data.relationships[name];
2772
+ const field = fields.get(name);
2773
+ // TODO consider asserting if the relationship is not in the schema
2774
+ // we intentionally ignore relationships that are not in the schema
2775
+ if (!relationshipData || !field || !isRelationship(field)) continue;
2776
+ graph.push({
2777
+ op: 'updateRelationship',
2778
+ record: identifier,
2779
+ field: name,
2780
+ value: relationshipData
2781
+ });
2782
+ }
2783
+ }
2784
+ function isRelationship(field) {
2785
+ const {
2786
+ kind
2787
+ } = field;
2788
+ return kind === 'hasMany' || kind === 'belongsTo' || kind === 'resource' || kind === 'collection';
2789
+ }
2790
+ function patchLocalAttributes(cached, changedRemoteKeys) {
2791
+ const {
2792
+ localAttrs,
2793
+ remoteAttrs,
2794
+ inflightAttrs,
2795
+ defaultAttrs,
2796
+ changes
2797
+ } = cached;
2798
+ if (!localAttrs) {
2799
+ cached.changes = null;
2800
+ return false;
2801
+ }
2802
+ let hasAppliedPatch = false;
2803
+ const mutatedKeys = Object.keys(localAttrs);
2804
+ for (let i = 0, length = mutatedKeys.length; i < length; i++) {
2805
+ const attr = mutatedKeys[i];
2806
+ const existing = inflightAttrs && attr in inflightAttrs ? inflightAttrs[attr] : remoteAttrs && attr in remoteAttrs ? remoteAttrs[attr] : undefined;
2807
+ if (existing === localAttrs[attr]) {
2808
+ hasAppliedPatch = true;
2809
+
2810
+ // if the local change is committed, then
2811
+ // the remoteKeyChange is no longer relevant
2812
+ changedRemoteKeys?.delete(attr);
2813
+ delete localAttrs[attr];
2814
+ delete changes[attr];
2815
+ }
2816
+ if (defaultAttrs && attr in defaultAttrs) {
2817
+ delete defaultAttrs[attr];
2818
+ }
2819
+ }
2820
+ return hasAppliedPatch;
2821
+ }
2822
+ function putOne(cache, identifiers, resource) {
2823
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2824
+ if (!test) {
2825
+ throw new Error(`You must include an 'id' for the resource data ${resource.type}`);
2826
+ }
2827
+ })(resource.id !== null && resource.id !== undefined && resource.id !== '') : {};
2828
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
2829
+ if (!test) {
2830
+ throw new Error(`Missing Resource Type: received resource data with a type '${resource.type}' but no schema could be found with that name.`);
2831
+ }
2832
+ })(cache._capabilities.schema.hasResource(resource)) : {};
2833
+ let identifier = identifiers.peekRecordIdentifier(resource);
2834
+ if (identifier) {
2835
+ identifier = identifiers.updateRecordIdentifier(identifier, resource);
2836
+ } else {
2837
+ identifier = identifiers.getOrCreateRecordIdentifier(resource);
2838
+ }
2839
+ cache.upsert(identifier, resource, cache._capabilities.hasRecord(identifier));
2840
+ // even if the identifier was not "existing" before, it is now
2841
+ return identifier;
2842
+ }
2843
+
2844
+ /*
2845
+ Iterates over the set of internal models reachable from `this` across exactly one
2846
+ relationship.
2847
+ */
2848
+ function _directlyRelatedIdentifiersIterable(storeWrapper, originating) {
2849
+ const graph = peekGraph(storeWrapper);
2850
+ const initializedRelationships = graph?.identifiers.get(originating);
2851
+ if (!initializedRelationships) {
2852
+ return EMPTY_ITERATOR;
2853
+ }
2854
+ const initializedRelationshipsArr = [];
2855
+ Object.keys(initializedRelationships).forEach(key => {
2856
+ const rel = initializedRelationships[key];
2857
+ if (rel && !isImplicit(rel)) {
2858
+ initializedRelationshipsArr.push(rel);
2859
+ }
2860
+ });
2861
+ let i = 0;
2862
+ let j = 0;
2863
+ let k = 0;
2864
+ const findNext = () => {
2865
+ while (i < initializedRelationshipsArr.length) {
2866
+ while (j < 2) {
2867
+ const relatedIdentifiers = j === 0 ? getLocalState(initializedRelationshipsArr[i]) : getRemoteState(initializedRelationshipsArr[i]);
2868
+ while (k < relatedIdentifiers.length) {
2869
+ const relatedIdentifier = relatedIdentifiers[k++];
2870
+ if (relatedIdentifier !== null) {
2871
+ return relatedIdentifier;
2872
+ }
2873
+ }
2874
+ k = 0;
2875
+ j++;
2876
+ }
2877
+ j = 0;
2878
+ i++;
2879
+ }
2880
+ return undefined;
2881
+ };
2882
+ return {
2883
+ iterator() {
2884
+ return {
2885
+ next: () => {
2886
+ const value = findNext();
2887
+ return {
2888
+ value,
2889
+ done: value === undefined
2890
+ };
2891
+ }
2892
+ };
2893
+ }
2894
+ };
2895
+ }
2896
+
2897
+ /*
2898
+ Computes the set of Identifiers reachable from this Identifier.
2899
+
2900
+ Reachability is determined over the relationship graph (ie a graph where
2901
+ nodes are identifiers and edges are belongs to or has many
2902
+ relationships).
2903
+
2904
+ Returns an array including `this` and all identifiers reachable
2905
+ from `this.identifier`.
2906
+ */
2907
+ function _allRelatedIdentifiers(storeWrapper, originating) {
2908
+ const array = [];
2909
+ const queue = [];
2910
+ const seen = new Set();
2911
+ queue.push(originating);
2912
+ while (queue.length > 0) {
2913
+ const identifier = queue.shift();
2914
+ array.push(identifier);
2915
+ seen.add(identifier);
2916
+ const iterator = _directlyRelatedIdentifiersIterable(storeWrapper, originating).iterator();
2917
+ for (let obj = iterator.next(); !obj.done; obj = iterator.next()) {
2918
+ const relatedIdentifier = obj.value;
2919
+ if (relatedIdentifier && !seen.has(relatedIdentifier)) {
2920
+ seen.add(relatedIdentifier);
2921
+ queue.push(relatedIdentifier);
2922
+ }
2923
+ }
2924
+ }
2925
+ return array;
2926
+ }
2927
+ function fromBaseDocument(doc) {
2928
+ const resourceDocument = {};
2929
+ const jsonApiDoc = doc.content;
2930
+ if (jsonApiDoc) {
2931
+ copyLinksAndMeta(resourceDocument, jsonApiDoc);
2932
+ }
2933
+ return resourceDocument;
2934
+ }
2935
+ function fromStructuredError(doc) {
2936
+ const errorDoc = {};
2937
+ if (doc.content) {
2938
+ copyLinksAndMeta(errorDoc, doc.content);
2939
+ if ('errors' in doc.content) {
2940
+ errorDoc.errors = doc.content.errors;
2941
+ } else if (typeof doc.error === 'object' && 'errors' in doc.error) {
2942
+ errorDoc.errors = doc.error.errors;
2943
+ } else {
2944
+ errorDoc.errors = [{
2945
+ title: doc.message
2946
+ }];
2947
+ }
2948
+ }
2949
+ return errorDoc;
2950
+ }
2951
+ function copyLinksAndMeta(target, source) {
2952
+ if ('links' in source) {
2953
+ target.links = source.links;
2954
+ }
2955
+ if ('meta' in source) {
2956
+ target.meta = source.meta;
2957
+ }
2958
+ }
2959
+ function cacheUpsert(cache, identifier, data, calculateChanges) {
2960
+ let changedKeys;
2961
+ const peeked = cache.__safePeek(identifier, false);
2962
+ const existed = !!peeked;
2963
+ const cached = peeked || cache._createCache(identifier);
2964
+ const isLoading = /*#__NOINLINE__*/_isLoading(peeked, cache._capabilities, identifier) || !recordIsLoaded(peeked);
2965
+ const isUpdate = /*#__NOINLINE__*/!_isEmpty(peeked) && !isLoading;
2966
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
2967
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
2968
+ logGroup('cache', 'upsert', identifier.type, identifier.lid, existed ? 'merged' : 'inserted', calculateChanges ? 'has-subscription' : '');
2969
+ try {
2970
+ const _data = JSON.parse(JSON.stringify(data));
2971
+
2972
+ // eslint-disable-next-line no-console
2973
+ console.log(_data);
2974
+ } catch {
2975
+ // eslint-disable-next-line no-console
2976
+ console.log(data);
2977
+ }
2978
+ }
2979
+ }
2980
+ if (cached.isNew) {
2981
+ cached.isNew = false;
2982
+ cache._capabilities.notifyChange(identifier, 'identity', null);
2983
+ cache._capabilities.notifyChange(identifier, 'state', null);
2984
+ }
2985
+ const fields = cache._capabilities.schema.fields(identifier);
2986
+
2987
+ // if no cache entry existed, no record exists / property has been accessed
2988
+ // and thus we do not need to notify changes to any properties.
2989
+ if (calculateChanges && existed && data.attributes) {
2990
+ changedKeys = calculateChangedKeys(cached, data.attributes, fields);
2991
+ }
2992
+ cached.remoteAttrs = Object.assign(cached.remoteAttrs || Object.create(null), data.attributes);
2993
+ if (cached.localAttrs) {
2994
+ if (patchLocalAttributes(cached, changedKeys)) {
2995
+ cache._capabilities.notifyChange(identifier, 'state', null);
2996
+ }
2997
+ }
2998
+ if (!isUpdate) {
2999
+ cache._capabilities.notifyChange(identifier, 'added', null);
3000
+ }
3001
+ if (data.id) {
3002
+ cached.id = data.id;
3003
+ }
3004
+ if (data.relationships) {
3005
+ setupRelationships(cache.__graph, fields, identifier, data);
3006
+ }
3007
+ if (changedKeys?.size) {
3008
+ notifyAttributes(cache._capabilities, identifier, changedKeys);
3009
+ }
3010
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
3011
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3012
+ // eslint-disable-next-line no-console
3013
+ console.groupEnd();
3014
+ }
3015
+ }
3016
+ return changedKeys?.size ? Array.from(changedKeys) : undefined;
3017
+ }
3018
+ function patchCache(Cache, op) {
3019
+ const isRecord = isStableIdentifier(op.record);
3020
+ const isDocument = !isRecord && isDocumentIdentifier(op.record);
3021
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3022
+ if (!test) {
3023
+ throw new Error(`Expected Cache.patch op.record to be a record or document identifier`);
3024
+ }
3025
+ })(isRecord || isDocument) : {};
3026
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
3027
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3028
+ logGroup('cache', 'patch', isRecord ? op.record.type : '<@document>', op.record.lid, op.op, 'field' in op ? op.field : op.op === 'mergeIdentifiers' ? op.value.lid : '');
3029
+ try {
3030
+ const _data = JSON.parse(JSON.stringify(op));
3031
+ // eslint-disable-next-line no-console
3032
+ console.log(_data);
3033
+ } catch {
3034
+ // eslint-disable-next-line no-console
3035
+ console.log(op);
3036
+ }
3037
+ }
3038
+ }
3039
+ switch (op.op) {
3040
+ case 'mergeIdentifiers':
3041
+ {
3042
+ const cache = Cache.__cache.get(op.record);
3043
+ if (cache) {
3044
+ Cache.__cache.set(op.value, cache);
3045
+ Cache.__cache.delete(op.record);
3046
+ }
3047
+ Cache.__graph.update(op, true);
3048
+ break;
3049
+ }
3050
+ case 'update':
3051
+ {
3052
+ if (isRecord) {
3053
+ if ('field' in op) {
3054
+ const field = Cache._capabilities.schema.fields(op.record).get(op.field);
3055
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3056
+ if (!test) {
3057
+ throw new Error(`Expected ${op.field} to be a field on ${op.record.type}`);
3058
+ }
3059
+ })(field) : {};
3060
+ if (isRelationship(field)) {
3061
+ Cache.__graph.push(op);
3062
+ } else {
3063
+ Cache.upsert(op.record, {
3064
+ type: op.record.type,
3065
+ id: op.record.id,
3066
+ attributes: {
3067
+ [op.field]: op.value
3068
+ }
3069
+ }, Cache._capabilities.hasRecord(op.record));
3070
+ }
3071
+ } else {
3072
+ Cache.upsert(op.record, op.value, Cache._capabilities.hasRecord(op.record));
3073
+ }
3074
+ } else {
3075
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3076
+ {
3077
+ throw new Error(`Update operations on documents is not supported`);
3078
+ }
3079
+ })() : {};
3080
+ }
3081
+ break;
3082
+ }
3083
+ case 'add':
3084
+ {
3085
+ if (isRecord) {
3086
+ if ('field' in op) {
3087
+ Cache.__graph.push(op);
3088
+ } else {
3089
+ Cache.upsert(op.record, op.value, Cache._capabilities.hasRecord(op.record));
3090
+ }
3091
+ } else {
3092
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3093
+ if (!test) {
3094
+ throw new Error(`Expected a field in the add operation`);
3095
+ }
3096
+ })('field' in op) : {};
3097
+ addResourceToDocument(Cache, op);
3098
+ }
3099
+ break;
3100
+ }
3101
+ case 'remove':
3102
+ {
3103
+ if (isRecord) {
3104
+ if ('field' in op) {
3105
+ Cache.__graph.push(op);
3106
+ } else {
3107
+ const cached = Cache.__safePeek(op.record, false);
3108
+ if (cached) {
3109
+ cached.isDeleted = true;
3110
+ cached.isDeletionCommitted = true;
3111
+ Cache.unloadRecord(op.record);
3112
+ } else {
3113
+ peekGraph(Cache._capabilities)?.push({
3114
+ op: 'deleteRecord',
3115
+ record: op.record,
3116
+ isNew: false
3117
+ });
3118
+ }
3119
+ }
3120
+ } else {
3121
+ if ('field' in op) {
3122
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3123
+ if (!test) {
3124
+ throw new Error(`Expected a field in the remove operation`);
3125
+ }
3126
+ })('field' in op) : {};
3127
+ removeResourceFromDocument(Cache, op);
3128
+ } else {
3129
+ // TODO @runspired teardown associated state ... notify subscribers etc.
3130
+ // This likely means that the instance cache needs to handle
3131
+ // holding onto reactive documents instead of the CacheHandler
3132
+ // and use a subscription to remove them.
3133
+ // Cache.__documents.delete(op.record.lid);
3134
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3135
+ {
3136
+ throw new Error(`Removing documents from the cache is not yet supported`);
3137
+ }
3138
+ })() : {};
3139
+ }
3140
+ }
3141
+ break;
3142
+ }
3143
+ default:
3144
+ macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
3145
+ {
3146
+ throw new Error(`Unhandled cache.patch operation ${op.op}`);
3147
+ }
3148
+ })() : {};
3149
+ }
3150
+ if (macroCondition(getGlobalConfig().WarpDriveMirror.activeLogging.LOG_CACHE)) {
3151
+ if (getGlobalConfig().WarpDriveMirror.debug.LOG_CACHE || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE) {
3152
+ // eslint-disable-next-line no-console
3153
+ console.groupEnd();
3154
+ }
3155
+ }
3156
+ }
3157
+ export { JSONAPICache };