@warp-drive/core 5.7.0-alpha.11 → 5.7.0-alpha.12

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.
package/dist/reactive.js CHANGED
@@ -1,1921 +1,15 @@
1
1
  import { isResourceSchema } from './types/schema/fields.js';
2
- import { F as withSignalStore, T as isExtensionProp, U as performExtensionSet, H as consumeInternalSignal, V as performArrayExtensionGet, x as entangleSignal, E as peekInternalSignal, d as SOURCE$1, f as fastPush, l as RelatedCollection, J as getOrCreateInternalSignal, G as notifyInternalSignal, W as performObjectExtensionGet, y as defineSignal, B as Signals, h as setRecordIdentifier, r as recordIdentifierFor } from "./request-state-CeN66aML.js";
3
- import { EnableHydration, STRUCTURED } from './types/request.js';
2
+ import { H as ReactiveResource, J as isNonIdentityCacheableField, K as getFieldCacheKeyStrict, r as recordIdentifierFor, B as withSignalStore } from "./request-state-BWYju5O9.js";
3
+ import { D as Destroy, C as Context } from "./symbols-BoONANuz.js";
4
+ export { a as Checkout } from "./symbols-BoONANuz.js";
4
5
  import { macroCondition, getGlobalConfig } from '@embroider/macros';
5
6
  import { warn, deprecate } from '@ember/debug';
7
+ import './index.js';
8
+ import './types/request.js';
6
9
  import './utils/string.js';
7
- import { A as ARRAY_SIGNAL, O as OBJECT_SIGNAL, c as createMemo } from "./configure-B48bFHOl.js";
8
- import { RecordStore, Type } from './types/symbols.js';
9
- import { S as SOURCE, C as Context, D as Destroy, a as Checkout } from "./symbols-BoONANuz.js";
10
+ import { c as createMemo } from "./configure-B48bFHOl.js";
10
11
  import { getOrSetGlobal } from './types/-private.js';
11
- import './index.js';
12
- function getAliasField(context) {
13
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
14
- {
15
- throw new Error(`Alias field access is not implemented`);
16
- }
17
- })() : {};
18
- }
19
- function setAliasField(context) {
20
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
21
- {
22
- throw new Error(`Alias field setting is not implemented`);
23
- }
24
- })() : {};
25
- return false;
26
- }
27
- const ARRAY_GETTER_METHODS = new Set([Symbol.iterator, 'concat', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'flat', 'flatMap', 'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'reduce', 'reduceRight', 'slice', 'some', 'values']);
28
- // const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
29
- const SYNC_PROPS = new Set(['[]', 'length']);
30
- function isArrayGetter(prop) {
31
- return ARRAY_GETTER_METHODS.has(prop);
32
- }
33
- const ARRAY_SETTER_METHODS = new Set(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
34
- function isArraySetter(prop) {
35
- return ARRAY_SETTER_METHODS.has(prop);
36
- }
37
-
38
- // function isSelfProp<T extends object>(self: T, prop: KeyType): prop is keyof T {
39
- // return prop in self;
40
- // }
41
-
42
- function convertToInt(prop) {
43
- if (typeof prop === 'symbol') return null;
44
- const num = Number(prop);
45
- if (isNaN(num)) return null;
46
- return num % 1 === 0 ? num : null;
47
- }
48
- function safeForEach(instance, arr, store, callback, target) {
49
- if (target === undefined) {
50
- target = null;
51
- }
52
- // clone to prevent mutation
53
- arr = arr.slice();
54
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
55
- if (!test) {
56
- throw new Error('`forEach` expects a function as first argument.');
57
- }
58
- })(typeof callback === 'function') : {};
59
-
60
- // because we retrieveLatest above we need not worry if array is mutated during iteration
61
- // by unloadRecord/rollbackAttributes
62
- // push/add/removeObject may still be problematic
63
- // but this is a more traditionally expected forEach bug.
64
- const length = arr.length; // we need to access length to ensure we are consumed
65
-
66
- for (let index = 0; index < length; index++) {
67
- callback.call(target, arr[index], index, instance);
68
- }
69
- return instance;
70
- }
71
- // eslint-disable-next-line @typescript-eslint/no-extraneous-class
72
- class ManagedArray {
73
- constructor(context, owner, data) {
74
- // eslint-disable-next-line @typescript-eslint/no-this-alias
75
- const self = this;
76
- this[SOURCE] = data?.slice();
77
- const IS_EDITABLE = context.editable ?? false;
78
- this[Context] = context;
79
- const schema = context.store.schema;
80
- const cache = context.store.cache;
81
- const {
82
- field
83
- } = context;
84
- const signals = withSignalStore(this);
85
- let _SIGNAL = null;
86
- const boundFns = new Map();
87
- this.identifier = context.resourceKey;
88
- this.path = context.path;
89
- this.owner = owner;
90
- let transaction = false;
91
- const KeyMode = field.options?.key ?? '@identity';
92
- // listener.
93
- const RefStorage = KeyMode === '@identity' ? WeakMap :
94
- // CAUTION CAUTION CAUTION
95
- // this is a pile of lies
96
- // the Map is Map<string, WeakRef<ReactiveResource>>
97
- // but TS does not understand how to juggle modes like this
98
- // internal to a method like ours without us duplicating the code
99
- // into two separate methods.
100
- Map;
101
- const ManagedRecordRefs = field.kind === 'schema-array' ? new RefStorage() : null;
102
- const extensions = context.legacy ? schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions(field) : null;
103
- const proxy = new Proxy(this[SOURCE], {
104
- get(target, prop, receiver) {
105
- if (prop === ARRAY_SIGNAL) {
106
- return _SIGNAL;
107
- }
108
- if (prop === 'identifier') {
109
- return self.identifier;
110
- }
111
- if (prop === 'owner') {
112
- return self.owner;
113
- }
114
- const index = convertToInt(prop);
115
- if (_SIGNAL.isStale && (index !== null || SYNC_PROPS.has(prop) || isArrayGetter(prop))) {
116
- _SIGNAL.isStale = false;
117
- const newData = cache.getAttr(context.resourceKey, context.path);
118
- if (newData && newData !== self[SOURCE]) {
119
- self[SOURCE].length = 0;
120
- self[SOURCE].push(...newData);
121
- }
122
- }
123
- if (prop === 'length') {
124
- return consumeInternalSignal(_SIGNAL), target.length;
125
- }
126
- if (prop === '[]') return consumeInternalSignal(_SIGNAL), receiver;
127
- if (index !== null) {
128
- if (!transaction) {
129
- consumeInternalSignal(_SIGNAL);
130
- }
131
- const rawValue = target[index];
132
- if (field.kind === 'array') {
133
- if (field.type) {
134
- const transform = schema.transformation(field);
135
- return transform.hydrate(rawValue, field.options ?? null, self.owner);
136
- }
137
- return rawValue;
138
- }
139
-
140
- /**
141
- * When the array is polymorphic, we need to determine the real type
142
- * in order to apply the correct identity as schema-object identity
143
- * is only required to be unique by type
144
- */
145
- let objectType;
146
- if (field.options?.polymorphic) {
147
- const typePath = field.options.type ?? 'type';
148
- // if we are polymorphic, then context.field.options.type will
149
- // either specify a path on the rawValue to use as the type, defaulting to "type" or
150
- // the special string "@hash" which tells us to treat field.type as a hashFn name with which
151
- // to calc the type.
152
- if (typePath === '@hash') {
153
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
154
- if (!test) {
155
- throw new Error(`Expected the field to define a hashFn as its type`);
156
- }
157
- })(field.type) : {};
158
- const hashFn = schema.hashFn({
159
- type: field.type
160
- });
161
- // TODO consider if there are better options and name args we could provide.
162
- objectType = hashFn(rawValue, null, null);
163
- } else {
164
- objectType = rawValue[typePath];
165
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
166
- if (!test) {
167
- throw new Error(`Expected the type path for the field to be a value on the raw object`);
168
- }
169
- })(typePath && objectType && typeof objectType === 'string') : {};
170
- }
171
- } else {
172
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
173
- if (!test) {
174
- throw new Error(`A non-polymorphic SchemaArrayField must provide a SchemaObject type in its definition`);
175
- }
176
- })(field.type) : {};
177
- objectType = field.type;
178
- }
179
-
180
- /**
181
- * When KeyMode=@hash the ReactiveResource is keyed into
182
- * ManagedRecordRefs by the return value of @hash on the rawValue.
183
- *
184
- * This means that we could find a way to only recompute the identity
185
- * when ARRAY_SIGNAL is dirty if hash performance becomes a bottleneck.
186
- */
187
- let schemaObjectKeyValue;
188
- if (KeyMode === '@hash') {
189
- const hashField = schema.resource({
190
- type: objectType
191
- }).identity;
192
- const hashFn = schema.hashFn(hashField);
193
- schemaObjectKeyValue = hashFn(rawValue, hashField.options ?? null, hashField.name);
194
- } else {
195
- // if mode is not @identity or @index, then access the key path.
196
- // we should assert that `mode` is a string
197
- // it should read directly from the cache value for that field (e.g. no derivation, no transformation)
198
- // and, we likely should lookup the associated field and throw an error IF
199
- // the given field does not exist OR
200
- // the field is anything other than a GenericField or LegacyAttributeField.
201
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
202
- const isPathKeyMode = KeyMode !== '@identity' && KeyMode !== '@index';
203
- if (isPathKeyMode) {
204
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
205
- if (!test) {
206
- throw new Error('mode must be a string');
207
- }
208
- })(typeof KeyMode === 'string' && KeyMode !== '') : {};
209
- const modeField = schema.fields({
210
- type: objectType
211
- }).get(KeyMode);
212
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
213
- if (!test) {
214
- throw new Error('field must exist in schema');
215
- }
216
- })(modeField) : {};
217
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
218
- if (!test) {
219
- throw new Error('field must be a GenericField or LegacyAttributeField');
220
- }
221
- })(modeField.kind === 'field' || modeField.kind === 'attribute') : {};
222
- }
223
- }
224
- schemaObjectKeyValue = KeyMode === '@identity' ? rawValue : KeyMode === '@index' ? index : rawValue[KeyMode];
225
- }
226
- if (!schemaObjectKeyValue) {
227
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
228
- {
229
- throw new Error(`Unexpected out of bounds access on SchemaArray`);
230
- }
231
- })() : {};
232
- return undefined;
233
- }
234
- const recordRef = ManagedRecordRefs.get(schemaObjectKeyValue);
235
- const record = recordRef?.value.deref();
236
-
237
- // confirm the type and key still match
238
- if (record && recordRef.type === objectType && recordRef.identity === schemaObjectKeyValue) {
239
- if (recordRef.index !== index) {
240
- recordRef.index = index;
241
- recordRef.context.path[recordRef.context.path.length - 1] = index;
242
- }
243
- return record;
244
- } else if (record) {
245
- // TODO schedule idle once we can
246
- void Promise.resolve().then(() => {
247
- record[Destroy]();
248
- });
249
- }
250
- const recordPath = context.path.slice();
251
- // this is a dirty lie since path is string[] but really we
252
- // should change the types for paths to `Array<string | number>`
253
- recordPath.push(index);
254
- const objectContext = {
255
- store: context.store,
256
- resourceKey: context.resourceKey,
257
- modeName: context.modeName,
258
- legacy: context.legacy,
259
- editable: context.editable,
260
- path: recordPath,
261
- field: field,
262
- value: objectType
263
- };
264
- const schemaObject = new ReactiveResource(objectContext);
265
- ManagedRecordRefs.set(schemaObjectKeyValue, {
266
- type: objectType,
267
- identity: schemaObjectKeyValue,
268
- index,
269
- context: objectContext,
270
- value: new WeakRef(schemaObject)
271
- });
272
- return schemaObject;
273
- }
274
- if (isArrayGetter(prop)) {
275
- let fn = boundFns.get(prop);
276
- if (fn === undefined) {
277
- if (prop === 'forEach') {
278
- fn = function () {
279
- consumeInternalSignal(_SIGNAL);
280
- transaction = true;
281
- const result = safeForEach(receiver, target, context.store, arguments[0], arguments[1]);
282
- transaction = false;
283
- return result;
284
- };
285
- } else {
286
- fn = function () {
287
- consumeInternalSignal(_SIGNAL);
288
- // array functions must run through Reflect to work properly
289
- // binding via other means will not work.
290
- transaction = true;
291
- const result = Reflect.apply(target[prop], receiver, arguments);
292
- transaction = false;
293
- return result;
294
- };
295
- }
296
- boundFns.set(prop, fn);
297
- }
298
- return fn;
299
- }
300
- if (isArraySetter(prop)) {
301
- let fn = boundFns.get(prop);
302
- if (fn === undefined) {
303
- fn = function () {
304
- if (!IS_EDITABLE) {
305
- throw new Error(`Mutating this array via ${String(prop)} is not allowed because the record is not editable`);
306
- }
307
- consumeInternalSignal(_SIGNAL);
308
- transaction = true;
309
- const result = Reflect.apply(target[prop], receiver, arguments);
310
- transaction = false;
311
- return result;
312
- };
313
- boundFns.set(prop, fn);
314
- }
315
- return fn;
316
- }
317
- if (isExtensionProp(extensions, prop)) {
318
- return performArrayExtensionGet(receiver, extensions, signals, prop, _SIGNAL, boundFns, v => void (transaction = v));
319
- }
320
- return Reflect.get(target, prop, receiver);
321
- },
322
- set(target, prop, value, receiver) {
323
- if (!IS_EDITABLE) {
324
- let errorPath = context.resourceKey.type;
325
- if (context.path) {
326
- errorPath = context.path[context.path.length - 1];
327
- }
328
- throw new Error(`Cannot set ${String(prop)} on ${errorPath} because the record is not editable`);
329
- }
330
- if (prop === 'identifier') {
331
- self.identifier = value;
332
- return true;
333
- }
334
- if (prop === 'owner') {
335
- self.owner = value;
336
- return true;
337
- }
338
- if (isExtensionProp(extensions, prop)) {
339
- return performExtensionSet(receiver, extensions, signals, prop, value);
340
- }
341
- const reflect = Reflect.set(target, prop, value, receiver);
342
- if (reflect) {
343
- if (!field.type) {
344
- cache.setAttr(context.resourceKey, context.path, self[SOURCE]);
345
- _SIGNAL.isStale = true;
346
- return true;
347
- }
348
- let rawValue = self[SOURCE];
349
- if (field.kind !== 'schema-array') {
350
- const transform = schema.transformation(field);
351
- if (!transform) {
352
- throw new Error(`No '${field.type}' transform defined for use by ${context.resourceKey.type}.${String(prop)}`);
353
- }
354
- rawValue = self[SOURCE].map(item => transform.serialize(item, field.options ?? null, self.owner));
355
- }
356
- cache.setAttr(context.resourceKey, context.path, rawValue);
357
- _SIGNAL.isStale = true;
358
- }
359
- return reflect;
360
- },
361
- has(target, prop) {
362
- if (prop === 'identifier' || prop === 'owner' || prop === ARRAY_SIGNAL) {
363
- return true;
364
- }
365
- return Reflect.has(target, prop);
366
- }
367
- });
368
-
369
- // we entangle the signal on the returned proxy since that is
370
- // the object that other code will be interfacing with.
371
- _SIGNAL = entangleSignal(signals, proxy, ARRAY_SIGNAL, undefined);
372
- return proxy;
373
- }
374
- }
375
-
376
- // this will error if someone tries to call
377
- // A(identifierArray) since it is not configurable
378
- // which is preferable to the `meta` override we used
379
- // before which required importing all of Ember
380
- const desc = {
381
- enumerable: true,
382
- configurable: false,
383
- get: function () {
384
- // here to support computed chains
385
- // and {{#each}}
386
- if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_COMPUTED_CHAINS)) {
387
- return this;
388
- }
389
- }
390
- };
391
- // compat(desc);
392
- Object.defineProperty(ManagedArray.prototype, '[]', desc);
393
- function getArrayField(context) {
394
- const signal = entangleSignal(context.signals, context.record, context.path.at(-1), null);
395
- // the thing we hand out needs to know its owner and path in a private manner
396
- // its "address" is the parent identifier (identifier) + field name (field.name)
397
- // in the nested object case field name here is the full dot path from root resource to this value
398
- // its "key" is the field on the parent record
399
- // its "owner" is the parent record
400
- const {
401
- record
402
- } = context;
403
- let managedArray = signal.value;
404
- if (managedArray) {
405
- return managedArray;
406
- } else {
407
- const {
408
- store,
409
- resourceKey,
410
- path,
411
- field
412
- } = context;
413
- const {
414
- cache
415
- } = store;
416
- let rawValue = context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path);
417
- if (!rawValue && field.kind === 'schema-array' && field.options?.defaultValue) {
418
- rawValue = [];
419
- }
420
- if (!rawValue) {
421
- return null;
422
- }
423
- managedArray = new ManagedArray(context, record, rawValue);
424
- signal.value = managedArray;
425
- }
426
- return managedArray;
427
- }
428
- function setArrayField(context) {
429
- const {
430
- field,
431
- record,
432
- value
433
- } = context;
434
- const {
435
- cache,
436
- schema
437
- } = context.store;
438
- const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1));
439
- const peeked = fieldSignal?.value;
440
- const transform = field.type ? schema.transformation(field) : null;
441
- const rawValue = field.type ? value.map(item => transform.serialize(item, field.options ?? null, record)) : value?.slice();
442
- cache.setAttr(context.resourceKey, context.path, rawValue);
443
- if (peeked) {
444
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
445
- if (!test) {
446
- throw new Error(`Expected the peekManagedArray for ${field.kind} to return a ManagedArray`);
447
- }
448
- })(ARRAY_SIGNAL in peeked) : {};
449
- const arrSignal = peeked[ARRAY_SIGNAL];
450
- arrSignal.isStale = true;
451
- // TODO run array destroy?
452
- }
453
- if (!Array.isArray(rawValue) && fieldSignal) {
454
- fieldSignal.value = null;
455
- }
456
- return true;
457
- }
458
- function getAttributeField(context) {
459
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
460
- const {
461
- cache
462
- } = context.store;
463
- return context.editable ? cache.getAttr(context.resourceKey, context.path) : cache.getRemoteAttr(context.resourceKey, context.path);
464
- }
465
- function setAttributeField(context) {
466
- context.store.cache.setAttr(context.resourceKey, context.path, context.value);
467
- return true;
468
- }
469
- const InvalidKinds = ['alias', 'derived', '@local'];
470
- function isInvalidKind(kind) {
471
- return InvalidKinds.includes(kind);
472
- }
473
- function isNonIdentityCacheableField(field) {
474
- return !isInvalidKind(field.kind) && field.kind !== '@id' && field.kind !== '@hash';
475
- }
476
- function getFieldCacheKeyStrict(field) {
477
- return field.sourceKey || field.name;
478
- }
479
- function getFieldCacheKey(field) {
480
- return 'sourceKey' in field && field.sourceKey ? field.sourceKey : field.name;
481
- }
482
- function getBelongsToField(context) {
483
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
484
- const {
485
- field,
486
- resourceKey,
487
- store
488
- } = context;
489
- const {
490
- schema,
491
- cache
492
- } = store;
493
- if (field.options.linksMode) {
494
- const rawValue = context.editable ? cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field)) : cache.getRemoteRelationship(resourceKey, getFieldCacheKeyStrict(field));
495
- return rawValue.data ? store.peekRecord(rawValue.data) : null;
496
- }
497
-
498
- // FIXME move this to a "LegacyMode" make this part of "PolarisMode"
499
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
500
- if (!test) {
501
- throw new Error(`Can only use belongsTo fields when the resource is in legacy mode`);
502
- }
503
- })(context.legacy) : {};
504
- return schema._kind('@legacy', 'belongsTo').get(store, context.record, resourceKey, field);
505
- }
506
- function setBelongsToField(context) {
507
- const {
508
- store
509
- } = context;
510
- const {
511
- schema
512
- } = store;
513
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
514
- if (!test) {
515
- throw new Error(`Can only mutate belongsTo fields when the resource is in legacy mode`);
516
- }
517
- })(context.legacy) : {};
518
- schema._kind('@legacy', 'belongsTo').set(store, context.record, context.resourceKey, context.field, context.value);
519
- return true;
520
- }
521
- function getCollectionField(context) {
522
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
523
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
524
- {
525
- throw new Error(`Accessing collection fields is not yet implemented`);
526
- }
527
- })() : {};
528
- }
529
- function setCollectionField(context) {
530
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
531
- {
532
- throw new Error(`Setting collection fields is not yet implemented`);
533
- }
534
- })() : {};
535
- return false;
536
- }
537
- function getDerivedField(context) {
538
- const {
539
- schema
540
- } = context.store;
541
- return schema.derivation(context.field)(context.record, context.field.options ?? null, context.field.name);
542
- }
543
- function setDerivedField(context) {
544
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
545
- {
546
- throw new Error(`ILLEGAL SET: Cannot set '${context.path.join('.')}' on '${context.resourceKey.type}' as ${context.field.kind} fields are not mutable`);
547
- }
548
- })() : {};
549
- return false;
550
- }
551
- function getGenericField(context) {
552
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
553
- const {
554
- cache,
555
- schema
556
- } = context.store;
557
- const rawValue = context.editable ? cache.getAttr(context.resourceKey, context.path) : cache.getRemoteAttr(context.resourceKey, context.path);
558
- const {
559
- field
560
- } = context;
561
- if (!field.type) {
562
- return rawValue;
563
- }
564
- const transform = schema.transformation(field);
565
- return transform.hydrate(rawValue, field.options ?? null, context.record);
566
- }
567
- function setGenericField(context) {
568
- const {
569
- cache,
570
- schema
571
- } = context.store;
572
- const {
573
- field
574
- } = context;
575
- if (!field.type) {
576
- cache.setAttr(context.resourceKey, context.path, context.value);
577
- return true;
578
- }
579
- const transform = schema.transformation(field);
580
- const rawValue = transform.serialize(context.value, field.options ?? null, context.record);
581
- cache.setAttr(context.resourceKey, context.path, rawValue);
582
- return true;
583
- }
584
- class ManyArrayManager {
585
- constructor(record, editable) {
586
- const context = record[Context];
587
- this.record = record;
588
- this.store = context.store;
589
- this.identifier = context.resourceKey;
590
- this.editable = editable;
591
- }
592
- _syncArray(array) {
593
- const method = this.editable ? 'getRelationship' : 'getRemoteRelationship';
594
- // FIXME field needs to use sourceKey
595
- const rawValue = this.store.cache[method](this.identifier, array.key);
596
- if (rawValue.meta) {
597
- array.meta = rawValue.meta;
598
- }
599
- if (rawValue.links) {
600
- array.links = rawValue.links;
601
- }
602
- const currentState = array[SOURCE$1];
603
-
604
- // unlike in the normal RecordArray case, we don't need to divorce the reference
605
- // because we don't need to worry about associate/disassociate since the graph
606
- // takes care of that for us
607
- if (currentState !== rawValue.data) {
608
- currentState.length = 0;
609
- fastPush(currentState, rawValue.data);
610
- }
611
- }
612
- reloadHasMany(key, options) {
613
- // FIXME field needs to use sourceKey
614
- const field = this.store.schema.fields(this.identifier).get(key);
615
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
616
- if (!test) {
617
- throw new Error(`Expected a hasMany field for ${key}`);
618
- }
619
- })(field?.kind === 'hasMany') : {};
620
- const cacheOptions = options ? extractCacheOptions(options) : {
621
- reload: true
622
- };
623
- cacheOptions.types = [field.type];
624
- const rawValue = this.store.cache.getRelationship(this.identifier, key);
625
- const req = {
626
- url: getRelatedLink(rawValue),
627
- op: 'findHasMany',
628
- method: 'GET',
629
- records: rawValue.data,
630
- cacheOptions,
631
- options: {
632
- field,
633
- identifier: this.identifier,
634
- links: rawValue.links,
635
- meta: rawValue.meta
636
- },
637
- [EnableHydration]: false
638
- };
639
- return this.store.request(req);
640
- }
641
- mutate(mutation) {
642
- this.store.cache.mutate(mutation);
643
- }
644
- }
645
- function getRelatedLink(resource) {
646
- const related = resource.links?.related;
647
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
648
- if (!test) {
649
- throw new Error(`Expected a related link`);
650
- }
651
- })(related) : {};
652
- return typeof related === 'object' ? related.href : related;
653
- }
654
- function extractCacheOptions(options) {
655
- const cacheOptions = {};
656
- if ('reload' in options) {
657
- cacheOptions.reload = options.reload;
658
- }
659
- if ('backgroundReload' in options) {
660
- cacheOptions.backgroundReload = options.backgroundReload;
661
- }
662
- return cacheOptions;
663
- }
664
- function getHasManyField(context) {
665
- const signal = entangleSignal(context.signals, context.record, context.path.at(-1), null);
666
- const {
667
- store,
668
- field
669
- } = context;
670
- if (field.options.linksMode) {
671
- const {
672
- record
673
- } = context;
674
- // the thing we hand out needs to know its owner and path in a private manner
675
- // its "address" is the parent identifier (identifier) + field name (field.name)
676
- // in the nested object case field name here is the full dot path from root resource to this value
677
- // its "key" is the field on the parent record
678
- // its "owner" is the parent record
679
-
680
- const cached = signal.value;
681
- if (cached) {
682
- return cached;
683
- }
684
- const {
685
- editable,
686
- resourceKey
687
- } = context;
688
- const {
689
- cache
690
- } = store;
691
- const rawValue = cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field));
692
- if (!rawValue) {
693
- return null;
694
- }
695
- const managedArray = new RelatedCollection({
696
- store,
697
- type: field.type,
698
- identifier: resourceKey,
699
- cache,
700
- field: context.legacy ? field : undefined,
701
- // we divorce the reference here because ManyArray mutates the target directly
702
- // before sending the mutation op to the cache. We may be able to avoid this in the future
703
- identifiers: rawValue.data?.slice(),
704
- key: field.name,
705
- meta: rawValue.meta || null,
706
- links: rawValue.links || null,
707
- isPolymorphic: field.options.polymorphic ?? false,
708
- isAsync: field.options.async ?? false,
709
- // TODO: Grab the proper value
710
- _inverseIsAsync: false,
711
- // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
712
- manager: new ManyArrayManager(record, editable),
713
- isLoaded: true,
714
- allowMutation: editable
715
- });
716
- signal.value = managedArray;
717
- return managedArray;
718
- }
719
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
720
- if (!test) {
721
- throw new Error(`Can only use hasMany fields when the resource is in legacy mode`);
722
- }
723
- })(context.legacy) : {};
724
- return store.schema._kind('@legacy', 'hasMany').get(store, context.record, context.resourceKey, field);
725
- }
726
- function setHasManyField(context) {
727
- const {
728
- store
729
- } = context;
730
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
731
- if (!test) {
732
- throw new Error(`Can only use hasMany fields when the resource is in legacy mode`);
733
- }
734
- })(context.legacy) : {};
735
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
736
- if (!test) {
737
- throw new Error(`You must pass an array of records to set a hasMany relationship`);
738
- }
739
- })(Array.isArray(context.value)) : {};
740
- store.schema._kind('@legacy', 'hasMany').set(store, context.record, context.resourceKey, context.field, context.value);
741
- return true;
742
- }
743
- function getHashField(context) {
744
- const {
745
- field,
746
- path,
747
- resourceKey
748
- } = context;
749
- const {
750
- schema,
751
- cache
752
- } = context.store;
753
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
754
- if (!test) {
755
- throw new Error(`Cannot use a ${field.kind} directly on a resource.`);
756
- }
757
- })(Array.isArray(path) && path.length > 1) : {};
758
- const realPath = path.slice(0, -1);
759
- const rawData = context.editable ? cache.getAttr(resourceKey, realPath) : cache.getRemoteAttr(resourceKey, realPath);
760
- return schema.hashFn(field)(rawData, field.options ?? null, field.name ?? null);
761
- }
762
- function setHashField(context) {
763
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
764
- {
765
- throw new Error(`ILLEGAL SET: Cannot set '${Array.isArray(context.path) ? context.path.join('.') : context.path}' on '${context.resourceKey.type}' as ${context.field.kind} fields are not mutable`);
766
- }
767
- })() : {};
768
- return false;
769
- }
770
- function getIdentityField(context) {
771
- entangleSignal(context.signals, context.record, '@identity', null);
772
- return context.resourceKey.id;
773
- }
774
- function setIdentityField(context) {
775
- const {
776
- value,
777
- resourceKey,
778
- store
779
- } = context;
780
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
781
- if (!test) {
782
- throw new Error(`Expected to receive a string id`);
783
- }
784
- })(typeof value === 'string' && value.length) : {};
785
- const normalizedId = String(value);
786
- const didChange = normalizedId !== resourceKey.id;
787
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
788
- if (!test) {
789
- throw new Error(`Cannot set ${resourceKey.type} record's id to ${normalizedId}, because id is already ${resourceKey.id}`);
790
- }
791
- })(!didChange || resourceKey.id === null) : {};
792
- if (normalizedId !== null && didChange) {
793
- store._instanceCache.setRecordId(resourceKey, normalizedId);
794
- store.notifications.notify(resourceKey, 'identity');
795
- }
796
- return true;
797
- }
798
- function getLocalField(context) {
799
- const {
800
- field
801
- } = context;
802
- const signal = getOrCreateInternalSignal(context.signals, context.record, field.name, field.options?.defaultValue ?? null);
803
- consumeInternalSignal(signal);
804
- return signal.value;
805
- }
806
- function setLocalField(context) {
807
- const {
808
- value
809
- } = context;
810
- const signal = getOrCreateInternalSignal(context.signals, context.record, context.field.name, value);
811
- if (signal.value !== value) {
812
- signal.value = value;
813
- notifyInternalSignal(signal);
814
- }
815
- return true;
816
- }
817
- const ObjectSymbols = new Set([OBJECT_SIGNAL, Context, SOURCE]);
818
-
819
- // const ignoredGlobalFields = new Set<string>(['setInterval', 'nodeType', 'nodeName', 'length', 'document', STRUCTURED]);
820
-
821
- // eslint-disable-next-line @typescript-eslint/no-extraneous-class
822
- class ManagedObject {
823
- constructor(context) {
824
- const {
825
- field,
826
- path
827
- } = context;
828
- // eslint-disable-next-line @typescript-eslint/no-this-alias
829
- const self = this;
830
- this[SOURCE] = Object.assign({}, context.value);
831
- const signals = withSignalStore(this);
832
- const _SIGNAL = this[OBJECT_SIGNAL] = entangleSignal(signals, this, OBJECT_SIGNAL, undefined);
833
- this[Context] = context;
834
- const identifier = context.resourceKey;
835
- const {
836
- cache,
837
- schema
838
- } = context.store;
839
-
840
- // prettier-ignore
841
- const extensions = !context.legacy ? null : schema.CAUTION_MEGA_DANGER_ZONE_objectExtensions(field, null);
842
- const proxy = new Proxy(this[SOURCE], {
843
- ownKeys() {
844
- return Object.keys(self[SOURCE]);
845
- },
846
- has(target, prop) {
847
- return prop in self[SOURCE];
848
- },
849
- getOwnPropertyDescriptor(target, prop) {
850
- return {
851
- writable: context.editable,
852
- enumerable: true,
853
- configurable: true
854
- };
855
- },
856
- get(target, prop, receiver) {
857
- if (ObjectSymbols.has(prop)) {
858
- return self[prop];
859
- }
860
- if (prop === Symbol.toPrimitive) {
861
- return () => null;
862
- }
863
- if (prop === Symbol.toStringTag) {
864
- return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;
865
- }
866
- if (prop === 'constructor') {
867
- return Object;
868
- }
869
- if (prop === 'toString') {
870
- return function () {
871
- return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;
872
- };
873
- }
874
- if (prop === 'toHTML') {
875
- return function () {
876
- return '<span>ManagedObject</span>';
877
- };
878
- }
879
- if (_SIGNAL.isStale) {
880
- _SIGNAL.isStale = false;
881
- let newData = cache.getAttr(identifier, path);
882
- if (newData && newData !== self[SOURCE]) {
883
- if (field.type) {
884
- const transform = schema.transformation(field);
885
- newData = transform.hydrate(newData, field.options ?? null, context.record);
886
- }
887
- self[SOURCE] = Object.assign({}, newData); // Add type assertion for newData
888
- }
889
- }
890
-
891
- // toJSON and extensions need to come after we update data if stale
892
- if (prop === 'toJSON') {
893
- return function () {
894
- return structuredClone(self[SOURCE]);
895
- };
896
- }
897
-
898
- // we always defer to data before extensions
899
- if (prop in self[SOURCE]) {
900
- consumeInternalSignal(_SIGNAL);
901
- return self[SOURCE][prop];
902
- }
903
- if (isExtensionProp(extensions, prop)) {
904
- return performObjectExtensionGet(receiver, extensions, signals, prop);
905
- }
906
- return Reflect.get(target, prop, receiver);
907
- },
908
- set(target, prop, value, receiver) {
909
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
910
- if (!test) {
911
- throw new Error(`Cannot set read-only property '${String(prop)}' on ManagedObject`);
912
- }
913
- })(context.editable) : {};
914
-
915
- // since objects function as dictionaries, we can't defer to schema/data before extensions
916
- // unless the prop is in the existing data.
917
- if (!(prop in self[SOURCE]) && isExtensionProp(extensions, prop)) {
918
- return performExtensionSet(receiver, extensions, signals, prop, value);
919
- }
920
- const reflect = Reflect.set(target, prop, value, receiver);
921
- if (!reflect) {
922
- return false;
923
- }
924
- if (!field.type) {
925
- cache.setAttr(identifier, path, self[SOURCE]);
926
- } else {
927
- const transform = schema.transformation(field);
928
- const val = transform.serialize(self[SOURCE], field.options ?? null, context.record);
929
- cache.setAttr(identifier, path, val);
930
- }
931
- _SIGNAL.isStale = true;
932
- return true;
933
- }
934
- });
935
- return proxy;
936
- }
937
- }
938
- const ManagedObjectMap = getOrSetGlobal('ManagedObjectMap', new Map());
939
- function peekManagedObject(record, field) {
940
- const managedObjectMapForRecord = ManagedObjectMap.get(record);
941
- if (managedObjectMapForRecord) {
942
- return managedObjectMapForRecord.get(field.name);
943
- }
944
- }
945
- function getObjectField(context) {
946
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
947
- const {
948
- record,
949
- field
950
- } = context;
951
- const managedObjectMapForRecord = ManagedObjectMap.get(record);
952
- let managedObject;
953
- if (managedObjectMapForRecord) {
954
- managedObject = managedObjectMapForRecord.get(field.name);
955
- }
956
- if (managedObject) {
957
- return managedObject;
958
- } else {
959
- const {
960
- store,
961
- resourceKey,
962
- path
963
- } = context;
964
- const {
965
- cache,
966
- schema
967
- } = store;
968
- let rawValue = context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path);
969
- if (!rawValue) {
970
- return null;
971
- }
972
- if (field.type) {
973
- const transform = schema.transformation(field);
974
- rawValue = transform.hydrate(rawValue, field.options ?? null, record);
975
- }
976
- managedObject = new ManagedObject({
977
- store,
978
- resourceKey,
979
- modeName: context.modeName,
980
- legacy: context.legacy,
981
- editable: context.editable,
982
- path,
983
- field,
984
- record,
985
- signals: context.signals,
986
- value: rawValue
987
- });
988
- if (!managedObjectMapForRecord) {
989
- ManagedObjectMap.set(record, new Map([[field.name, managedObject]]));
990
- } else {
991
- managedObjectMapForRecord.set(field.name, managedObject);
992
- }
993
- }
994
- return managedObject;
995
- }
996
- function setObjectField(context) {
997
- const {
998
- field,
999
- value,
1000
- record
1001
- } = context;
1002
- const {
1003
- cache,
1004
- schema
1005
- } = context.store;
1006
- if (!field.type) {
1007
- let newValue = value;
1008
- if (value !== null) {
1009
- newValue = {
1010
- ...value
1011
- };
1012
- } else {
1013
- ManagedObjectMap.delete(record);
1014
- }
1015
- cache.setAttr(context.resourceKey, context.path, newValue);
1016
- const peeked = peekManagedObject(record, field);
1017
- if (peeked) {
1018
- const objSignal = peeked[OBJECT_SIGNAL];
1019
- objSignal.isStale = true;
1020
- }
1021
- return true;
1022
- }
1023
- const transform = schema.transformation(field);
1024
- const rawValue = transform.serialize({
1025
- ...value
1026
- }, field.options ?? null, record);
1027
- cache.setAttr(context.resourceKey, context.path, rawValue);
1028
- const peeked = peekManagedObject(record, field);
1029
- if (peeked) {
1030
- const objSignal = peeked[OBJECT_SIGNAL];
1031
- objSignal.isStale = true;
1032
- }
1033
- return true;
1034
- }
1035
-
1036
- // TODO probably this should just be a Document
1037
- // but its separate until we work out the lid situation
1038
- class ResourceRelationship {
1039
- constructor(context) {
1040
- const {
1041
- store,
1042
- resourceKey
1043
- } = context;
1044
- const {
1045
- cache
1046
- } = store;
1047
- const name = getFieldCacheKeyStrict(context.field);
1048
- const rawValue = context.editable ? cache.getRelationship(resourceKey, name) : cache.getRemoteRelationship(resourceKey, name);
1049
-
1050
- // TODO setup true lids for relationship documents
1051
- // @ts-expect-error we need to give relationship documents a lid
1052
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1053
- this.lid = rawValue.lid ?? rawValue.links?.self ?? `relationship:${resourceKey.lid}.${name}`;
1054
- this.data = rawValue.data ? store.peekRecord(rawValue.data) : null;
1055
- this.name = name;
1056
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1057
- this.links = Object.freeze(Object.assign({}, rawValue.links));
1058
- this.meta = Object.freeze(Object.assign({}, rawValue.meta));
1059
- } else {
1060
- this.links = rawValue.links ?? {};
1061
- this.meta = rawValue.meta ?? {};
1062
- }
1063
- this[Context] = context;
1064
- }
1065
- fetch(options) {
1066
- const url = options?.url ?? getHref(this.links.related) ?? getHref(this.links.self) ?? null;
1067
- if (!url) {
1068
- throw new Error(`Cannot ${options?.method ?? 'fetch'} ${this[Context].resourceKey.type}.${String(this.name)} because it has no related link`);
1069
- }
1070
- const request = Object.assign({
1071
- url,
1072
- method: 'GET'
1073
- }, options);
1074
- return this[Context].store.request(request);
1075
- }
1076
- }
1077
- defineSignal(ResourceRelationship.prototype, 'data', null);
1078
- defineSignal(ResourceRelationship.prototype, 'links', null);
1079
- defineSignal(ResourceRelationship.prototype, 'meta', null);
1080
- function getHref(link) {
1081
- if (!link) {
1082
- return null;
1083
- }
1084
- if (typeof link === 'string') {
1085
- return link;
1086
- }
1087
- return link.href;
1088
- }
1089
- function getResourceField(context) {
1090
- entangleSignal(context.signals, context.record, context.path.at(-1), null);
1091
- return new ResourceRelationship(context);
1092
- }
1093
- function setResourceField(context) {
1094
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1095
- {
1096
- throw new Error(`setting resource relationships is not yet supported`);
1097
- }
1098
- })() : {};
1099
- return false;
1100
- }
1101
- function setSchemaArrayField(context) {
1102
- const arrayValue = context.value?.slice();
1103
- const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1));
1104
- const peeked = fieldSignal?.value;
1105
- context.store.cache.setAttr(context.resourceKey, context.path, arrayValue);
1106
- if (peeked) {
1107
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1108
- if (!test) {
1109
- throw new Error(`Expected the peekManagedArray for ${context.field.kind} to return a ManagedArray`);
1110
- }
1111
- })(ARRAY_SIGNAL in peeked) : {};
1112
- const arrSignal = peeked[ARRAY_SIGNAL];
1113
- arrSignal.isStale = true;
1114
- if (!Array.isArray(arrayValue)) {
1115
- fieldSignal.value = null;
1116
- }
1117
- }
1118
- return true;
1119
- }
1120
- function getSchemaObjectField(context) {
1121
- const signal = entangleSignal(context.signals, context.record, context.path.at(-1), null);
1122
- const {
1123
- store,
1124
- resourceKey,
1125
- path,
1126
- field
1127
- } = context;
1128
- const {
1129
- cache
1130
- } = store;
1131
- let rawValue = context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path);
1132
- if (!rawValue && !field.options?.polymorphic && field.options?.defaultValue) {
1133
- rawValue = {};
1134
- }
1135
- if (!rawValue) {
1136
- if (signal.value) {
1137
- const value = signal.value;
1138
- // TODO if we had idle scheduling this should be done there.
1139
- void Promise.resolve().then(() => {
1140
- value.value[Destroy]();
1141
- });
1142
- signal.value = null;
1143
- }
1144
- return null;
1145
- }
1146
- const {
1147
- schema
1148
- } = store;
1149
- let objectType;
1150
- if (field.options?.polymorphic) {
1151
- const typePath = field.options.type ?? 'type';
1152
- // if we are polymorphic, then context.field.options.type will
1153
- // either specify a path on the rawValue to use as the type, defaulting to "type" or
1154
- // the special string "@hash" which tells us to treat field.type as a hashFn name with which
1155
- // to calc the type.
1156
- if (typePath === '@hash') {
1157
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1158
- if (!test) {
1159
- throw new Error(`Expected the field to define a hashFn as its type`);
1160
- }
1161
- })(field.type) : {};
1162
- const hashFn = schema.hashFn({
1163
- type: field.type
1164
- });
1165
- // TODO consider if there are better options and name args we could provide.
1166
- objectType = hashFn(rawValue, null, null);
1167
- } else {
1168
- objectType = rawValue[typePath];
1169
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1170
- if (!test) {
1171
- throw new Error(`Expected the type path for the field to be a value on the raw object`);
1172
- }
1173
- })(typePath && objectType && typeof objectType === 'string') : {};
1174
- }
1175
- } else {
1176
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1177
- if (!test) {
1178
- throw new Error(`A non-polymorphic SchemaObjectField must provide a SchemaObject type in its definition`);
1179
- }
1180
- })(field.type) : {};
1181
- objectType = field.type;
1182
- }
1183
- const hashField = schema.resource({
1184
- type: objectType
1185
- }).identity;
1186
- const identity = hashField ? schema.hashFn(hashField)(rawValue, hashField.options ?? null, hashField.name) : field.name;
1187
- const cachedSchemaObject = signal.value;
1188
- if (cachedSchemaObject) {
1189
- if (cachedSchemaObject.type === objectType && cachedSchemaObject.identity === identity) {
1190
- return cachedSchemaObject.value;
1191
- } else {
1192
- // TODO if we had idle scheduling this should be done there.
1193
- void Promise.resolve().then(() => {
1194
- cachedSchemaObject.value[Destroy]();
1195
- });
1196
- }
1197
- }
1198
- const schemaObject = new ReactiveResource({
1199
- store: context.store,
1200
- resourceKey: context.resourceKey,
1201
- modeName: context.modeName,
1202
- legacy: context.legacy,
1203
- editable: context.editable,
1204
- path: context.path,
1205
- field: context.field,
1206
- value: objectType
1207
- });
1208
- signal.value = {
1209
- type: objectType,
1210
- identity: identity,
1211
- value: schemaObject
1212
- };
1213
- return schemaObject;
1214
- }
1215
- function setSchemaObjectField(context) {
1216
- const {
1217
- store,
1218
- value
1219
- } = context;
1220
- let newValue = value;
1221
- if (value !== null) {
1222
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1223
- if (!test) {
1224
- throw new Error(`Expected value to be an object`);
1225
- }
1226
- })(typeof value === 'object') : {};
1227
- newValue = {
1228
- ...value
1229
- };
1230
- // FIXME the case of field.type to string here is likely incorrect
1231
- const schemaFields = store.schema.fields({
1232
- type: context.field.type
1233
- });
1234
- for (const key of Object.keys(newValue)) {
1235
- if (!schemaFields.has(key)) {
1236
- throw new Error(`Field ${key} does not exist on schema object ${context.field.type}`);
1237
- }
1238
- }
1239
- } else {
1240
- ManagedObjectMap.delete(context.record);
1241
- }
1242
- store.cache.setAttr(context.resourceKey, context.path, newValue);
1243
- // const peeked = peekManagedObject(self, field);
1244
- // if (peeked) {
1245
- // const objSignal = peeked[OBJECT_SIGNAL];
1246
- // objSignal.isStale = true;
1247
- // }
1248
- return true;
1249
- }
1250
- const DefaultMode = {
1251
- '@hash': {
1252
- get: getHashField,
1253
- set: setHashField,
1254
- mutable: false,
1255
- enumerable: false,
1256
- serializable: false
1257
- },
1258
- '@id': {
1259
- get: getIdentityField,
1260
- set: setIdentityField,
1261
- mutable: true,
1262
- enumerable: true,
1263
- serializable: true
1264
- },
1265
- '@local': {
1266
- get: getLocalField,
1267
- set: setLocalField,
1268
- mutable: true,
1269
- enumerable: false,
1270
- serializable: false
1271
- },
1272
- alias: {
1273
- get: getAliasField,
1274
- set: setAliasField,
1275
- mutable: true,
1276
- enumerable: true,
1277
- serializable: false
1278
- },
1279
- array: {
1280
- get: getArrayField,
1281
- set: setArrayField,
1282
- mutable: true,
1283
- enumerable: true,
1284
- serializable: true
1285
- },
1286
- attribute: {
1287
- get: getAttributeField,
1288
- set: setAttributeField,
1289
- mutable: true,
1290
- enumerable: true,
1291
- serializable: true
1292
- },
1293
- belongsTo: {
1294
- get: getBelongsToField,
1295
- set: setBelongsToField,
1296
- mutable: true,
1297
- enumerable: true,
1298
- serializable: true
1299
- },
1300
- collection: {
1301
- get: getCollectionField,
1302
- set: setCollectionField,
1303
- mutable: true,
1304
- enumerable: true,
1305
- serializable: true
1306
- },
1307
- derived: {
1308
- get: getDerivedField,
1309
- set: setDerivedField,
1310
- mutable: true,
1311
- enumerable: true,
1312
- serializable: false
1313
- },
1314
- field: {
1315
- get: getGenericField,
1316
- set: setGenericField,
1317
- mutable: true,
1318
- enumerable: true,
1319
- serializable: true
1320
- },
1321
- hasMany: {
1322
- get: getHasManyField,
1323
- set: setHasManyField,
1324
- mutable: true,
1325
- enumerable: true,
1326
- serializable: true
1327
- },
1328
- object: {
1329
- get: getObjectField,
1330
- set: setObjectField,
1331
- mutable: true,
1332
- enumerable: true,
1333
- serializable: true
1334
- },
1335
- resource: {
1336
- get: getResourceField,
1337
- set: setResourceField,
1338
- mutable: true,
1339
- enumerable: true,
1340
- serializable: true
1341
- },
1342
- 'schema-array': {
1343
- get: getArrayField,
1344
- set: setSchemaArrayField,
1345
- mutable: true,
1346
- enumerable: true,
1347
- serializable: true
1348
- },
1349
- 'schema-object': {
1350
- get: getSchemaObjectField,
1351
- set: setSchemaObjectField,
1352
- mutable: true,
1353
- enumerable: true,
1354
- serializable: true
1355
- }
1356
- };
1357
- const IgnoredGlobalFields = new Set(['length', 'nodeType', 'then', 'setInterval', 'document', STRUCTURED]);
1358
- const symbolList = [Context, Destroy, RecordStore, Checkout];
1359
- const RecordSymbols = new Set(symbolList);
1360
- function isPathMatch(a, b) {
1361
- return a.length === b.length && a.every((v, i) => v === b[i]);
1362
- }
1363
- function isNonEnumerableProp(prop) {
1364
- return prop === 'constructor' || prop === 'prototype' || prop === '__proto__' || prop === 'toString' || prop === 'toJSON' || prop === 'toHTML' || typeof prop === 'symbol';
1365
- }
1366
- const Editables = new WeakMap();
1367
- /**
1368
- * A class that uses a the ResourceSchema for a ResourceType
1369
- * and a ResouceKey to transform data from the cache into a rich, reactive
1370
- * object.
1371
- *
1372
- * This class is not directly instantiable. To use it, you should
1373
- * configure the store's `instantiateRecord` and `teardownRecord` hooks
1374
- * with the matching hooks provided by this package.
1375
- *
1376
- * @hideconstructor
1377
- * @public
1378
- */
1379
- // eslint-disable-next-line @typescript-eslint/no-extraneous-class
1380
- class ReactiveResource {
1381
- constructor(context) {
1382
- const {
1383
- store
1384
- } = context;
1385
- const identifier = context.resourceKey;
1386
- const embeddedField = context.field;
1387
- const embeddedPath = context.path;
1388
- const isEmbedded = context.field !== null;
1389
- const IS_EDITABLE = context.editable ?? false;
1390
- const schema = store.schema;
1391
- const objectType = isEmbedded ? context.value : identifier.type;
1392
- const ResourceSchema = schema.resource(isEmbedded ? {
1393
- type: objectType
1394
- } : identifier);
1395
- const identityField = ResourceSchema.identity;
1396
- const BoundFns = new Map();
1397
-
1398
- // prettier-ignore
1399
- const extensions = !context.legacy ? null : isEmbedded ? schema.CAUTION_MEGA_DANGER_ZONE_objectExtensions(embeddedField, objectType) : schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(identifier);
1400
- this[Context] = context;
1401
- this[RecordStore] = context.store;
1402
- const fields = isEmbedded ? schema.fields({
1403
- type: objectType
1404
- }) : schema.fields(identifier);
1405
- const method = typeof schema.cacheFields === 'function' ? 'cacheFields' : 'fields';
1406
- const cacheFields = isEmbedded ? schema[method]({
1407
- type: objectType
1408
- }) : schema[method](identifier);
1409
- const signals = withSignalStore(this);
1410
- const proxy = new Proxy(this, {
1411
- ownKeys() {
1412
- const identityKey = identityField?.name;
1413
- const keys = Array.from(fields.keys());
1414
- if (identityKey) {
1415
- keys.unshift(identityKey);
1416
- }
1417
- return keys;
1418
- },
1419
- has(target, prop) {
1420
- if (prop === Destroy || prop === Checkout) {
1421
- return true;
1422
- }
1423
- return fields.has(prop);
1424
- },
1425
- getOwnPropertyDescriptor(target, prop) {
1426
- const schemaForField = prop === identityField?.name ? identityField : fields.get(prop);
1427
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1428
- if (!test) {
1429
- throw new Error(`No field named ${String(prop)} on ${identifier.type}`);
1430
- }
1431
- })(schemaForField) : {};
1432
- if (isNonEnumerableProp(prop)) {
1433
- return {
1434
- writable: false,
1435
- enumerable: false,
1436
- configurable: true
1437
- };
1438
- }
1439
- switch (schemaForField.kind) {
1440
- case 'derived':
1441
- return {
1442
- writable: false,
1443
- enumerable: true,
1444
- configurable: true
1445
- };
1446
- case '@id':
1447
- return {
1448
- writable: identifier.id === null,
1449
- enumerable: true,
1450
- configurable: true
1451
- };
1452
- case '@local':
1453
- case 'field':
1454
- case 'attribute':
1455
- case 'resource':
1456
- case 'alias':
1457
- case 'belongsTo':
1458
- case 'hasMany':
1459
- case 'collection':
1460
- case 'schema-array':
1461
- case 'array':
1462
- case 'schema-object':
1463
- case 'object':
1464
- return {
1465
- writable: IS_EDITABLE,
1466
- enumerable: true,
1467
- configurable: true
1468
- };
1469
- default:
1470
- return {
1471
- writable: false,
1472
- enumerable: false,
1473
- configurable: false
1474
- };
1475
- }
1476
- },
1477
- get(target, prop, receiver) {
1478
- if (RecordSymbols.has(prop)) {
1479
- if (prop === Destroy) {
1480
- return () => _DESTROY(receiver);
1481
- }
1482
- if (prop === Checkout) {
1483
- return () => _CHECKOUT(receiver);
1484
- }
1485
- return target[prop];
1486
- }
1487
- if (prop === Signals) {
1488
- return signals;
1489
- }
1490
-
1491
- // TODO make this a symbol
1492
- if (prop === '___notifications') {
1493
- return target.___notifications;
1494
- }
1495
-
1496
- // ReactiveResource reserves use of keys that begin with these characters
1497
- // for its own usage.
1498
- // _, @, $, *
1499
-
1500
- const maybeField = prop === identityField?.name ? identityField : fields.get(prop);
1501
- if (!maybeField) {
1502
- if (IgnoredGlobalFields.has(prop)) {
1503
- return undefined;
1504
- }
1505
-
1506
- /////////////////////////////////////////////////////////////
1507
- //// Note these bound function behaviors are essentially ////
1508
- //// built-in but overrideable derivations. ////
1509
- //// ////
1510
- //// The bar for this has to be "basic expectations of ////
1511
- /// an object" – very, very high ////
1512
- /////////////////////////////////////////////////////////////
1513
-
1514
- if (prop === Symbol.toStringTag || prop === 'toString') {
1515
- let fn = BoundFns.get('toString');
1516
- if (!fn) {
1517
- fn = function () {
1518
- entangleSignal(signals, receiver, '@identity', null);
1519
- return `Record<${identifier.type}:${identifier.id} (${identifier.lid})>`;
1520
- };
1521
- BoundFns.set(prop, fn);
1522
- }
1523
- return fn;
1524
- }
1525
- if (prop === 'toHTML') {
1526
- let fn = BoundFns.get('toHTML');
1527
- if (!fn) {
1528
- fn = function () {
1529
- entangleSignal(signals, receiver, '@identity', null);
1530
- return `<span>Record<${identifier.type}:${identifier.id} (${identifier.lid})></span>`;
1531
- };
1532
- BoundFns.set(prop, fn);
1533
- }
1534
- return fn;
1535
- }
1536
- if (prop === 'toJSON') {
1537
- let fn = BoundFns.get('toJSON');
1538
- if (!fn) {
1539
- fn = function () {
1540
- const json = {};
1541
- for (const key in receiver) {
1542
- json[key] = receiver[key];
1543
- }
1544
- return json;
1545
- };
1546
- BoundFns.set(prop, fn);
1547
- }
1548
- return fn;
1549
- }
1550
- if (prop === Symbol.toPrimitive) return () => null;
1551
- if (prop === Symbol.iterator) {
1552
- let fn = BoundFns.get(Symbol.iterator);
1553
- if (!fn) {
1554
- fn = function* () {
1555
- for (const key in receiver) {
1556
- yield [key, receiver[key]];
1557
- }
1558
- };
1559
- BoundFns.set(Symbol.iterator, fn);
1560
- }
1561
- return fn;
1562
- }
1563
- if (prop === 'constructor') {
1564
- return ReactiveResource;
1565
- }
1566
- if (isExtensionProp(extensions, prop)) {
1567
- return performObjectExtensionGet(receiver, extensions, signals, prop);
1568
- }
1569
-
1570
- // too many things check for random symbols
1571
- if (typeof prop === 'symbol') return undefined;
1572
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1573
- {
1574
- throw new Error(`No field named ${String(prop)} on ${isEmbedded ? embeddedField.type : identifier.type}`);
1575
- }
1576
- })() : {};
1577
- return undefined;
1578
- }
1579
- const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;
1580
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1581
- if (!test) {
1582
- throw new Error(`Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`);
1583
- }
1584
- })(maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)) : {};
1585
- /**
1586
- * Prop Array is the path from a resource to the field including
1587
- * intermediate "links" on arrays,objects,schema-arrays and schema-objects.
1588
- *
1589
- * E.g. in the following
1590
- *
1591
- * ```
1592
- * const user = {
1593
- * addresses: [{
1594
- * street: 'Sunset Blvd',
1595
- * zip: 90210
1596
- * }]
1597
- * }
1598
- * ```
1599
- *
1600
- * The propArray for "street" is ['addresses', 0, 'street']
1601
- *
1602
- * Prop Array follows the `cache` path to the value, not the ui path.
1603
- * Thus, if `addresses` has a sourceKey of `user_addresses` and
1604
- * `zip` has a sourceKey of `zip_code` then the propArray for "zip" is
1605
- * ['user_addresses', 0, 'zip_code']
1606
- */
1607
- const propArray = isEmbedded ? embeddedPath.slice() : [];
1608
- // we use the field.name instead of prop here because we want to use the cache-path not
1609
- // the record path.
1610
- // SAFETY: we lie as string here because if we were to get null
1611
- // we would be in a field kind that won't use the propArray below.
1612
- const fieldCacheKey = getFieldCacheKey(field);
1613
- propArray.push(fieldCacheKey);
1614
- switch (field.kind) {
1615
- case '@id':
1616
- case '@hash':
1617
- case '@local':
1618
- case 'derived':
1619
- case 'field':
1620
- case 'attribute':
1621
- case 'schema-array':
1622
- case 'array':
1623
- case 'schema-object':
1624
- case 'object':
1625
- case 'resource':
1626
- case 'belongsTo':
1627
- case 'hasMany':
1628
- case 'collection':
1629
- return DefaultMode[field.kind].get({
1630
- store,
1631
- resourceKey: identifier,
1632
- modeName: context.modeName,
1633
- legacy: context.legacy,
1634
- editable: context.editable,
1635
- path: propArray,
1636
- field: field,
1637
- record: receiver,
1638
- signals,
1639
- value: null
1640
- });
1641
- default:
1642
- assertNeverField(identifier, field, propArray);
1643
- }
1644
- },
1645
- set(target, prop, value, receiver) {
1646
- if (!IS_EDITABLE) {
1647
- const type = isEmbedded ? embeddedField.type : identifier.type;
1648
- throw new Error(`Cannot set ${String(prop)} on ${type} because the record is not editable`);
1649
- }
1650
- const maybeField = prop === identityField?.name ? identityField : fields.get(prop);
1651
- if (!maybeField) {
1652
- const type = isEmbedded ? embeddedField.type : identifier.type;
1653
- if (isExtensionProp(extensions, prop)) {
1654
- return performExtensionSet(receiver, extensions, signals, prop, value);
1655
- }
1656
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1657
- {
1658
- throw new Error(`There is no settable field named ${String(prop)} on ${type}`);
1659
- }
1660
- })() : {};
1661
- return false;
1662
- }
1663
- const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;
1664
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1665
- if (!test) {
1666
- throw new Error(`Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`);
1667
- }
1668
- })(maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)) : {};
1669
- /**
1670
- * Prop Array is the path from a resource to the field including
1671
- * intermediate "links" on arrays,objects,schema-arrays and schema-objects.
1672
- *
1673
- * E.g. in the following
1674
- *
1675
- * ```
1676
- * const user = {
1677
- * addresses: [{
1678
- * street: 'Sunset Blvd',
1679
- * zip: 90210
1680
- * }]
1681
- * }
1682
- * ```
1683
- *
1684
- * The propArray for "street" is ['addresses', 0, 'street']
1685
- *
1686
- * Prop Array follows the `cache` path to the value, not the ui path.
1687
- * Thus, if `addresses` has a sourceKey of `user_addresses` and
1688
- * `zip` has a sourceKey of `zip_code` then the propArray for "zip" is
1689
- * ['user_addresses', 0, 'zip_code']
1690
- */
1691
- const propArray = isEmbedded ? embeddedPath.slice() : [];
1692
- // we use the field.name instead of prop here because we want to use the cache-path not
1693
- // the record path.
1694
- // SAFETY: we lie as string here because if we were to get null
1695
- // we would be in a field kind that won't use the propArray below.
1696
- const fieldCacheKey = getFieldCacheKey(field);
1697
- propArray.push(fieldCacheKey);
1698
- switch (field.kind) {
1699
- case '@id':
1700
- case '@hash':
1701
- case '@local':
1702
- case 'field':
1703
- case 'attribute':
1704
- case 'derived':
1705
- case 'array':
1706
- case 'schema-array':
1707
- case 'schema-object':
1708
- case 'object':
1709
- case 'resource':
1710
- case 'belongsTo':
1711
- case 'hasMany':
1712
- case 'collection':
1713
- return DefaultMode[field.kind].set({
1714
- store,
1715
- resourceKey: identifier,
1716
- modeName: context.modeName,
1717
- legacy: context.legacy,
1718
- editable: context.editable,
1719
- path: propArray,
1720
- field: field,
1721
- record: receiver,
1722
- signals,
1723
- value
1724
- });
1725
- default:
1726
- return assertNeverField(identifier, field, propArray);
1727
- }
1728
- }
1729
- });
1730
-
1731
- // what signal do we need for embedded record?
1732
- this.___notifications = store.notifications.subscribe(identifier, (_, type, key) => {
1733
- switch (type) {
1734
- case 'identity':
1735
- {
1736
- if (isEmbedded || !identityField) return; // base paths never apply to embedded records
1737
-
1738
- if (identityField.name && identityField.kind === '@id') {
1739
- const signal = signals.get('@identity');
1740
- if (signal) {
1741
- notifyInternalSignal(signal);
1742
- }
1743
- }
1744
- break;
1745
- }
1746
- case 'attributes':
1747
- if (key) {
1748
- if (Array.isArray(key)) {
1749
- if (!isEmbedded) return; // deep paths will be handled by embedded records
1750
- // TODO we should have the notification manager
1751
- // ensure it is safe for each callback to mutate this array
1752
- if (isPathMatch(embeddedPath, key)) {
1753
- // handle the notification
1754
- // TODO we should likely handle this notification here
1755
- // also we should add a LOGGING flag
1756
- // eslint-disable-next-line no-console
1757
- console.warn(`Notification unhandled for ${key.join(',')} on ${identifier.type}`, proxy);
1758
- return;
1759
- }
1760
-
1761
- // TODO we should add a LOGGING flag
1762
- // console.log(`Deep notification skipped for ${key.join('.')} on ${identifier.type}`, proxy);
1763
- // deep notify the key path
1764
- } else {
1765
- if (isEmbedded) return; // base paths never apply to embedded records
1766
-
1767
- // TODO determine what LOGGING flag to wrap this in if any
1768
- // console.log(`Notification for ${key} on ${identifier.type}`, proxy);
1769
- const signal = signals.get(key);
1770
- if (signal) {
1771
- notifyInternalSignal(signal);
1772
- }
1773
- const field = cacheFields.get(key);
1774
- if (field?.kind === 'array' || field?.kind === 'schema-array') {
1775
- const peeked = signal?.value;
1776
- if (peeked) {
1777
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1778
- if (!test) {
1779
- throw new Error(`Expected the peekManagedArray for ${field.kind} to return a ManagedArray`);
1780
- }
1781
- })(ARRAY_SIGNAL in peeked) : {};
1782
- const arrSignal = peeked[ARRAY_SIGNAL];
1783
- notifyInternalSignal(arrSignal);
1784
- }
1785
- }
1786
- if (field?.kind === 'object') {
1787
- const peeked = peekManagedObject(proxy, field);
1788
- if (peeked) {
1789
- const objSignal = peeked[OBJECT_SIGNAL];
1790
- notifyInternalSignal(objSignal);
1791
- }
1792
- }
1793
- }
1794
- }
1795
- break;
1796
- case 'relationships':
1797
- if (key) {
1798
- if (Array.isArray(key)) ;else {
1799
- if (isEmbedded) return; // base paths never apply to embedded records
1800
-
1801
- const field = cacheFields.get(key);
1802
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1803
- if (!test) {
1804
- throw new Error(`Expected relationship ${key} to be the name of a field`);
1805
- }
1806
- })(field) : {};
1807
- if (field.kind === 'belongsTo') {
1808
- // TODO determine what LOGGING flag to wrap this in if any
1809
- // console.log(`Notification for ${key} on ${identifier.type}`, proxy);
1810
- const signal = signals.get(key);
1811
- if (signal) {
1812
- notifyInternalSignal(signal);
1813
- }
1814
- // FIXME
1815
- } else if (field.kind === 'resource') ;else if (field.kind === 'hasMany') {
1816
- if (field.options.linksMode) {
1817
- const signal = signals.get(key);
1818
- if (signal) {
1819
- const peeked = signal.value;
1820
- if (peeked) {
1821
- notifyInternalSignal(peeked[ARRAY_SIGNAL]);
1822
- }
1823
- }
1824
- return;
1825
- }
1826
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1827
- if (!test) {
1828
- throw new Error(`Can only use hasMany fields when the resource is in legacy mode`);
1829
- }
1830
- })(context.legacy) : {};
1831
- if (schema._kind('@legacy', 'hasMany').notify(store, proxy, identifier, field)) {
1832
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1833
- if (!test) {
1834
- throw new Error(`Expected options to exist on relationship meta`);
1835
- }
1836
- })(field.options) : {};
1837
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1838
- if (!test) {
1839
- throw new Error(`Expected async to exist on relationship meta options`);
1840
- }
1841
- })('async' in field.options) : {};
1842
- if (field.options.async) {
1843
- const signal = signals.get(key);
1844
- if (signal) {
1845
- notifyInternalSignal(signal);
1846
- }
1847
- }
1848
- }
1849
- } else if (field.kind === 'collection') ;
1850
- }
1851
- }
1852
- break;
1853
- }
1854
- });
1855
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1856
- Object.defineProperty(this, '__SHOW_ME_THE_DATA_(debug mode only)__', {
1857
- enumerable: false,
1858
- configurable: true,
1859
- get() {
1860
- const data = {};
1861
- for (const key of fields.keys()) {
1862
- data[key] = proxy[key];
1863
- }
1864
- return data;
1865
- }
1866
- });
1867
- }
1868
- return proxy;
1869
- }
1870
- }
1871
- function _CHECKOUT(record) {
1872
- const context = record[Context];
1873
-
1874
- // IF we are already the editable record, throw an error
1875
- if (context.editable) {
1876
- throw new Error(`Cannot checkout an already editable record`);
1877
- }
1878
- const editable = Editables.get(record);
1879
- if (editable) {
1880
- return Promise.resolve(editable);
1881
- }
1882
- const isEmbedded = context.field !== null && context.path !== null;
1883
- if (isEmbedded) {
1884
- throw new Error(`Cannot checkout an embedded record (yet)`);
1885
- }
1886
- const editableRecord = new ReactiveResource({
1887
- store: context.store,
1888
- resourceKey: context.resourceKey,
1889
- modeName: context.legacy ? 'legacy' : 'polaris',
1890
- legacy: context.legacy,
1891
- editable: true,
1892
- path: null,
1893
- field: null,
1894
- value: null
1895
- });
1896
- setRecordIdentifier(editableRecord, recordIdentifierFor(record));
1897
- return Promise.resolve(editableRecord);
1898
- }
1899
- function _DESTROY(record) {
1900
- if (record[Context].legacy) {
1901
- // @ts-expect-error
1902
- record.isDestroying = true;
1903
- // @ts-expect-error
1904
- record.isDestroyed = true;
1905
- }
1906
- record[Context].store.notifications.unsubscribe(record.___notifications);
1907
-
1908
- // FIXME we need a way to also unsubscribe all SchemaObjects when the primary
1909
- // resource is destroyed.
1910
- }
1911
- function assertNeverField(identifier, field, path) {
1912
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1913
- {
1914
- throw new Error(`Cannot use unknown field kind ${field.kind} on <${identifier.type}>.${Array.isArray(path) ? path.join('.') : path}`);
1915
- }
1916
- })() : {};
1917
- return false;
1918
- }
12
+ import { Type } from './types/symbols.js';
1919
13
  function instantiateRecord(store, identifier, createArgs) {
1920
14
  const schema = store.schema;
1921
15
  const resourceSchema = schema.resource(identifier);
@@ -1925,7 +19,7 @@ function instantiateRecord(store, identifier, createArgs) {
1925
19
  }
1926
20
  })(isResourceSchema(resourceSchema)) : {};
1927
21
  const legacy = resourceSchema?.legacy ?? false;
1928
- const editable = legacy || store.cache.isNew(identifier);
22
+ const editable = legacy;
1929
23
  const record = new ReactiveResource({
1930
24
  store,
1931
25
  resourceKey: identifier,
@@ -1936,7 +30,7 @@ function instantiateRecord(store, identifier, createArgs) {
1936
30
  field: null,
1937
31
  value: null
1938
32
  });
1939
- if (createArgs) {
33
+ if (createArgs && editable) {
1940
34
  Object.assign(record, createArgs);
1941
35
  }
1942
36
  return record;
@@ -2678,4 +772,4 @@ function mergeMap(base, toApply) {
2678
772
  base.set(key, value);
2679
773
  }
2680
774
  }
2681
- export { Checkout, SchemaService, fromIdentity, instantiateRecord, registerDerivations, teardownRecord, withDefaults };
775
+ export { SchemaService, fromIdentity, instantiateRecord, registerDerivations, teardownRecord, withDefaults };