@warp-drive/core 5.9.0-beta.2 → 5.9.0
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/{-private-zrP4VGAf.js → -private-C4L-6BFr.js} +3 -3
- package/dist/{-private-zrP4VGAf.js.map → -private-C4L-6BFr.js.map} +1 -1
- package/dist/{-private-CyhhcK1a.js → -private-DJ3g9bNk.js} +2 -2
- package/dist/{-private-CyhhcK1a.js.map → -private-DJ3g9bNk.js.map} +1 -1
- package/dist/{-private-BYn1Vh-L.js → -private-r5p8QUr4.js} +2 -2
- package/dist/{-private-BYn1Vh-L.js.map → -private-r5p8QUr4.js.map} +1 -1
- package/dist/configure.js +1 -1
- package/dist/graph/-private.js +1 -1
- package/dist/index.js +1 -1
- package/dist/reactive/-private.js +1 -1
- package/dist/reactive.js +3 -3
- package/dist/{request-7BJFgSu_.js → request-DZVW74wn.js} +2 -2
- package/dist/{request-7BJFgSu_.js.map → request-DZVW74wn.js.map} +1 -1
- package/dist/request.js +1 -1
- package/dist/signals/-leaked.js +1 -1
- package/dist/{src-BOAWJH_S.js → src-CsvKpo_j.js} +5 -5
- package/dist/{src-BOAWJH_S.js.map → src-CsvKpo_j.js.map} +1 -1
- package/dist/store/-private.js +1 -1
- package/dist/types/-private.js +1 -1
- package/dist/types/request.js +1 -1
- package/dist/types/runtime.js +1 -1
- package/dist/types/symbols.js +1 -1
- package/dist/unpkg/dev/{-private-CUkeqUhO.js → -private-CbWd-ZyQ.js} +2 -2
- package/dist/unpkg/{prod/-private-B36B1ztP.js.map → dev/-private-CbWd-ZyQ.js.map} +1 -1
- package/dist/unpkg/dev/{-private-D6Tw25AD.js → -private-DKli7-dV.js} +2 -2
- package/dist/unpkg/dev/{-private-D6Tw25AD.js.map → -private-DKli7-dV.js.map} +1 -1
- package/dist/unpkg/dev/{-private-BoSTJwp9.js → -private-FcLmzpRX.js} +3 -3
- package/dist/unpkg/{dev-deprecated/-private-BoSTJwp9.js.map → dev/-private-FcLmzpRX.js.map} +1 -1
- package/dist/unpkg/dev/configure.js +1 -1
- package/dist/unpkg/dev/graph/-private.js +1 -1
- package/dist/unpkg/dev/index.js +1 -1
- package/dist/unpkg/dev/reactive/-private.js +1 -1
- package/dist/unpkg/dev/reactive.js +3 -3
- package/dist/unpkg/dev/{request-CwjpJB3r.js → request-sIfZjSrT.js} +2 -2
- package/dist/unpkg/dev/{request-CwjpJB3r.js.map → request-sIfZjSrT.js.map} +1 -1
- package/dist/unpkg/dev/request.js +1 -1
- package/dist/unpkg/dev/signals/-leaked.js +1 -1
- package/dist/unpkg/dev/{src-CP6e_ozt.js → src-CIPYMS1G.js} +5 -5
- package/dist/unpkg/dev/{src-CP6e_ozt.js.map → src-CIPYMS1G.js.map} +1 -1
- package/dist/unpkg/dev/store/-private.js +1 -1
- package/dist/unpkg/dev/types/-private.js +1 -1
- package/dist/unpkg/dev/types/request.js +1 -1
- package/dist/unpkg/dev/types/runtime.js +1 -1
- package/dist/unpkg/dev/types/symbols.js +1 -1
- package/dist/unpkg/dev-deprecated/{-private-CUkeqUhO.js → -private-CbWd-ZyQ.js} +2 -2
- package/dist/unpkg/dev-deprecated/{-private-CUkeqUhO.js.map → -private-CbWd-ZyQ.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/{-private-D6Tw25AD.js → -private-DKli7-dV.js} +2 -2
- package/dist/unpkg/dev-deprecated/{-private-D6Tw25AD.js.map → -private-DKli7-dV.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/{-private-BoSTJwp9.js → -private-FcLmzpRX.js} +3 -3
- package/dist/unpkg/{dev/-private-BoSTJwp9.js.map → dev-deprecated/-private-FcLmzpRX.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/configure.js +1 -1
- package/dist/unpkg/dev-deprecated/graph/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/index.js +1 -1
- package/dist/unpkg/dev-deprecated/reactive/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/reactive.js +3 -3
- package/dist/unpkg/dev-deprecated/{request-CwjpJB3r.js → request-sIfZjSrT.js} +2 -2
- package/dist/unpkg/dev-deprecated/{request-CwjpJB3r.js.map → request-sIfZjSrT.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/request.js +1 -1
- package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -1
- package/dist/unpkg/dev-deprecated/{src-De8OV58h.js → src-BW5t6nJR.js} +5 -5
- package/dist/unpkg/dev-deprecated/{src-De8OV58h.js.map → src-BW5t6nJR.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/store/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/types/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/types/request.js +1 -1
- package/dist/unpkg/dev-deprecated/types/runtime.js +1 -1
- package/dist/unpkg/dev-deprecated/types/symbols.js +1 -1
- package/dist/unpkg/{prod-deprecated/-private-Dhl123OI.js → prod/-private-BPbQ_hud.js} +2 -2
- package/dist/unpkg/prod/{-private-Dhl123OI.js.map → -private-BPbQ_hud.js.map} +1 -1
- package/dist/unpkg/{prod-deprecated/-private-DHco-h0q.js → prod/-private-D4leSvXQ.js} +3 -3
- package/dist/unpkg/{prod-deprecated/-private-DHco-h0q.js.map → prod/-private-D4leSvXQ.js.map} +1 -1
- package/dist/unpkg/prod/-private-DXAng78m.js +22 -0
- package/dist/unpkg/{prod-deprecated/-private-B36B1ztP.js.map → prod/-private-DXAng78m.js.map} +1 -1
- package/dist/unpkg/prod/configure.js +1 -1
- package/dist/unpkg/prod/graph/-private.js +1 -1
- package/dist/unpkg/prod/index.js +1 -1
- package/dist/unpkg/prod/reactive/-private.js +1 -1
- package/dist/unpkg/prod/reactive.js +3 -3
- package/dist/unpkg/{prod-deprecated/request-BBdC1Sz7.js → prod/request-BkQ1-Ihx.js} +2 -2
- package/dist/unpkg/{prod-deprecated/request-BBdC1Sz7.js.map → prod/request-BkQ1-Ihx.js.map} +1 -1
- package/dist/unpkg/prod/request.js +1 -1
- package/dist/unpkg/prod/signals/-leaked.js +1 -1
- package/dist/unpkg/prod/{src-nFHlZgKa.js → src-EVyOB2IR.js} +5 -5
- package/dist/unpkg/prod/{src-nFHlZgKa.js.map → src-EVyOB2IR.js.map} +1 -1
- package/dist/unpkg/prod/store/-private.js +1 -1
- package/dist/unpkg/prod/types/-private.js +1 -1
- package/dist/unpkg/prod/types/request.js +1 -1
- package/dist/unpkg/prod/types/runtime.js +1 -1
- package/dist/unpkg/prod/types/symbols.js +1 -1
- package/dist/unpkg/{prod/-private-Dhl123OI.js → prod-deprecated/-private-BPbQ_hud.js} +2 -2
- package/dist/unpkg/prod-deprecated/{-private-Dhl123OI.js.map → -private-BPbQ_hud.js.map} +1 -1
- package/dist/unpkg/{prod/-private-DHco-h0q.js → prod-deprecated/-private-D4leSvXQ.js} +3 -3
- package/dist/unpkg/{prod/-private-DHco-h0q.js.map → prod-deprecated/-private-D4leSvXQ.js.map} +1 -1
- package/dist/unpkg/prod-deprecated/{-private-B36B1ztP.js → -private-DXAng78m.js} +2 -2
- package/dist/unpkg/{dev/-private-CUkeqUhO.js.map → prod-deprecated/-private-DXAng78m.js.map} +1 -1
- package/dist/unpkg/prod-deprecated/configure.js +1 -1
- package/dist/unpkg/prod-deprecated/graph/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/index.js +1 -1
- package/dist/unpkg/prod-deprecated/reactive/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/reactive.js +3 -3
- package/dist/unpkg/{prod/request-BBdC1Sz7.js → prod-deprecated/request-BkQ1-Ihx.js} +2 -2
- package/dist/unpkg/{prod/request-BBdC1Sz7.js.map → prod-deprecated/request-BkQ1-Ihx.js.map} +1 -1
- package/dist/unpkg/prod-deprecated/request.js +1 -1
- package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -1
- package/dist/unpkg/prod-deprecated/{src-Cku5ymUJ.js → src-Bankvkbq.js} +5 -5
- package/dist/unpkg/prod-deprecated/{src-Cku5ymUJ.js.map → src-Bankvkbq.js.map} +1 -1
- package/dist/unpkg/prod-deprecated/store/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/types/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/types/request.js +1 -1
- package/dist/unpkg/prod-deprecated/types/runtime.js +1 -1
- package/dist/unpkg/prod-deprecated/types/symbols.js +1 -1
- package/package.json +3 -3
- package/dist/unpkg/prod/-private-B36B1ztP.js +0 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src-De8OV58h.js","names":["withBrand","defineGate","notifyInternalSignal","peekInternalSignal","withSignalStore","Destroy","urlFromLink","link","href","upgradeThis","doc","ReactiveDocumentProto","_request","options","url","method","links","Object","assign","response","_store","request","content","fetch","test","Error","related","self","cacheOptions","key","identifier","lid","next","prev","first","last","toJSON","data","undefined","errors","meta","_subscription","notifications","unsubscribe","get","document","_localCache","cache","peek","Array","isArray","recordArrayManager","getCollection","source","slice","requestKey","peekRecord","createReactiveDocument","store","cacheKey","localCache","create","signals","subscribe","_key","type","TEXT_COLORS","TEXT","notify","graph","request","cache","BG_COLORS","NOTIFY_BORDER","LIGHT_DARK_ALT","lightgreen","green","badge","isLight","color","bgColor","border","correctColor","colorForBucket","scope","bucket","logGroup","prefix","subScop1","subScop2","subScop3","subScop4","console","groupCollapsed","_log","log","isLightMode","window","matchMedia","matches","scopePath","path","coerceId","id","normalized","undefined","String","console","warn","JSON","stringify","test","Error","length","ensureStringId","isNaN","dasherize","normalizeModelName","type","result","console","warn","getOrSetGlobal","peekTransient","setTransient","CACHE_OWNER","DEBUG_CLIENT_ORIGINATED","DEBUG_KEY_TYPE","DEBUG_STALE_CACHE_OWNER","hasId","hasLid","hasType","coerceId","normalizeModelName","installPolyfill","getGlobalConfig","getGlobalConfig0","isResourceKey","identifier","type","undefined","isRequestKey","isFastBoot","FastBoot","_crypto","require","globalThis","crypto","uuidv4","test","Error","randomUUID","freeze","obj","Object","setIdentifierGenerationMethod","method","setIdentifierUpdateMethod","setIdentifierForgetMethod","setIdentifierResetMethod","setKeyInfoForResource","assertIsRequest","request","NEW_IDENTIFIERS","Map","IDENTIFIER_CACHE_ID","updateTypeIdMapping","typeMap","id","idMap","get","set","lid","defaultUpdateMethod","data","bucket","defaultKeyInfoMethod","resource","known","defaultGenerationMethod","url","toUpperCase","defaultEmptyCallback","args","defaultMergeMethod","a","_b","_c","DEBUG_MAP","WeakMap","CacheKeyManager","_cache","constructor","_generate","_update","_forget","_reset","_merge","_keyInfoForResource","_id","resources","resourcesByType","create","documents","polymorphicLidBackMap","__configureMerge","upgradeIdentifier","_getRecordIdentifier","shouldGenerate","WarpDrive","debug","LOG_IDENTIFIERS","getWarpDriveRuntimeConfig","console","groupCollapsed","has","JSON","stringify","log","groupEnd","getIdentifierFromLid","makeResourceKey","keyInfo","addResourceToCache","peekResourceKey","peekRequestKey","cacheKey","cacheOptions","key","getOrCreateDocumentIdentifier","getOrCreateRecordIdentifier","createIdentifierForNewRecord","newLid","String","updateRecordIdentifier","identifierObject","existingIdentifier","detectMerge","hadLid","generatedIdentifier","_mergeRecordIdentifiers","performRecordIdentifierUpdate","newId","typeSet","delete","kept","abandoned","abandonedBackReferences","forgetRecordIdentifier","keptBackReferences","push","forEach","backReferences","destroy","clear","recordIdentifier","clientOriginated","wrapper","proto","value","defineProperty","enumerable","setPrototypeOf","updateFn","warn","cache","newType","newTypeSet","isRequestKey","isResourceKey","CacheCapabilitiesManager","constructor","_store","_willNotify","_pendingNotifies","Map","cacheKeyManager","identifierCache","_scheduleNotification","identifier","key","channel","pending","get","set","channels","Set","add","_cbs","_schedule","_flushNotifications","forEach","channelsByKey","keysByChannel","keys","notifications","notify","notifyChange","namespace","test","Error","schema","setRecordId","id","_instanceCache","hasRecord","Boolean","peek","disconnectRecord","disconnect","delete","prototype","getSchemaDefinitionService","assertPrivateCapabilities","manager","createReactiveDocument","_CHECKOUT","ReactiveResource","getOrSetGlobal","log","logGroup","CacheCapabilitiesManager","getGlobalConfig","getGlobalConfig0","isDestroyable","record","Boolean","destroy","RecordCache","Map","peekResourceKey","get","recordIdentifierFor","test","Error","String","has","setRecordIdentifier","identifier","set","removeRecordIdentifier","delete","StoreMap","storeFor","ignoreMissing","store","InstanceCache","constructor","__instances","document","_storeWrapper","cacheKeyManager","__configureMerge","matchedIdentifier","resourceData","keptIdentifier","id","type","staleIdentifier","keptHasRecord","staleHasRecord","lid","cache","patch","op","value","unloadRecord","peek","getDocument","doc","getRecord","_createRecord","recordIsLoaded","filterDeleted","isNew","isEmpty","isDeleted","isDeletionCommitted","disconnect","isDestroyed","isDestroying","_graph","remove","forgetRecordIdentifier","_requestCache","_clearEntries","WarpDrive","debug","LOG_INSTANCE_CACHE","globalThis","getWarpDriveRuntimeConfig","requests","getRequestStateService","getPendingRequestsForRecord","some","req","console","groupCollapsed","_join","clear","_cache","undefined","resources","forEach","typeCache","resourcesByType","identifiers","setRecordId","oldId","warn","existingIdentifier","updateRecordIdentifier","notifications","notify","getNewRecord","instances","properties","schema","resource","legacy","editable","Object","assign","instantiateRecord","groupEnd","_clearCaches","teardownRecord","willSyncFlushWatchers","getOrSetGlobal","log","isRequestKey","isResourceKey","getGlobalConfig","getGlobalConfig0","isCacheOperationValue","value","UnscopedChannel","Symbol","keyToString","key","Set","Array","from","join","mergeIntoBuffer","buffer","channel","set","existing","get","undefined","channels","Map","channelsForKey","values","ch","add","map","keys","k","shouldDeliverToChannel","subscriberChannel","has","count","label","globalThis","__WarpDriveMetricCountData","asInternalToken","token","test","Error","_unsubscribe","cache","cacheKey","for","WarpDrive","debug","LOG_NOTIFICATIONS","getWarpDriveRuntimeConfig","console","callbacks","index","indexOf","splice","NotificationManager","constructor","store","isDestroyed","_buffered","_hasFlush","_cache","subscribe","callback","includes","push","unsubscribe","notify","String","_hasSubscribers","hasSubscribers","LOG_METRIC_COUNTS","type","_scheduleNotify","lid","_onNextFlush","cb","_onFlushCB","asyncFlush","_enableAsyncFlush","_flush","buffered","size","states","bucket","_flushNotification","destroy","clear","callbackMap","forEach","length","hasSubscriber","Boolean","Context","upgradeThis","obj","update","isUpdating","_updatingPromise","updatingPromise","_update","finally","isDestroying","isDestroyed","save","context","promise","Promise","all","map","record","store","saveRecord","then","ARRAY_GETTER_METHODS","Set","Symbol","iterator","ARRAY_SETTER_METHODS","isArrayGetter","prop","has","isArraySetter","convertToInt","num","Number","isNaN","safeForEach","instance","arr","callback","target","undefined","slice","test","Error","length","index","call","_instanceCache","getRecord","consumeInternalSignal","getOrCreateInternalSignal","expectNever","value","isExtensionProp","extensions","prop","Boolean","has","performObjectExtensionGet","receiver","signals","desc","get","kind","fn","signal","call","test","Error","String","undefined","performExtensionSet","set","performArrayExtensionGet","_SIGNAL","boundFns","transaction","result","Reflect","apply","arguments","NativeProxy","Proxy","Context","isExtensionProp","performArrayExtensionGet","performExtensionSet","ARRAY_SIGNAL","consumeInternalSignal","createInternalSignal","createSignalDescriptor","notifyInternalSignal","Signals","withSignalStore","getOrSetGlobal","recordIdentifierFor","isResourceKey","convertToInt","isArrayGetter","isArraySetter","safeForEach","NativeProxy","IS_COLLECTION","Symbol","for","isContextProp","prop","MUTABLE_PROPS","ARR_BRACKET_DESC","enumerable","configurable","get","IS_UPDATING_DESC","ArrayHandler","getOwnPropertyDescriptor","target","underlying","Reflect","Object","defineProperty","receiver","CONTEXT","signals","index","signal","isStale","data","manager","_syncArray","identifier","transaction","store","_instanceCache","getRecord","length","call","fn","boundFns","undefined","result","arguments","apply","set","editable","test","Error","String","args","Array","prototype","slice","mutate","features","outcome","extensions","v","value","includes","original","newIdentifier","extractIdentifierFromRecord","deleteProperty","getPrototypeOf","ILLEGAL_MUTATION","createReactiveResourceArray","options","TARGET","source","context","destroy","isDestroying","isDestroyed","Map","proxy","record","clear","createRequestCollection","config","createRelatedCollection","Context","save","update","createReactiveResourceArray","createLegacyLiveArray","options","store","manager","editable","source","data","features","modelName","type","_update","_updateLiveArray","DEPRECATED_CLASS_NAME","isUpdating","isLoaded","_updatingPromise","extensions","destroy","mutate","upgradeThis","obj","context","test","Error","findAll","reload","Context","save","update","createReactiveResourceArray","destroy","createLegacyQueryArray","options","store","manager","editable","source","data","links","meta","features","query","modelName","type","_update","_updateCollection","DEPRECATED_CLASS_NAME","isUpdating","isLoaded","_updatingPromise","extensions","destroyCollection","mutate","context","test","Error","promise","_recordArray","upgradeManager","obj","clear","call","_managed","delete","_pending","Context","notifyInternalSignal","getOrSetGlobal","createLegacyLiveArray","createLegacyQueryArray","createRequestCollection","FAKE_ARR","SLICE_BATCH_SIZE","fastPush","target","source","batch","length","splice","push","RecordArrayManager","constructor","options","store","isDestroying","isDestroyed","_live","Map","_managed","Set","_pending","_staged","_keyedArrays","_identifiers","_set","_visibilitySet","_documentSubscription","notifications","subscribe","identifier","type","has","lid","array","get","dirtyArray","_subscribeToResourceChanges","_subscription","schema","resource","legacy","cache","isNew","set","identifierAdded","identifierRemoved","identifierChanged","_syncArray","pending","isLegacyQuery","isLegacyQueryArray","sync","delete","isLegacyLiveArray","context","signal","requestKey","value","doc","peek","test","Error","data","Array","isArray","populateManagedArray","mutate","mutation","liveArrayFor","identifiers","staged","forEach","key","manager","getCollection","config","associate","query","isLoaded","links","meta","add","delta","shouldSyncFromCache","isStale","_getPendingFor","includeManaged","isRemove","liveArray","allPending","managed","arr","changes","pendingLive","size","payload","old","slice","disassociate","changeSets","existing","newState","_instanceCache","recordIsLoaded","pause","unsubscribe","resume","clear","isClear","values","destroy","ArraysCache","i","disassociateIdentifier","arraySet","state","adds","removes","index","indexOf","features","DEPRECATED_CLASS_NAME","getOrSetGlobal","Touching","Symbol","RequestPromise","EMPTY_ARR","Object","freeze","hasRecordIdentifier","op","RequestStateService","_pending","Map","_done","_subscriptions","_toFlush","_store","constructor","store","_clearEntries","identifier","delete","_enqueue","promise","queryRequest","query","data","recordIdentifier","type","has","set","request","state","get","push","_triggerSubscriptions","then","result","_dequeue","finalizedRequest","response","_addDone","error","test","Error","req","_flushRequest","length","notifications","_onNextFlush","_flush","forEach","subscriptions","callback","pending","filter","requestDataOp","requests","Array","isArray","subscribeForRecord","getPendingRequestsForRecord","getLastRequestForRecord","ReactiveResource","EnableHydration","getRuntimeConfig","setLogging","getNewRecord","InstanceCache","peekResourceKey","recordIdentifierFor","storeFor","CacheKeyManager","CacheManager","NotificationManager","RecordArrayManager","RequestPromise","RequestStateService","coerceId","ensureStringId","normalizeModelName","getGlobalConfig","getGlobalConfig0","esc","_importSync20","globalThis","setWarpDriveLogging","getWarpDriveRuntimeConfig","WarpDrive","debug","LOG_METRIC_COUNTS","__WarpDriveMetricCountData","getWarpDriveMetricCounts","structuredClone","resetWarpDriveMetricCounts","__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS","__primitiveInstanceId","interceptAndLog","klassName","methodName","klass","instantiationLabel","constructor","args","instanceId","instanceName","Error","stack","split","original","prototype","logName","instanceLogName","apply","upgradeStore","store","EmptyClass","_BaseClass","BaseClass","default","console","warn","Store","schema","_schema","createSchemaService","isDestroying","_isDestroying","value","isDestroyed","_isDestroyed","identifierCache","cacheKeyManager","createArgs","Object","assign","notifications","recordArrayManager","_requestCache","_instanceCache","_run","cb","test","_cbs","coalesce","sync","notify","_join","_schedule","name","getRequestStateService","_getAllPending","all","pending","_pending","forEach","requests","push","map","v","requestManager","promise","Promise","allSettled","length","request","requestConfig","opts","records","r","getOrCreateRecordIdentifier","DISABLE_WAITER","disableTestWaiter","LOG_REQUESTS","options","JSON","parse","stringify","log","op","url","method","future","onFinalize","_flush","createRecord","type","inputProperties","context","assertDestroyingStore","record","normalizedModelName","properties","id","undefined","adapter","adapterFor","generateIdForRecord","resource","identifier","String","lid","createIdentifierForNewRecord","cache","createOptions","normalizeProperties","resultProps","clientDidCreate","deleteRecord","setIsDeleted","isNew","unloadRecord","peekRecord","arguments","isMaybeIdentifier","stableIdentifier","isLoaded","recordIsLoaded","getRecord","normalizedId","peekAll","liveArrayFor","unloadAll","assertDestroyedStoreOnly","assertPrivateStore","_enableAsyncFlush","pause","_graph","identifiers","clear","resume","data","pushed","_push","Array","isArray","jsonApiDoc","asyncFlush","ret","put","content","createCache","_storeWrapper","destroy","create","isPrivateStore","getSchemaDefinitionService","registerSchemaDefinitionService","registerSchema","maybeIdentifier","Boolean","defs","fields","size","keys","i","prop","field","get","kind","assertRecordsPassedToHasMany","extractIdentifiersFromRecords","extractIdentifierFromRecord","join","every","recordOrPromiseRecord","extract","ensureStringId","recordIdentifierFor","defineSignal","getOrSetGlobal","preloadData","store","identifier","preload","jsonPayload","schemas","schema","fields","Object","keys","forEach","key","preloadValue","field","get","kind","relationships","preloadRelationship","attributes","cache","hasRecord","Boolean","_instanceCache","peek","upsert","relatedType","type","test","Error","Array","isArray","data","map","value","_convertPreloadRelationshipToJSON","id","_resourceIsFullDeleted","isDeletionCommitted","isNew","isDeleted","resourceIsFullyDeleted","instanceCache","RecordReference","___token","___identifier","constructor","notifications","subscribe","_","bucket","notifiedKey","_ref","destroy","unsubscribe","remoteType","push","objectOrPromise","Promise","resolve","then","peekRecord","load","findRecord","reload","prototype","AvailableShims","WeakMap","getShimClass","modelName","shims","create","set","shim","undefined","ShimModelClass","__store","Map","fieldSchemas","attrs","relationshipsByName","rels","eachAttribute","callback","binding","call","eachRelationship","eachTransformedAttribute","constructResource","ensureStringId","recordIdentifierFor","storeFor","isMaybeIdentifier","Store","normalizeModelName","SkipCache","getShimClass","preloadData","RecordReference","resourceIsFullyDeleted","prototype","findRecord","resource","id","options","console","warn","test","Error","isDestroying","isDestroyed","type","normalizedId","identifier","cacheKeyManager","getOrCreateRecordIdentifier","preload","_instanceCache","recordIsLoaded","reload","_join","promise","request","op","data","record","cacheOptions","then","document","content","findAll","query","queryRecord","getReference","resourceIdentifier","arguments","length","cache","upgradeInstanceCaches","__instances","reference","get","set","modelFor","schema","hasResource","saveRecord","Promise","reject","lid","resolve","operation","isNew","isDeleted","records","withReferences","WeakMap","MUTATION_OPS","createReactiveDocument","EnableHydration","SkipCache","log","calcShouldBackgroundFetch","calcShouldFetch","cloneError","getPriority","isCacheAffecting","isMutation","getGlobalConfig","getGlobalConfig0","CacheHandler","request","context","next","store","cacheOptions","identifier","cacheKeyManager","getOrCreateDocumentIdentifier","setIdentifier","DEDUPE","requestManager","_deduped","activeRequest","get","peeked","cache","peekRequest","priority","blocking","WarpDrive","debug","LOG_REQUESTS","globalThis","getWarpDriveRuntimeConfig","lid","promise","url","op","fetchContentAndHydrate","finally","delete","notifications","notify","set","queueMicrotask","_pending","id","test","Error","shouldHydrate","setResponse","response","content","maybeUpdateUiObjects","newError","result","options","document","_instanceCache","getDocument","updateCacheForSuccess","Array","isArray","records","didCommit","data","record","put","handleFetchSuccess","_enableAsyncFlush","_join","lifetimes","didRequest","finalPriority","_flush","updateCacheForError","error","errors","undefined","commitWasRejected","handleFetchError","signal","aborted","isMut","forEach","willCommit","willRequest","then","_requestCache","_enqueue","recordIdentifier","isResourceKey","coerceId","isNonEmptyString","constructResource","type","id","lid","resource","test","Error","trueId","Context","notifyInternalSignal","recordIdentifierFor","isResourceKey","save","createReactiveResourceArray","destroy","createLegacyManyArray","options","extensions","store","schema","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","field","manager","editable","source","data","links","meta","features","modelName","type","DEPRECATED_CLASS_NAME","isLoaded","isAsync","isPolymorphic","identifier","key","name","reload","createRecord","notify","destroyLegacyManyArray","mutate","_MUTATE","target","receiver","prop","args","_SIGNAL","collection","Reflect","set","mutateReplaceRelatedRecords","index","prior","value","mutateReplaceRelatedRecord","newValues","extractIdentifiersFromRecords","assertNoDuplicates","currentState","push","seen","Set","unique","forEach","item","has","add","newArgs","Array","from","result","apply","length","mutateAddToRelatedRecords","mutateRemoveFromRelatedRecords","unshift","mutateSortRelatedRecords","map","start","_deleteCount","adds","deleteCount","Infinity","Math","min","splice","current","concat","slice","test","Error","signal","reloadHasMany","hash","record","call","assertRecordPassedToHasMany","records","extractIdentifierFromRecord","recordOrPromiseRecord","callback","reason","state","size","duplicates","filter","currentValue","currentIndex","indexOf","console","warn","id","lid","r","sort","a","b","localeCompare","join","operationInfo","op","mutation","getAliasField","context","test","Error","setAliasField","ARRAY_SIGNAL","consumeInternalSignal","entangleSignal","withSignalStore","ReactiveResource","Context","Destroy","SOURCE","isExtensionProp","performArrayExtensionGet","performExtensionSet","ARRAY_GETTER_METHODS","Set","Symbol","iterator","SYNC_PROPS","isArrayGetter","prop","has","ARRAY_SETTER_METHODS","isArraySetter","convertToInt","num","Number","isNaN","safeForEach","instance","arr","store","callback","target","undefined","slice","test","Error","length","index","call","ManagedArray","constructor","context","owner","data","self","IS_EDITABLE","editable","schema","cache","field","signals","_SIGNAL","boundFns","Map","identifier","resourceKey","path","transaction","KeyMode","options","key","RefStorage","WeakMap","ManagedRecordRefs","kind","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","proxy","Proxy","get","receiver","isStale","newData","getAttr","push","rawValue","type","transform","transformation","hydrate","objectType","polymorphic","typePath","hashFn","schemaObjectKeyValue","hashField","resource","identity","name","isPathKeyMode","modeField","fields","recordRef","record","value","deref","Promise","resolve","then","recordPath","objectContext","modeName","schemaObject","set","WeakRef","fn","result","arguments","Reflect","apply","String","v","errorPath","reflect","setAttr","map","item","serialize","desc","enumerable","configurable","Object","defineProperty","prototype","ARRAY_SIGNAL","entangleSignal","peekInternalSignal","ManagedArray","getArrayField","context","signal","signals","record","path","at","managedArray","value","isStale","store","resourceKey","field","cache","rawValue","getAttr","options","defaultValue","editable","getRemoteAttr","setArrayField","schema","fieldSignal","peeked","transform","type","transformation","map","item","serialize","slice","setAttr","test","Error","kind","arrSignal","Array","isArray","InvalidKinds","isInvalidKind","kind","includes","isNonIdentityCacheableField","field","getFieldCacheKeyStrict","sourceKey","name","getFieldCacheKey","assertIsCacheField","test","Error","cacheKeyFor","entangleSignal","getFieldCacheKeyStrict","getBelongsToField","context","signals","record","path","at","field","resourceKey","store","schema","cache","options","linksMode","rawValue","editable","getRelationship","getRemoteRelationship","data","peekRecord","test","Error","legacy","_kind","get","setBelongsToField","isValidPolarisConfig","async","name","mutate","op","value","getResourceKey","set","entangleSignal","getCollectionField","context","signals","record","path","at","test","Error","setCollectionField","getDerivedField","context","schema","store","derivation","field","record","options","name","setDerivedField","test","Error","path","join","resourceKey","type","kind","fastPush","EnableHydration","Context","ManyArrayManager","constructor","record","editable","context","store","identifier","resourceKey","_syncArray","array","method","rawValue","cache","key","meta","links","currentState","source","data","undefined","length","reloadHasMany","options","field","schema","fields","get","test","Error","kind","cacheOptions","extractCacheOptions","reload","types","type","getRelationship","req","url","getRelatedLink","op","records","request","mutate","mutation","resource","related","href","backgroundReload","entangleSignal","createLegacyManyArray","getFieldCacheKeyStrict","ManyArrayManager","getHasManyField","context","signal","signals","record","path","at","store","field","options","linksMode","cached","value","editable","resourceKey","cache","rawValue","getRelationship","getRemoteRelationship","managedArray","manager","source","data","slice","type","isLoaded","isAsync","async","isPolymorphic","polymorphic","identifier","links","meta","test","Error","legacy","schema","_kind","get","setHasManyField","Array","isArray","set","getHashField","context","field","path","resourceKey","schema","cache","store","test","Error","kind","Array","isArray","length","realPath","slice","rawData","editable","getAttr","getRemoteAttr","hashFn","options","name","setHashField","join","type","entangleSignal","getIdentityField","context","signals","record","resourceKey","id","setIdentityField","value","store","test","Error","length","normalizedId","String","didChange","type","_instanceCache","setRecordId","notifications","notify","consumeInternalSignal","entangleSignal","notifyInternalSignal","OBJECT_SIGNAL","withSignalStore","getOrSetGlobal","Context","SOURCE","isExtensionProp","performExtensionSet","performObjectExtensionGet","notifyObject","obj","ObjectSymbols","Set","ManagedObject","constructor","context","field","path","self","Object","assign","value","signals","_SIGNAL","undefined","identifier","resourceKey","cache","schema","store","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_objectExtensions","proxy","Proxy","ownKeys","keys","has","target","prop","getOwnPropertyDescriptor","writable","editable","enumerable","configurable","get","receiver","Symbol","toPrimitive","toStringTag","type","id","lid","isStale","newData","getAttr","transform","transformation","hydrate","options","record","structuredClone","Reflect","set","test","Error","String","reflect","setAttr","val","serialize","ManagedObjectMap","Map","peekManagedObject","managedObjectMapForRecord","name","defineSignal","entangleSignal","getFieldCacheKeyStrict","Context","ResourceRelationship","constructor","context","store","resourceKey","cache","name","field","rawValue","editable","getRelationship","getRemoteRelationship","lid","links","self","data","peekRecord","Object","freeze","assign","meta","fetch","options","url","getHref","related","Error","method","type","String","request","prototype","link","href","getResourceField","signals","record","path","at","setResourceField","test","ARRAY_SIGNAL","peekInternalSignal","getArrayField","getSchemaArrayField","setSchemaArrayField","context","arrayValue","value","slice","fieldSignal","signals","path","at","peeked","store","cache","setAttr","resourceKey","test","Error","field","kind","arrSignal","isStale","Array","isArray","entangleSignal","ManagedObjectMap","ReactiveResource","Destroy","getSchemaObjectField","context","signal","signals","record","path","at","store","resourceKey","field","cache","rawValue","editable","getAttr","getRemoteAttr","options","polymorphic","defaultValue","value","Promise","resolve","then","schema","objectType","typePath","type","test","Error","hashFn","hashField","resource","identity","name","cachedSchemaObject","schemaObject","modeName","legacy","setSchemaObjectField","newValue","schemaFields","fields","key","Object","keys","has","delete","setAttr","getAliasField","setAliasField","getArrayField","setArrayField","getAttributeField","setAttributeField","getBelongsToField","setBelongsToField","getCollectionField","setCollectionField","getDerivedField","setDerivedField","getGenericField","setGenericField","getHasManyField","setHasManyField","getHashField","setHashField","getIdentityField","setIdentityField","getLocalField","setLocalField","getObjectField","setObjectField","getResourceField","setResourceField","getSchemaArrayField","setSchemaArrayField","getSchemaObjectField","setSchemaObjectField","DefaultMode","get","set","mutable","enumerable","serializable","alias","array","attribute","belongsTo","collection","derived","field","hasMany","object","resource","ARRAY_SIGNAL","entangleSignal","notifyInternalSignal","OBJECT_SIGNAL","Signals","withSignalStore","recordIdentifierFor","setRecordIdentifier","removeRecordIdentifier","STRUCTURED","RecordStore","DefaultMode","isExtensionProp","performExtensionSet","performObjectExtensionGet","getFieldCacheKey","peekManagedObject","Checkout","Commit","Context","Destroy","IgnoredGlobalFields","Set","symbolList","RecordSymbols","isPathMatch","a","b","length","every","v","i","isNonEnumerableProp","prop","Editables","Map","ReactiveResource","constructor","context","resourceKey","isEmbedded","path","schema","store","objectType","value","type","ResourceSchema","resource","identityField","identity","BoundFns","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_objectExtensions","field","CAUTION_MEGA_DANGER_ZONE_resourceExtensions","fields","method","cacheFields","signals","___notifications","notifications","subscribe","_","key","name","kind","signal","get","Array","isArray","console","warn","join","proxy","peeked","test","Error","arrSignal","objSignal","options","linksMode","_kind","notify","async","editable","Proxy","ownKeys","identityKey","keys","from","unshift","has","target","getOwnPropertyDescriptor","schemaForField","String","writable","enumerable","configurable","id","receiver","_DESTROY","Promise","resolve","_CHECKOUT","_COMMIT","maybeField","undefined","Symbol","toStringTag","fn","lid","set","json","toPrimitive","iterator","includes","propArray","slice","fieldCacheKey","push","modeName","record","assertNeverField","Object","defineProperty","data","cache","willCommit","didCommit","editableRecord","isDestroying","isDestroyed","unsubscribe","identifier","checkout","commit","isResourceSchema","ReactiveResource","Destroy","instantiateRecord","store","identifier","createArgs","schema","resourceSchema","resource","test","Error","legacy","editable","record","resourceKey","modeName","path","field","value","Object","assign","assertReactiveResource","teardownRecord","recordIdentifierFor","createInternalMemo","withSignalStore","getOrSetGlobal","isResourceSchema","Type","getFieldCacheKeyStrict","isNonIdentityCacheableField","Context","Support","WeakMap","ConstructorField","type","name","kind","TypeField","options","key","IdentifierField","DefaultIdentityField","_constructor","record","state","get","set","modelName","test","Error","undefined","BannedKeys","processExtension","extension","features","Map","baseFeatures","prototype","Object","getOwnPropertyNames","includes","decl","getOwnPropertyDescriptor","value","fn","writable","getExt","extCache","extName","ext","String","hasObjectSchema","field","pretendIsResourceOrObjectSchema","processExtensions","schema","scenario","resolvedType","objectExtensions","length","_extensions","fieldCache","_cachedFieldExtensionsByField","has","extensions","arrayExtensions","CAUTION_MEGA_DANGER_ZONE_resourceExtensions","baseExtensions","feature","desc","size","withDefaults","identity","fields","unshift","push","fromIdentity","context","identifier","resourceKey","registerDerivations","registerDerivation","comparableAbstractFieldShape","sourceKey","as","async","inverse","polymorphic","linksMode","resetOnRemoteUpdate","assertConsistentAbstractFieldShape","abstractType","fieldName","existing","incoming","existingShape","incomingShape","source","JSON","stringify","makeCachedDerivation","derivation","memoizedDerivation","prop","signals","signal","SchemaService","constructor","_schemas","_transforms","_hashFns","_derivations","_traits","_modes","_abstractImplementerFields","object","array","resourceTypes","Array","from","keys","hasTrait","resourceHasTrait","resource","trait","traits","transformation","hashFn","original","registerResources","schemas","forEach","registerResource","relationships","attributes","abstractImplementations","implementerFields","contribution","ownField","cacheFields","Set","finalized","internalSchema","getCacheFields","_registerAbstractTypeImplementation","implementer","abstractField","existingImplementer","abstractSchema","legacy","existingAbstractField","registerTrait","internalTrait","assign","registerTransformation","CAUTION_MEGA_DANGER_ZONE_registerExtension","CAUTION_MEGA_DANGER_ZONE_objectExtensions","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","CAUTION_MEGA_DANGER_ZONE_hasExtension","_registerMode","mode","kinds","_kind","registerHashFn","finalizeResource","hasResource","attributesDefinitionFor","console","warn","relationshipsDefinitionFor","doesTypeExist","seen","traitName","walkTrait","mergeMap","cacheKey","debugPath","join","ownPath","add","subtrait","id","base","toApply","checkout","instantiateRecord","teardownRecord","SchemaService","withDefaults","fromIdentity","registerDerivations","commit","Checkout","createRequestSubscription","getRequestState","getPromiseState","getRuntimeConfig","cloneResponseProperties","DOMError","_fetch","fetch","args","FastBoot","require","Error","cloneResponse","response","overrides","props","Response","body","Object","assign","withDateHeader","headers","Headers","set","Date","toUTCString","IS_MAYBE_MIRAGE","override","mirage","undefined","Boolean","window","server","pretender","toString","replace","MUTATION_OPS","Set","ERROR_STATUS_CODE_FOR","Map","Fetch","request","context","test","url","e","isDOMException","name","statusText","status","isRequestError","code","isError","ok","op","isMutationOp","has","setResponse","method","text","reader","getReader","decoder","TextDecoder","isStreaming","hasRequestedStream","stream","TransformStream","writer","writable","getWriter","signal","addEventListener","abort","readable","cancel","setStream","done","value","read","ready","close","decode","write","encode","TextEncoder","errorPayload","JSON","parse","errors","Array","isArray","isDict","get","msg","type","error","AggregateError","replaceAll","content","v","waitFor","peekUniversalTransient","setUniversalTransient","EnableHydration","assertValidRequest","upgradePromise","clearRequestResult","getRequestResult","setPromiseResult","executeNextHandler","IS_CACHE_HANDLER","RequestManager","constructor","options","Object","assign","_pending","Map","_deduped","_handlers","useCache","cacheHandler","_hasCacheHandler","Error","isFrozen","unshift","use","newHandlers","handlers","Array","isArray","forEach","handler","index","request","push","freeze","controller","AbortController","requestId","context","response","stream","hasRequestedStream","id","identifier","requester","store","promise","cacheResult","disableTestWaiter","newPromise","finalPromise","then","result","isError","error","create","instantiateRecord","registerDerivations","SchemaService","teardownRecord","Fetch","RequestManager","DefaultCachePolicy","CacheHandler","Store","recordIdentifierFor","getRuntimeConfig","setIsMaybeMirage","setLogging","cacheKeyFor","globalThis","setWarpDriveLogging","getWarpDriveRuntimeConfig","setWarpDriveIsMaybeMirage","storeFor","setIdentifierGenerationMethod","setIdentifierUpdateMethod","setIdentifierForgetMethod","setIdentifierResetMethod","setKeyInfoForResource","useRecommendedStore","options","StoreKlass","AppStore","constructor","createArgs","requestManager","Object","defineProperty","configurable","enumerable","get","handlers","use","useCache","set","value","lifetimes","policy","apiCacheHardExpires","apiCacheSoftExpires","constraints","headers","Expires","createSchemaService","schema","schemas","registerResources","traits","trait","registerTrait","derivations","derivation","registerDerivation","transformations","transformation","registerTransformation","hashFns","hashFn","registerHashFn","CAUTION_MEGA_DANGER_ZONE_extensions","extension","CAUTION_MEGA_DANGER_ZONE_registerExtension","createCache","capabilities","cache","key","record"],"sources":["../../../src/reactive/-private/document.ts","../../../src/store/-private/debug/utils.ts","../../../src/store/-private/caches/resource-utils.ts","../../../src/store/-private/utils/coerce-id.ts","../../../src/store/-private/utils/normalize-model-name.ts","../../../src/store/-private/managers/cache-key-manager.ts","../../../src/store/-private/managers/cache-capabilities-manager.ts","../../../src/store/-private/caches/instance-cache.ts","../../../src/store/-private/managers/cache-manager.ts","../../../src/store/-private/managers/notification-manager.ts","../../../src/store/-private/record-arrays/-utils.ts","../../../src/reactive/-private/fields/extension.ts","../../../src/store/-private/record-arrays/native-proxy-type-fix.ts","../../../src/store/-private/record-arrays/resource-array.ts","../../../src/store/-private/record-arrays/legacy-live-array.ts","../../../src/store/-private/record-arrays/legacy-query.ts","../../../src/store/-private/managers/record-array-manager.ts","../../../src/store/-private/network/request-cache.ts","../../../../../node_modules/.pnpm/@embroider+macros@1.20.6/node_modules/@embroider/macros/src/addon/es-compat2.js","../../../src/store/-private/store-service.ts","../../../src/store/deprecated/-private.ts","../../../src/store/deprecated/store.ts","../../../src/store/-private/cache-handler/utils.ts","../../../src/store/-private/cache-handler/handler.ts","../../../src/store/-private/utils/is-non-empty-string.ts","../../../src/store/-private/utils/construct-resource.ts","../../../src/store/-private/record-arrays/legacy-many-array.ts","../../../src/reactive/-private/kind/alias-field.ts","../../../src/reactive/-private/fields/managed-array.ts","../../../src/reactive/-private/kind/array-field.ts","../../../src/reactive/-private/kind/attribute-field.ts","../../../src/reactive/-private/fields/get-field-key.ts","../../../src/reactive/-private/kind/belongs-to-field.ts","../../../src/reactive/-private/kind/collection-field.ts","../../../src/reactive/-private/kind/derived-field.ts","../../../src/reactive/-private/kind/generic-field.ts","../../../src/reactive/-private/fields/many-array-manager.ts","../../../src/reactive/-private/kind/has-many-field.ts","../../../src/reactive/-private/kind/hash-field.ts","../../../src/reactive/-private/kind/identity-field.ts","../../../src/reactive/-private/kind/local-field.ts","../../../src/reactive/-private/fields/managed-object.ts","../../../src/reactive/-private/kind/object-field.ts","../../../src/reactive/-private/kind/resource-field.ts","../../../src/reactive/-private/kind/schema-array-field.ts","../../../src/reactive/-private/kind/schema-object-field.ts","../../../src/reactive/-private/default-mode.ts","../../../src/reactive/-private/record.ts","../../../src/reactive/-private/hooks.ts","../../../src/reactive/-private/schema.ts","../../../src/reactive.ts","../../../src/request/-private/fetch.ts","../../../src/request/-private/manager.ts","../../../src/index.ts"],"sourcesContent":["import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { withBrand } from '../../request.ts';\nimport { defineGate, notifyInternalSignal, peekInternalSignal, withSignalStore } from '../../signals/-private.ts';\nimport type { DocumentCacheOperation, UnsubscribeToken } from '../../store/-private/managers/notification-manager.ts';\nimport type { Store } from '../../store/-private/store-service.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport type { RequestKey } from '../../types/identifier.ts';\nimport type { ImmutableRequestInfo, RequestInfo } from '../../types/request.ts';\nimport type { ResourceDocument } from '../../types/spec/document.ts';\nimport type { Link, Meta, PaginationLinks } from '../../types/spec/json-api-raw.ts';\nimport type { Mutable } from '../../types/utils.ts';\nimport { Destroy } from './symbols.ts';\n\nfunction urlFromLink(link: Link): string {\n if (typeof link === 'string') return link;\n return link.href;\n}\n\nexport interface ReactiveDocumentBase<T> {\n /**\n * The links object for this document, if any\n *\n * e.g.\n *\n * ```ts\n * {\n * self: '/articles?page[number]=3',\n * }\n * ```\n *\n * @public\n */\n readonly links?: PaginationLinks;\n\n /**\n * The meta object for this document, if any\n *\n * @public\n */\n readonly meta?: Meta;\n\n /**\n * The RequestKey associated with this document, if any\n *\n * @public\n */\n readonly identifier: RequestKey | null;\n\n /**\n * Fetches the related link for this document, returning a promise that resolves\n * with the document when the request completes. If no related link is present,\n * will fallback to the self link if present\n *\n * @public\n */\n fetch(options?: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T>>;\n\n /**\n * Fetches the next link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * next link.\n *\n * @public\n */\n next(options?: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the prev link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * prev link.\n *\n * @public\n */\n prev(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the first link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * first link.\n *\n * @public\n */\n first(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the last link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * last link.\n *\n * @public\n */\n last(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Implemented for `JSON.stringify` support.\n *\n * Returns the JSON representation of the document wrapper.\n *\n * This is a shallow serialization, it does not deeply serialize\n * the document's contents, leaving that to the individual record\n * instances to determine how to do, if at all.\n *\n * @public\n * @return\n */\n toJSON(): object;\n}\n\n/**\n * The variant of {@link ReactiveDocument} returned for a request whose\n * response contained no primary data, e.g. an error response.\n *\n * @public\n */\nexport interface ReactiveErrorDocument<T> extends ReactiveDocumentBase<T> {\n /**\n * The primary data for this document, if any.\n *\n * If this document has no primary data (e.g. because it is an error document)\n * this property will be `undefined`.\n *\n * For collections this will be an array of record instances,\n * for single resource requests it will be a single record instance or null.\n *\n * @public\n */\n readonly data?: undefined;\n\n /**\n * The errors returned by the API for this request, if any\n *\n * @public\n */\n readonly errors: object[];\n}\n\n/**\n * The variant of {@link ReactiveDocument} returned for a request whose\n * response contained primary data.\n *\n * @public\n */\nexport interface ReactiveDataDocument<T> extends ReactiveDocumentBase<T> {\n /**\n * The primary data for this document, if any.\n *\n * If this document has no primary data (e.g. because it is an error document)\n * this property will be `undefined`.\n *\n * For collections this will be an array of record instances,\n * for single resource requests it will be a single record instance or null.\n *\n * @public\n */\n readonly data: T;\n\n /**\n * The errors returned by the API for this request, if any\n *\n * @public\n */\n readonly errors?: undefined;\n}\n\ninterface PrivateReactiveDocument {\n /** @internal */\n _store: Store;\n\n /** @internal */\n _localCache: { document: ResourceDocument; request: ImmutableRequestInfo } | null;\n\n /** @internal */\n _subscription: UnsubscribeToken;\n\n _request<T>(\n this: ReactiveDocumentBase<T>,\n link: keyof PaginationLinks,\n options?: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null>;\n}\nfunction upgradeThis(doc: unknown): asserts doc is PrivateReactiveDocument {}\n\n/**\n * A Document is a class that wraps the response content from a request to the API\n * returned by `Cache.put` or `Cache.peek`, converting ResourceKeys into\n * ReactiveResource instances.\n *\n * It is not directly instantiated by the user, and its properties should not\n * be directly modified. Whether individual properties are mutable or not is\n * determined by the record instance itself.\n *\n * @public\n */\nexport type ReactiveDocument<T> = ReactiveDataDocument<T> | ReactiveErrorDocument<T>;\n\nconst ReactiveDocumentProto = {\n async _request<T>(\n this: ReactiveDocumentBase<T>,\n link: keyof PaginationLinks,\n options: RequestInfo<ReactiveDocument<T>> = withBrand<ReactiveDocument<T>>({ url: '', method: 'GET' })\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n const href = this.links?.[link];\n if (!href) {\n return null;\n }\n\n options.method = options.method || 'GET';\n Object.assign(options, { url: urlFromLink(href) });\n const response = await this._store.request<ReactiveDataDocument<T>>(options);\n\n return response.content;\n },\n\n fetch<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDocument<T>> = withBrand<ReactiveDataDocument<T>>({ url: '', method: 'GET' })\n ): Promise<ReactiveDataDocument<T>> {\n upgradeThis(this);\n assert(`No self or related link`, this.links?.related || this.links?.self);\n options.cacheOptions = options.cacheOptions || {};\n options.cacheOptions.key = this.identifier?.lid;\n return this._request(\n this.links.related ? 'related' : 'self',\n options as RequestInfo<ReactiveDataDocument<T>>\n ) as Promise<ReactiveDataDocument<T>>;\n },\n\n next<T>(\n this: ReactiveDocument<T>,\n options?: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('next', options);\n },\n\n prev<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('prev', options);\n },\n\n first<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('first', options);\n },\n\n last<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('last', options);\n },\n\n toJSON<T>(this: ReactiveDocument<T>): object {\n upgradeThis(this);\n const data: Mutable<Partial<ReactiveDocument<T>>> = {};\n data.identifier = this.identifier;\n if (this.data !== undefined) {\n data.data = this.data;\n }\n if (this.links !== undefined) {\n data.links = this.links;\n }\n if (this.errors !== undefined) {\n data.errors = this.errors;\n }\n if (this.meta !== undefined) {\n data.meta = this.meta;\n }\n return data;\n },\n\n [Destroy]<T>(this: ReactiveDocument<T>): void {\n upgradeThis(this);\n assert(`Cannot destroy a ReactiveDocument which has already been destroyed`, this._store);\n if (this._subscription) {\n this._store.notifications.unsubscribe(this._subscription);\n // @ts-expect-error\n this._store = null;\n // @ts-expect-error\n this._subscription = null;\n }\n },\n};\n\ndefineGate(ReactiveDocumentProto, 'errors', {\n get<T>(this: ReactiveDocument<T>): object[] | undefined {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n const { document } = this._localCache!;\n if ('errors' in document) {\n return document.errors;\n }\n return;\n }\n\n const doc = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, doc);\n return 'errors' in doc ? doc.errors : undefined;\n },\n});\ndefineGate(ReactiveDocumentProto, 'data', {\n get<T>(this: ReactiveDocument<T>) {\n upgradeThis(this);\n const { identifier, _localCache } = this;\n\n const doc = identifier ? this._store.cache.peek(identifier) : _localCache!.document;\n assert(`No cache data was found for the document '${identifier?.lid ?? '<uncached document>'}'`, doc);\n const data = 'data' in doc ? (doc.data as T | undefined) : undefined;\n\n if (Array.isArray(data)) {\n return identifier\n ? (this._store.recordArrayManager.getCollection({\n source: data.slice() as ResourceKey[],\n requestKey: identifier,\n }) as T)\n : (this._store.recordArrayManager.getCollection({\n source: data.slice() as ResourceKey[],\n }) as T);\n } else if (data) {\n return this._store.peekRecord(data as unknown as ResourceKey) as T;\n } else {\n return data;\n }\n },\n});\ndefineGate(ReactiveDocumentProto, 'links', {\n get<T>(this: ReactiveDocument<T>) {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n return this._localCache!.document.links;\n }\n const data = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, data);\n return data.links;\n },\n});\ndefineGate(ReactiveDocumentProto, 'meta', {\n get<T>(this: ReactiveDocument<T>): Meta | undefined {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n return this._localCache!.document.meta;\n }\n const data = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, data);\n return data.meta;\n },\n});\n\nexport function createReactiveDocument<T>(\n store: Store,\n cacheKey: RequestKey | null,\n localCache: { document: ResourceDocument; request: ImmutableRequestInfo } | null\n): ReactiveDocument<T> {\n const doc = Object.create(ReactiveDocumentProto) as ReactiveDocument<T> & PrivateReactiveDocument;\n doc._store = store;\n doc._localCache = localCache;\n // @ts-expect-error we are initializing it here\n doc.identifier = cacheKey;\n const signals = withSignalStore(doc);\n\n // TODO if we ever enable auto-cleanup of the cache, we will need to tear this down\n // in a destroy method\n if (cacheKey) {\n doc._subscription = store.notifications.subscribe(cacheKey, (_key: RequestKey, type: DocumentCacheOperation) => {\n switch (type) {\n case 'updated':\n // FIXME in the case of a collection we need to notify it's length\n // and have it recalc\n notifyInternalSignal(peekInternalSignal(signals, 'data'));\n notifyInternalSignal(peekInternalSignal(signals, 'links'));\n notifyInternalSignal(peekInternalSignal(signals, 'meta'));\n notifyInternalSignal(peekInternalSignal(signals, 'errors'));\n break;\n case 'added':\n case 'removed':\n case 'invalidated':\n case 'state':\n break;\n }\n });\n }\n\n return doc;\n}\n","type SCOPE = 'notify' | 'reactive-ui' | 'graph' | 'request' | 'cache';\n\nconst TEXT_COLORS = {\n TEXT: 'inherit',\n notify: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n 'reactive-ui': ['white', 'white', 'inherit', 'magenta', 'inherit'],\n graph: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n request: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n cache: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n};\nconst BG_COLORS = {\n TEXT: 'transparent',\n notify: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n 'reactive-ui': ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n graph: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n request: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n cache: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n};\nconst NOTIFY_BORDER = {\n TEXT: 0,\n notify: [3, 2, 0, 0, 0],\n 'reactive-ui': [3, 2, 0, 0, 0],\n graph: [3, 2, 0, 0, 0],\n request: [3, 2, 0, 0, 0],\n cache: [3, 2, 0, 0, 0],\n};\n\nconst LIGHT_DARK_ALT: Record<string, string> = {\n lightgreen: 'green',\n green: 'lightgreen',\n};\n\nfunction badge(isLight: boolean, color: string, bgColor: string, border: number) {\n return [\n `color: ${correctColor(isLight, color)}; background-color: ${correctColor(isLight, bgColor)}; padding: ${border}px ${2 * border}px; border-radius: ${border}px;`,\n `color: ${TEXT_COLORS.TEXT}; background-color: ${BG_COLORS.TEXT};`,\n ];\n}\n\nfunction colorForBucket(isLight: boolean, scope: SCOPE, bucket: string) {\n if (scope === 'request') {\n return bucket === 'blocking'\n ? badge(isLight, 'red', 'transparent', 0)\n : bucket === 'cached'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'non-blocking'\n ? badge(isLight, 'orange', 'transparent', 0)\n : badge(isLight, 'gray', 'transparent', 0);\n }\n if (scope === 'notify') {\n return bucket === 'added'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'removed'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n if (scope === 'reactive-ui') {\n return bucket === 'created'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'disconnected'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n if (scope === 'cache') {\n return bucket === 'inserted'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'removed'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n\n return badge(isLight, TEXT_COLORS[scope][3], BG_COLORS[scope][3], NOTIFY_BORDER[scope][3]);\n}\n\n/**\n * Opens a collapsed console group for a `cache` scoped debug message, using\n * `type`/`lid`/`bucket`/`key` to build the colorized group label.\n *\n * @private\n */\nexport function logGroup(scope: 'cache', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Opens a collapsed console group for a `reactive-ui` scoped debug message.\n * The trailing `key` segment is unused for this scope and must be an empty string.\n *\n * @private\n */\nexport function logGroup(\n scope: 'reactive-ui',\n prefix: string,\n type: string,\n lid: string,\n bucket: string,\n key: ''\n): void;\n/**\n * Opens a collapsed console group for a `notify` scoped debug message, using\n * `type`/`lid`/`bucket`/`key` to build the colorized group label.\n *\n * @private\n */\nexport function logGroup(scope: 'notify', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Implementation for {@link logGroup}. Builds the colorized label for the\n * given scope via `_log` and opens it as a collapsed `console.groupCollapsed`.\n *\n * @private\n */\nexport function logGroup(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): void {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(..._log(scope, prefix, subScop1, subScop2, subScop3, subScop4));\n}\n\n/**\n * Logs a colorized, scoped debug message to the console for the `request`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the request being logged.\n *\n * @private\n */\nexport function log(scope: 'request', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `cache`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the cache operation being logged.\n *\n * @private\n */\nexport function log(scope: 'cache', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `reactive-ui`\n * scope. The trailing `key` segment is unused for this scope and must be an empty string.\n *\n * @private\n */\nexport function log(scope: 'reactive-ui', prefix: string, type: string, lid: string, bucket: string, key: ''): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `notify`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the notification being logged.\n *\n * @private\n */\nexport function log(scope: 'notify', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Implementation for {@link log}. Builds the colorized message for the given\n * scope via `_log` and writes it to the console with `console.log`.\n *\n * @private\n */\nexport function log(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): void {\n // oxlint-disable-next-line no-console\n console.log(..._log(scope, prefix, subScop1, subScop2, subScop3, subScop4));\n}\n\nfunction correctColor(isLight: boolean, color: string) {\n if (!isLight) {\n return color;\n }\n return color in LIGHT_DARK_ALT ? LIGHT_DARK_ALT[color] : color;\n}\n\nfunction isLightMode() {\n if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {\n return true;\n }\n return false;\n}\n\nfunction _log(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): string[] {\n const isLight = isLightMode();\n switch (scope) {\n case 'request':\n case 'reactive-ui':\n case 'notify': {\n const scopePath = prefix ? `[${prefix}] ${scope}` : scope;\n const path = subScop4 ? `${subScop3}.${subScop4}` : subScop3;\n return [\n `%c@warp%c-%cdrive%c %c${scopePath}%c %c${subScop1}%c %c${subScop2}%c %c${path}%c`,\n ...badge(isLight, 'lightgreen', 'transparent', 0),\n ...badge(isLight, 'magenta', 'transparent', 0),\n ...badge(isLight, TEXT_COLORS[scope][0], BG_COLORS[scope][0], NOTIFY_BORDER[scope][0]),\n ...badge(isLight, TEXT_COLORS[scope][1], BG_COLORS[scope][1], NOTIFY_BORDER[scope][1]),\n ...badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]),\n ...colorForBucket(isLight, scope, path),\n ];\n }\n case 'cache': {\n const scopePath = prefix ? `${scope} (${prefix})` : scope;\n return [\n `%c@warp%c-%cdrive%c %c${scopePath}%c %c${subScop1}%c %c${subScop2}%c %c${subScop3}%c %c${subScop4}%c`,\n ...badge(isLight, 'lightgreen', 'transparent', 0),\n ...badge(isLight, 'magenta', 'transparent', 0),\n ...badge(isLight, TEXT_COLORS[scope][0], BG_COLORS[scope][0], NOTIFY_BORDER[scope][0]),\n ...badge(isLight, TEXT_COLORS[scope][1], BG_COLORS[scope][1], NOTIFY_BORDER[scope][1]),\n ...badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]),\n ...colorForBucket(isLight, scope, subScop3),\n ...badge(isLight, TEXT_COLORS[scope][4], BG_COLORS[scope][4], NOTIFY_BORDER[scope][4]),\n ];\n }\n }\n return [];\n}\n","function isResource(resource: unknown): resource is Record<string, unknown> {\n return Boolean(resource && typeof resource === 'object');\n}\n\nfunction hasProp<T extends string, K extends { [J in T]: string }>(resource: unknown, prop: T): resource is K {\n return Boolean(\n isResource(resource) && prop in resource && typeof resource[prop] === 'string' && resource[prop].length\n );\n}\n\nexport function hasLid(resource: unknown): resource is { lid: string } {\n return hasProp(resource, 'lid');\n}\n\nexport function hasId(resource: unknown): resource is { id: string } {\n return (\n hasProp(resource, 'id') || Boolean(isResource(resource) && 'id' in resource && typeof resource.id === 'number')\n );\n}\n\nexport function hasType(resource: unknown): resource is { type: string } {\n return hasProp(resource, 'type');\n}\n","import { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_NON_STRICT_ID } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\n// Used by the store to normalize IDs entering the store. Despite the fact\n// that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`),\n// it is important that internally we use strings, since IDs may be serialized\n// and lose type information. For example, Ember's router may put a record's\n// ID into the URL, and if we later try to deserialize that URL and find the\n// corresponding record, we will not know if it is a string or a number.\ntype Coercable = string | number | boolean | null | undefined | symbol;\n\n/**\n * Normalizes a resource `id` entering the store to a string (or `null`).\n *\n * When `DEPRECATE_NON_STRICT_ID` is enabled, any non-string, non-nullish id\n * is stringified and a deprecation is issued; `''`/`null`/`undefined` all\n * normalize to `null`. Otherwise, `id` must already be `null` or a\n * non-empty string, which is asserted.\n *\n * @private\n */\nexport function coerceId(id: unknown): string | null {\n if (DEPRECATE_NON_STRICT_ID) {\n let normalized: string | null;\n if (id === null || id === undefined || id === '') {\n normalized = null;\n } else {\n normalized = String(id);\n }\n\n deprecate(\n `The resource id '<${typeof id}> ${String(\n id\n )} ' is not normalized. Update your application code to use '${JSON.stringify(normalized)}' instead.`,\n normalized === id,\n {\n id: 'ember-data:deprecate-non-strict-id',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.3',\n },\n }\n );\n\n return normalized;\n }\n\n assert(\n `Resource IDs must be a non-empty string or null. Received '${String(id)}'.`,\n id === null || (typeof id === 'string' && id.length > 0)\n );\n\n return id;\n}\n\n/**\n * Coerces `id` to a non-empty string, asserting if it is not already a\n * non-empty string or a valid (non-`NaN`) number.\n *\n * Unlike {@link coerceId}, this never returns `null` and does not honor\n * `DEPRECATE_NON_STRICT_ID`.\n *\n * @private\n */\nexport function ensureStringId(id: Coercable): string {\n let normalized: string | null = null;\n if (typeof id === 'string') {\n normalized = id.length > 0 ? id : null;\n } else if (typeof id === 'number' && !isNaN(id)) {\n normalized = String(id);\n }\n\n assert(`Expected id to be a string or number, received ${String(id)}`, normalized !== null);\n\n return normalized;\n}\n","import { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_NON_STRICT_TYPES } from '@warp-drive/core/build-config/deprecations';\n\nimport { dasherize } from '../../../utils/string.ts';\n\n/**\n * Normalizes a resource `type` to its dasherized form, e.g. `myClass` to\n * `my-class`. Re-exported elsewhere as `_deprecatingNormalize`.\n *\n * When `DEPRECATE_NON_STRICT_TYPES` is enabled, dasherizes `type` and issues\n * a deprecation if it was not already normalized. Otherwise, `type` is\n * returned unchanged and callers are expected to have already normalized it.\n *\n * @private\n */\nexport function normalizeModelName(type: string): string {\n if (DEPRECATE_NON_STRICT_TYPES) {\n const result = dasherize(type);\n\n deprecate(\n `The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`,\n result === type,\n {\n id: 'ember-data:deprecate-non-strict-types',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.3',\n },\n }\n );\n\n return result;\n }\n\n return type;\n}\n","import { warn } from '@ember/debug';\n\nimport { getGlobalConfig, macroCondition } from '@embroider/macros';\n\nimport { LOG_IDENTIFIERS } from '@warp-drive/core/build-config/debugging';\nimport { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type {\n ForgetMethod,\n GenerationMethod,\n KeyInfo,\n KeyInfoMethod,\n ResetMethod,\n UpdateMethod,\n} from '../../-types/q/identifier.ts';\nimport { getOrSetGlobal, peekTransient, setTransient } from '../../../types/-private.ts';\nimport {\n CACHE_OWNER,\n type CacheKeyType,\n DEBUG_CLIENT_ORIGINATED,\n DEBUG_KEY_TYPE,\n DEBUG_STALE_CACHE_OWNER,\n type PersistedResourceKey,\n type RequestKey,\n type ResourceKey,\n} from '../../../types/identifier.ts';\nimport type { ImmutableRequestInfo, RequestInfo } from '../../../types/request.ts';\nimport type {\n ExistingResourceIdentifierObject,\n ExistingResourceObject,\n ResourceIdentifierObject,\n} from '../../../types/spec/json-api-raw.ts';\nimport { hasId, hasLid, hasType } from '../caches/resource-utils.ts';\nimport { coerceId } from '../utils/coerce-id.ts';\nimport { normalizeModelName } from '../utils/normalize-model-name.ts';\nimport installPolyfill from '../utils/uuid-polyfill.ts';\n\ntype TypeFromIdentifier<T> = T extends { type: infer U } ? U : string;\n\ntype NarrowIdentifierIfPossible<T> = T extends ExistingResourceIdentifierObject\n ? PersistedResourceKey<TypeFromIdentifier<T>>\n : ResourceKey;\n\n/**\n * Type-guard that returns `true` if the given value is a stable {@link ResourceKey}\n * (as opposed to a {@link RequestKey} or arbitrary, not-yet-stabilized resource data).\n */\nexport function isResourceKey(identifier: unknown): identifier is ResourceKey {\n if (DEBUG) {\n return (\n !!identifier &&\n typeof identifier === 'object' &&\n 'type' in identifier &&\n 'id' in identifier &&\n identifier.type !== '@document' &&\n (identifier as ResourceKey)[CACHE_OWNER] !== undefined\n );\n } else {\n return (identifier as RequestKey).type !== '@document' && (identifier as RequestKey)[CACHE_OWNER] !== undefined;\n }\n}\n\n/**\n * Type-guard that returns `true` if the given value is a stable {@link RequestKey}\n * (as opposed to a {@link ResourceKey} or arbitrary, not-yet-stabilized data).\n */\nexport function isRequestKey(identifier: unknown): identifier is RequestKey {\n if (DEBUG) {\n return (\n !!identifier &&\n typeof identifier === 'object' &&\n 'type' in identifier &&\n !('id' in identifier) &&\n identifier.type === '@document' &&\n (identifier as ResourceKey)[CACHE_OWNER] !== undefined\n );\n } else {\n return (identifier as RequestKey).type === '@document' && (identifier as RequestKey)[CACHE_OWNER] !== undefined;\n }\n}\n\nconst isFastBoot = typeof FastBoot !== 'undefined';\nconst _crypto: Crypto = isFastBoot ? (FastBoot.require('crypto') as Crypto) : globalThis.crypto;\n\nif (macroCondition(getGlobalConfig<{ WarpDrive: { polyfillUUID: boolean } }>().WarpDrive.polyfillUUID)) {\n installPolyfill();\n}\n\nfunction uuidv4(): string {\n assert(\n 'crypto.randomUUID needs to be avaliable. Some browsers incorrectly disallow it in insecure contexts. You maybe want to enable the polyfill: https://github.com/warp-drive-data/warp-drive#randomuuid-polyfill',\n typeof _crypto.randomUUID === 'function'\n );\n return _crypto.randomUUID();\n}\n\nfunction freeze<T>(obj: T): T {\n if (typeof Object.freeze === 'function') {\n return Object.freeze(obj);\n }\n return obj;\n}\n\ninterface KeyOptions {\n lid: IdentifierMap;\n id: IdentifierMap;\n}\ntype TypeMap = { [key: string]: KeyOptions };\n\n// type IdentifierTypeLookup = { all: Set<ResourceKey>; id: Map<string, ResourceKey> };\n// type IdentifiersByType = Map<string, IdentifierTypeLookup>;\ntype IdentifierMap = Map<string, ResourceKey>;\n\ntype StableCache = {\n resources: IdentifierMap;\n documents: Map<string, RequestKey>;\n resourcesByType: TypeMap;\n polymorphicLidBackMap: Map<string, string[]>;\n};\n\nexport type MergeMethod = (\n targetIdentifier: ResourceKey,\n matchedIdentifier: ResourceKey,\n resourceData: unknown\n) => ResourceKey;\n\n/**\n Configures how unique identifier lid strings are generated by @ember-data/store.\n\n This configuration MUST occur prior to the store instance being created.\n\n Takes a method which can expect to receive various data as its first argument\n and the name of a bucket as its second argument.\n\n Currently there are two buckets, 'record' and 'document'.\n\n ### Resource (`Record`) Identity\n\n If the bucket is `record` the method must return a unique (to at-least\n the given bucket) string identifier for the given data as a string to be\n used as the `lid` of an `Identifier` token.\n\n This method will only be called by either `getOrCreateRecordIdentifier` or\n `createIdentifierForNewRecord` when an identifier for the supplied data\n is not already known via `lid` or `type + id` combo and one needs to be\n generated or retrieved from a proprietary cache.\n\n `data` will be the same data argument provided to `getOrCreateRecordIdentifier`\n and in the `createIdentifierForNewRecord` case will be an object with\n only `type` as a key.\n\n ```ts\n import { setIdentifierGenerationMethod } from '@warp-drive/core';\n\n export function initialize(applicationInstance) {\n // note how `count` here is now scoped to the application instance\n // for our generation method by being inside the closure provided\n // by the initialize function\n let count = 0;\n\n setIdentifierGenerationMethod((resource, bucket) => {\n return resource.lid || `my-key-${count++}`;\n });\n }\n\n export default {\n name: 'configure-ember-data-identifiers',\n initialize\n };\n ```\n\n ### Document Identity\n\n If the bucket is `document` the method will receive the associated\n immutable `request` passed to `store.request` as its first argument\n and should return a unique string for the given request if the document\n should be cached, and `null` if it should not be cached.\n\n Note, the request result will still be passed to the cache via `Cache.put`,\n but caches should take this as a signal that the document should not itself\n be cached, while its contents may still be used to update other cache state.\n\n The presence of `cacheOptions.key` on the request will take precedence\n for the document cache key, and this method will not be called if it is\n present.\n\n The default method implementation for this bucket is to return `null`\n for all requests whose method is not `GET`, and to return the `url` for\n those where it is.\n\n This means that queries via `POST` MUST provide `cacheOptions.key` or\n implement this hook.\n\n ⚠️ Caution: Requests that do not have a `method` assigned are assumed to be `GET`\n\n @public\n*/\nexport function setIdentifierGenerationMethod(method: GenerationMethod | null): void {\n setTransient('configuredGenerationMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache encounters new resource\n data for an existing resource.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierUpdateMethod } from '@warp-drive/core';\n ```\n\n Takes a method which can expect to receive an existing `Identifier` alongside\n some new data to consider as a second argument. This is an opportunity\n for secondary lookup tables and caches associated with the identifier\n to be amended.\n\n This method is called everytime `updateRecordIdentifier` is called and\n with the same arguments. It provides the opportunity to update secondary\n lookup tables for existing identifiers.\n\n It will always be called after an identifier created with `createIdentifierForNewRecord`\n has been committed, or after an update to the `record` a `RecordIdentifier`\n is assigned to has been committed. Committed here meaning that the server\n has acknowledged the update (for instance after a call to `.save()`)\n\n If `id` has not previously existed, it will be assigned to the `Identifier`\n prior to this `UpdateMethod` being called; however, calls to the parent method\n `updateRecordIdentifier` that attempt to change the `id` or calling update\n without providing an `id` when one is missing will throw an error.\n\n @public\n*/\nexport function setIdentifierUpdateMethod(method: UpdateMethod | null): void {\n setTransient('configuredUpdateMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is going to release an identifier.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierForgetMethod } from '@warp-drive/core';\n ```\n\n Takes method which can expect to receive an existing `Identifier` that should be eliminated\n from any secondary lookup tables or caches that the user has populated for it.\n\n @public\n*/\nexport function setIdentifierForgetMethod(method: ForgetMethod | null): void {\n setTransient('configuredForgetMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is being torn down.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierResetMethod } from '@warp-drive/core';\n ```\n\n Takes a method which can expect to be called when the parent application is destroyed.\n\n If you have properly used a WeakMap to encapsulate the state of your customization\n to the application instance, you may not need to implement the `resetMethod`.\n\n @public\n*/\nexport function setIdentifierResetMethod(method: ResetMethod | null): void {\n setTransient('configuredResetMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is generating a new\n ResourceKey for a resource.\n\n This method controls the `type` and `id` that will be assigned to the\n `ResourceKey` that is created.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setKeyInfoForResource } from '@warp-drive/core';\n ```\n\n @public\n */\nexport function setKeyInfoForResource(method: KeyInfoMethod | null): void {\n setTransient('configuredKeyInfoMethod', method);\n}\n\nfunction assertIsRequest(request: unknown): asserts request is ImmutableRequestInfo {\n return;\n}\n\n// Map<type, Map<id, lid>>\ntype TypeIdMap = Map<string, Map<string, string>>;\n// TODO can we just delete this?\nconst NEW_IDENTIFIERS: TypeIdMap = new Map();\n// TODO @runspired maybe needs peekTransient ?\nlet IDENTIFIER_CACHE_ID = 0;\n\nfunction updateTypeIdMapping(typeMap: TypeIdMap, identifier: ResourceKey, id: string): void {\n let idMap = typeMap.get(identifier.type);\n if (!idMap) {\n idMap = new Map();\n typeMap.set(identifier.type, idMap);\n }\n idMap.set(id, identifier.lid);\n}\n\nfunction defaultUpdateMethod(identifier: ResourceKey, data: unknown, bucket: 'record'): void;\nfunction defaultUpdateMethod(identifier: RequestKey, data: unknown, bucket: 'document'): void;\nfunction defaultUpdateMethod(identifier: { lid: string }, newData: unknown, bucket: never): void;\nfunction defaultUpdateMethod(\n identifier: RequestKey | ResourceKey | { lid: string },\n data: unknown,\n bucket: 'record' | 'document'\n): void {\n if (bucket === 'record') {\n assert(`Expected identifier to be a ResourceKey`, isResourceKey(identifier));\n if (!identifier.id && hasId(data)) {\n updateTypeIdMapping(NEW_IDENTIFIERS, identifier, data.id);\n }\n }\n}\n\nfunction defaultKeyInfoMethod(resource: unknown, known: ResourceKey | null): KeyInfo {\n // TODO RFC something to make this configurable\n const id = hasId(resource) ? coerceId(resource.id) : null;\n const type = hasType(resource) ? normalizeModelName(resource.type) : known ? known.type : null;\n\n assert(`Expected keyInfoForResource to provide a type for the resource`, type);\n\n return { type, id };\n}\n\nfunction defaultGenerationMethod(data: unknown, bucket: CacheKeyType): string | null {\n if (bucket === 'record') {\n if (hasLid(data)) {\n return data.lid;\n }\n\n assert(`Cannot generate an identifier for a resource without a type`, hasType(data));\n\n if (hasId(data)) {\n const type = normalizeModelName(data.type);\n const lid = NEW_IDENTIFIERS.get(type)?.get(data.id);\n\n return lid || `@lid:${type}-${data.id}`;\n }\n\n return uuidv4();\n } else if (bucket === 'document') {\n assertIsRequest(data);\n if (!data.url) {\n return null;\n }\n if (!data.method || data.method.toUpperCase() === 'GET') {\n return data.url;\n }\n return null;\n }\n assert(`Unknown bucket ${bucket as string}`, false);\n}\n\nfunction defaultEmptyCallback(...args: unknown[]): void {}\nfunction defaultMergeMethod(a: ResourceKey, _b: ResourceKey, _c: unknown): ResourceKey {\n return a;\n}\n\nlet DEBUG_MAP: WeakMap<ResourceKey, ResourceKey>;\nif (DEBUG) {\n DEBUG_MAP = getOrSetGlobal('DEBUG_MAP', new WeakMap<ResourceKey, ResourceKey>());\n}\n\n/**\n * Each instance of {@link Store} receives a unique instance of a CacheKeyManager.\n *\n * This cache is responsible for assigning or retrieving the unique identify\n * for arbitrary resource data encountered by the store. Data representing\n * a unique resource or record should always be represented by the same\n * identifier.\n *\n * It can be configured by consuming applications.\n *\n * @hideconstructor\n * @public\n */\nexport class CacheKeyManager {\n /** @internal */\n _cache: StableCache;\n /** @internal */\n declare private _generate: GenerationMethod;\n /** @internal */\n declare private _update: UpdateMethod;\n /** @internal */\n declare private _forget: ForgetMethod;\n /** @internal */\n declare private _reset: ResetMethod;\n /** @internal */\n declare private _merge: MergeMethod;\n /** @internal */\n declare private _keyInfoForResource: KeyInfoMethod;\n /** @internal */\n declare private _id: number;\n\n constructor() {\n // we cache the user configuredGenerationMethod at init because it must\n // be configured prior and is not allowed to be changed\n this._generate =\n peekTransient<GenerationMethod>('configuredGenerationMethod') || (defaultGenerationMethod as GenerationMethod);\n this._update = peekTransient<UpdateMethod>('configuredUpdateMethod') || defaultUpdateMethod;\n this._forget = peekTransient<ForgetMethod>('configuredForgetMethod') || defaultEmptyCallback;\n this._reset = peekTransient<ResetMethod>('configuredResetMethod') || defaultEmptyCallback;\n this._merge = defaultMergeMethod;\n this._keyInfoForResource = peekTransient<KeyInfoMethod>('configuredKeyInfoMethod') || defaultKeyInfoMethod;\n this._id = IDENTIFIER_CACHE_ID++;\n\n this._cache = {\n resources: new Map<string, ResourceKey>(),\n resourcesByType: Object.create(null) as TypeMap,\n documents: new Map<string, RequestKey>(),\n polymorphicLidBackMap: new Map<string, string[]>(),\n };\n }\n\n /**\n * Internal hook to allow management of merge conflicts with identifiers.\n *\n * we allow late binding of this private internal merge so that\n * the cache can insert itself here to handle elimination of duplicates\n *\n * @internal\n */\n __configureMerge(method: MergeMethod | null): void {\n this._merge = method || defaultMergeMethod;\n }\n\n /** @internal */\n upgradeIdentifier(resource: { type: string; id: string | null; lid?: string }): ResourceKey {\n return this._getRecordIdentifier(resource, 2);\n }\n\n /** @internal */\n private _getRecordIdentifier(\n resource: { type: string; id: string | null; lid?: string },\n shouldGenerate: 2\n ): ResourceKey;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 1): ResourceKey;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 0): ResourceKey | undefined;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 0 | 1 | 2): ResourceKey | undefined {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(`Identifiers: ${shouldGenerate ? 'Generating' : 'Peeking'} Identifier`, resource);\n }\n // short circuit if we're already the stable version\n if (isResourceKey(resource)) {\n if (DEBUG) {\n // TODO should we instead just treat this case as a new generation skipping the short circuit?\n if (!this._cache.resources.has(resource.lid) || this._cache.resources.get(resource.lid) !== resource) {\n throw new Error(`The supplied identifier ${JSON.stringify(resource)} does not belong to this store instance`);\n }\n }\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: cache HIT - Stable ${resource.lid}`);\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return resource;\n }\n\n // the resource is unknown, ask the application to identify this data for us\n const lid = this._generate(resource, 'record');\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: ${lid ? 'no ' : ''}lid ${lid ? lid + ' ' : ''}determined for resource`, resource);\n }\n\n let identifier: ResourceKey | null = /*#__NOINLINE__*/ getIdentifierFromLid(this._cache, lid, resource);\n if (identifier !== null) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return identifier;\n }\n\n if (shouldGenerate === 0) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return;\n }\n\n // if we still don't have an identifier, time to generate one\n if (shouldGenerate === 2) {\n (resource as ResourceKey).lid = lid;\n (resource as ResourceKey)[CACHE_OWNER] = this._id;\n identifier = /*#__NOINLINE__*/ makeResourceKey(resource as ResourceKey, 'record', false);\n } else {\n // we lie a bit here as a memory optimization\n const keyInfo = this._keyInfoForResource(resource, null) as ResourceKey;\n keyInfo.lid = lid;\n keyInfo[CACHE_OWNER] = this._id;\n identifier = /*#__NOINLINE__*/ makeResourceKey(keyInfo, 'record', false);\n }\n\n addResourceToCache(this._cache, identifier);\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n\n return identifier;\n }\n\n /**\n * allows us to peek without generating when needed\n * useful for the \"create\" case when we need to see if\n * we are accidentally overwritting something\n *\n * @private\n */\n peekResourceKey(resource: ResourceIdentifierObject): ResourceKey | undefined {\n return this._getRecordIdentifier(resource, 0);\n }\n\n /**\n * Peeks the {@link RequestKey} for the given {@link RequestInfo}, but will not\n * create one if none has been previously generated.\n *\n * @public\n */\n peekRequestKey(request: RequestInfo): RequestKey | null {\n let cacheKey: string | null | undefined = request.cacheOptions?.key;\n\n if (!cacheKey) {\n cacheKey = this._generate(request, 'document');\n }\n\n if (!cacheKey) {\n return null;\n }\n\n const identifier = this._cache.documents.get(cacheKey);\n return identifier ?? null;\n }\n\n /**\n * Returns the {@link RequestKey} for the given {@link RequestInfo} if the request is\n * considered cacheable. For cacheable requests, this method will create\n * a RequestKey if none is found.\n *\n * A `null` response indicates the request cannot/will not be cached,\n * generally this means either\n *\n * - {@link RequestInfo.cacheOptions.key} is not present on the `RequestInfo`\n * - the request's method is `GET` but it has no `url`\n *\n * Generally you should not seek to cache requests that are not idempotent\n * or have side effects, such as mutations that create, update or delete\n * a resource.\n *\n * @public\n */\n getOrCreateDocumentIdentifier(request: RequestInfo): RequestKey | null {\n let cacheKey: string | null | undefined = request.cacheOptions?.key;\n\n if (!cacheKey) {\n cacheKey = this._generate(request, 'document');\n }\n\n if (!cacheKey) {\n return null;\n }\n\n let identifier = this._cache.documents.get(cacheKey);\n\n if (identifier === undefined) {\n identifier = { lid: cacheKey, type: '@document', [CACHE_OWNER]: this._id };\n if (DEBUG) {\n Object.freeze(identifier);\n }\n this._cache.documents.set(cacheKey, identifier);\n }\n\n return identifier;\n }\n\n /**\n Returns the {@link ResourceKey} for the given Resource, creates one if it does not yet exist.\n\n Specifically this means that we:\n\n - validate the `id` `type` and `lid` combo against known identifiers\n - return an object with an `lid` that is stable (repeated calls with the same\n `id` + `type` or `lid` will return the same `lid` value)\n - this referential stability of the object itself is guaranteed\n\n @public\n */\n getOrCreateRecordIdentifier<T>(resource: T): NarrowIdentifierIfPossible<T> {\n return this._getRecordIdentifier(resource as unknown, 1) as NarrowIdentifierIfPossible<T>;\n }\n\n /**\n Returns a new Identifier for the supplied data. Call this method to generate\n an identifier when a new resource is being created local to the client and\n potentially does not have an `id`.\n\n Delegates generation to the user supplied `GenerateMethod` if one has been provided\n with the signature `generateMethod({ type }, 'record')`.\n\n @public\n */\n createIdentifierForNewRecord(data: { type: string; id?: string | null; lid?: string }): ResourceKey {\n const newLid = this._generate(data, 'record');\n const identifier = /*#__NOINLINE__*/ makeResourceKey(\n { id: data.id || null, type: data.type, lid: newLid, [CACHE_OWNER]: this._id },\n 'record',\n true\n );\n\n // populate our unique table\n if (DEBUG) {\n if (this._cache.resources.has(identifier.lid)) {\n throw new Error(`The lid generated for the new record is not unique as it matches an existing identifier`);\n }\n }\n\n /*#__NOINLINE__*/ addResourceToCache(this._cache, identifier);\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: created identifier ${String(identifier)} for newly generated resource`, data);\n }\n\n return identifier;\n }\n\n /**\n Provides the opportunity to update secondary lookup tables for existing identifiers\n Called after an identifier created with `createIdentifierForNewRecord` has been\n committed.\n\n Assigned `id` to an `Identifier` if `id` has not previously existed; however,\n attempting to change the `id` or calling update without providing an `id` when\n one is missing will throw an error.\n\n - sets `id` (if `id` was previously `null`)\n - `lid` and `type` MUST NOT be altered post creation\n\n If a merge occurs, it is possible the returned identifier does not match the originally\n provided identifier. In this case the abandoned identifier will go through the usual\n `forgetRecordIdentifier` codepaths.\n\n @public\n */\n // FIXME audit usage\n updateRecordIdentifier(identifierObject: ResourceKey, data: unknown): ResourceKey {\n let identifier = this.getOrCreateRecordIdentifier(identifierObject);\n\n const keyInfo = this._keyInfoForResource(data, identifier);\n let existingIdentifier = /*#__NOINLINE__*/ detectMerge(this._cache, keyInfo, identifier, data);\n const hadLid = hasLid(data);\n\n if (!existingIdentifier) {\n // If the incoming type does not match the identifier type, we need to create an identifier for the incoming\n // data so we can merge the incoming data with the existing identifier, see #7325 and #7363\n if (identifier.type !== keyInfo.type) {\n if (hadLid) {\n // Strip the lid to ensure we force a new identifier creation\n delete (data as { lid?: string }).lid;\n }\n existingIdentifier = this.getOrCreateRecordIdentifier(data);\n }\n }\n\n if (existingIdentifier) {\n const generatedIdentifier = identifier;\n identifier = this._mergeRecordIdentifiers(keyInfo, generatedIdentifier, existingIdentifier, data);\n\n // make sure that the `lid` on the data we are processing matches the lid we kept\n if (hadLid) {\n data.lid = identifier.lid;\n }\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Identifiers: merged identifiers ${generatedIdentifier.lid} and ${existingIdentifier.lid} for resource into ${identifier.lid}`,\n data\n );\n }\n }\n\n const id = identifier.id;\n /*#__NOINLINE__*/ performRecordIdentifierUpdate(identifier, keyInfo, data, this._update);\n const newId = identifier.id;\n\n // add to our own secondary lookup table\n if (id !== newId && newId !== null) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Identifiers: updated id for identifier ${identifier.lid} from '${String(id)}' to '${String(\n newId\n )}' for resource`,\n data\n );\n }\n\n const typeSet = this._cache.resourcesByType[identifier.type];\n assert(`Expected to find a typeSet for ${identifier.type}`, typeSet);\n typeSet.id.set(newId, identifier);\n\n if (id !== null) {\n typeSet.id.delete(id);\n }\n } else if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: updated identifier ${identifier.lid} resource`, data);\n }\n\n return identifier;\n }\n\n /**\n * @internal\n */\n _mergeRecordIdentifiers(\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n existingIdentifier: ResourceKey,\n data: unknown\n ): ResourceKey {\n assert(`Expected keyInfo to contain an id`, hasId(keyInfo));\n // delegate determining which identifier to keep to the configured MergeMethod\n const kept = this._merge(identifier, existingIdentifier, data);\n const abandoned = kept === identifier ? existingIdentifier : identifier;\n\n // get any backreferences before forgetting this identifier, as it will be removed from the cache\n // and we will no longer be able to find them\n const abandonedBackReferences = this._cache.polymorphicLidBackMap.get(abandoned.lid);\n // delete the backreferences for the abandoned identifier so that forgetRecordIdentifier\n // does not try to remove them.\n if (abandonedBackReferences) this._cache.polymorphicLidBackMap.delete(abandoned.lid);\n\n // cleanup the identifier we no longer need\n this.forgetRecordIdentifier(abandoned);\n\n // ensure a secondary cache entry for the original lid for the abandoned identifier\n this._cache.resources.set(abandoned.lid, kept);\n\n // backReferences let us know which other identifiers are pointing at this identifier\n // so we can delete them later if we forget this identifier\n const keptBackReferences = this._cache.polymorphicLidBackMap.get(kept.lid) ?? [];\n keptBackReferences.push(abandoned.lid);\n\n // update the backreferences from the abandoned identifier to be for the kept identifier\n if (abandonedBackReferences) {\n abandonedBackReferences.forEach((lid) => {\n keptBackReferences.push(lid);\n this._cache.resources.set(lid, kept);\n });\n }\n\n this._cache.polymorphicLidBackMap.set(kept.lid, keptBackReferences);\n return kept;\n }\n\n /**\n Provides the opportunity to eliminate an identifier from secondary lookup tables\n as well as eliminates it from ember-data's own lookup tables and book keeping.\n\n Useful when a record has been deleted and the deletion has been persisted and\n we do not care about the record anymore. Especially useful when an `id` of a\n deleted record might be reused later for a new record.\n\n @public\n */\n // FIXME audit usage\n forgetRecordIdentifier(identifierObject: ResourceKey): void {\n const identifier = this.getOrCreateRecordIdentifier(identifierObject);\n const typeSet = this._cache.resourcesByType[identifier.type];\n assert(`Expected to find a typeSet for ${identifier.type}`, typeSet);\n\n if (identifier.id !== null) {\n typeSet.id.delete(identifier.id);\n }\n this._cache.resources.delete(identifier.lid);\n typeSet.lid.delete(identifier.lid);\n\n const backReferences = this._cache.polymorphicLidBackMap.get(identifier.lid);\n if (backReferences) {\n backReferences.forEach((lid) => {\n this._cache.resources.delete(lid);\n });\n this._cache.polymorphicLidBackMap.delete(identifier.lid);\n }\n\n if (DEBUG) {\n identifier[DEBUG_STALE_CACHE_OWNER] = identifier[CACHE_OWNER];\n }\n identifier[CACHE_OWNER] = undefined;\n this._forget(identifier, 'record');\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: released identifier ${identifierObject.lid}`);\n }\n }\n\n /** @internal */\n destroy(): void {\n NEW_IDENTIFIERS.clear();\n this._reset();\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateCacheKeyManager extends CacheKeyManager {\n _cache: StableCache;\n /**\n * Internal hook to allow management of merge conflicts with identifiers.\n *\n * we allow late binding of this private internal merge so that\n * the cache can insert itself here to handle elimination of duplicates\n */\n __configureMerge(method: MergeMethod | null): void;\n _mergeRecordIdentifiers(\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n existingIdentifier: ResourceKey,\n data: unknown\n ): ResourceKey;\n destroy(): void;\n}\n\nfunction makeResourceKey(\n recordIdentifier: {\n type: string;\n id: string | null;\n lid: string;\n [CACHE_OWNER]: number | undefined;\n },\n bucket: CacheKeyType,\n clientOriginated: boolean\n): ResourceKey {\n if (DEBUG) {\n // we enforce immutability in dev\n // but preserve our ability to do controlled updates to the reference\n let wrapper = {\n type: recordIdentifier.type,\n lid: recordIdentifier.lid,\n get id() {\n return recordIdentifier.id;\n },\n } as ResourceKey;\n const proto = {\n get [CACHE_OWNER](): number | undefined {\n return recordIdentifier[CACHE_OWNER];\n },\n set [CACHE_OWNER](value: number) {\n recordIdentifier[CACHE_OWNER] = value;\n },\n get [DEBUG_STALE_CACHE_OWNER](): number | undefined {\n return (recordIdentifier as ResourceKey)[DEBUG_STALE_CACHE_OWNER];\n },\n set [DEBUG_STALE_CACHE_OWNER](value: number | undefined) {\n (recordIdentifier as ResourceKey)[DEBUG_STALE_CACHE_OWNER] = value;\n },\n get [DEBUG_CLIENT_ORIGINATED]() {\n return clientOriginated;\n },\n get [DEBUG_KEY_TYPE]() {\n return bucket;\n },\n };\n Object.defineProperty(proto, 'toString', {\n enumerable: false,\n value: () => {\n const { type, id, lid } = recordIdentifier;\n return `${clientOriginated ? '[CLIENT_ORIGINATED] ' : ''}${String(type)}:${String(id)} (${lid})`;\n },\n });\n Object.defineProperty(proto, 'toJSON', {\n enumerable: false,\n value: () => {\n const { type, id, lid } = recordIdentifier;\n return { type, id, lid };\n },\n });\n Object.setPrototypeOf(wrapper, proto);\n DEBUG_MAP.set(wrapper, recordIdentifier);\n wrapper = freeze(wrapper);\n return wrapper;\n }\n\n return recordIdentifier;\n}\n\nfunction performRecordIdentifierUpdate(\n identifier: ResourceKey,\n keyInfo: KeyInfo,\n data: unknown,\n updateFn: UpdateMethod\n) {\n if (DEBUG) {\n const { id, type } = keyInfo;\n\n // get the mutable instance behind our proxy wrapper\n const wrapper = identifier;\n identifier = DEBUG_MAP.get(wrapper)!;\n\n if (hasLid(data)) {\n const lid = data.lid;\n if (lid !== identifier.lid) {\n throw new Error(\n `The 'lid' for a ResourceKey cannot be updated once it has been created. Attempted to set lid for '${wrapper.lid}' to '${lid}'.`\n );\n }\n }\n\n if (id && identifier.id !== null && identifier.id !== id) {\n // here we warn and ignore, as this may be a mistake, but we allow the user\n // to have multiple cache-keys pointing at a single lid so we cannot error\n warn(\n `The 'id' for a ResourceKey should not be updated once it has been set. Attempted to set id for '${wrapper.lid}' to '${id}'.`,\n false,\n { id: 'ember-data:multiple-ids-for-identifier' }\n );\n }\n\n // TODO consider just ignoring here to allow flexible polymorphic support\n if (type && type !== identifier.type) {\n throw new Error(\n `The 'type' for a ResourceKey cannot be updated once it has been set. Attempted to set type for '${wrapper.lid}' to '${type}'.`\n );\n }\n\n updateFn(wrapper, data, 'record');\n } else {\n updateFn(identifier, data, 'record');\n }\n\n // upgrade the ID, this is a \"one time only\" ability\n // for the multiple-cache-key scenario we \"could\"\n // use a heuristic to guess the best id for display\n // (usually when `data.id` is available and `data.attributes` is not)\n if ((data as ExistingResourceObject).id !== undefined) {\n identifier.id = coerceId((data as ExistingResourceObject).id);\n }\n}\n\nfunction detectMerge(\n cache: StableCache,\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n data: unknown\n): ResourceKey | false {\n const newId = keyInfo.id;\n const { id, type, lid } = identifier;\n const typeSet = cache.resourcesByType[identifier.type];\n\n // if the IDs are present but do not match\n // then check if we have an existing identifier\n // for the newer ID.\n if (id !== null && id !== newId && newId !== null) {\n const existingIdentifier = typeSet && typeSet.id.get(newId);\n\n return existingIdentifier !== undefined ? existingIdentifier : false;\n } else {\n const newType = keyInfo.type;\n\n // If the ids and type are the same but lid is not the same, we should trigger a merge of the identifiers\n // we trigger a merge of the identifiers\n // though probably we should just throw an error here\n if (id !== null && id === newId && newType === type && hasLid(data) && data.lid !== lid) {\n return getIdentifierFromLid(cache, data.lid, data) || false;\n\n // If the lids are the same, and ids are the same, but types are different we should trigger a merge of the identifiers\n } else if (id !== null && id === newId && newType && newType !== type && hasLid(data) && data.lid === lid) {\n const newTypeSet = cache.resourcesByType[newType];\n const existingIdentifier = newTypeSet && newTypeSet.id.get(newId);\n\n return existingIdentifier !== undefined ? existingIdentifier : false;\n }\n }\n\n return false;\n}\n\nfunction getIdentifierFromLid(cache: StableCache, lid: string, resource: unknown): ResourceKey | null {\n const identifier = cache.resources.get(lid);\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: cache ${identifier ? 'HIT' : 'MISS'} - Non-Stable ${lid}`, resource);\n }\n return identifier || null;\n}\n\nfunction addResourceToCache(cache: StableCache, identifier: ResourceKey): void {\n cache.resources.set(identifier.lid, identifier);\n let typeSet = cache.resourcesByType[identifier.type];\n\n if (!typeSet) {\n typeSet = { lid: new Map(), id: new Map() };\n cache.resourcesByType[identifier.type] = typeSet;\n }\n\n typeSet.lid.set(identifier.lid, identifier);\n if (identifier.id) {\n typeSet.id.set(identifier.id, identifier);\n }\n}\n","import { ENABLE_LEGACY_SCHEMA_SERVICE } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { CacheCapabilitiesManager as StoreWrapper } from '../../-types/q/cache-capabilities-manager.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { SchemaService } from '../../../types/schema/schema-service.ts';\nimport type { PrivateStore, Store } from '../store-service.ts';\nimport type { CacheKeyManager } from './cache-key-manager.ts';\nimport { isRequestKey, isResourceKey } from './cache-key-manager.ts';\nimport type { NotificationChannel, NotificationType, NotifyKeys } from './notification-manager.ts';\n\nexport interface CacheCapabilitiesManager {\n /** @deprecated - use {@link CacheCapabilitiesManager.schema} */\n getSchemaDefinitionService(): SchemaService;\n}\nexport class CacheCapabilitiesManager implements StoreWrapper {\n /** @internal */\n declare private _willNotify: boolean;\n\n /** @internal */\n declare private _pendingNotifies: Map<ResourceKey, Map<string, Set<NotificationChannel | undefined>>>;\n\n /** @internal */\n declare _store: Store;\n\n constructor(_store: Store) {\n this._store = _store;\n this._willNotify = false;\n this._pendingNotifies = new Map();\n }\n\n get cacheKeyManager(): CacheKeyManager {\n return this._store.cacheKeyManager;\n }\n\n /** @deprecated use {@link CacheCapabilitiesManager.cacheKeyManager} */\n get identifierCache(): CacheKeyManager {\n return this.cacheKeyManager;\n }\n\n /** @internal */\n private _scheduleNotification(identifier: ResourceKey, key: string, channel: NotificationChannel | undefined): void {\n let pending = this._pendingNotifies.get(identifier);\n\n if (!pending) {\n pending = new Map();\n this._pendingNotifies.set(identifier, pending);\n }\n let channels = pending.get(key);\n if (!channels) {\n channels = new Set();\n pending.set(key, channels);\n }\n channels.add(channel);\n\n if (this._willNotify === true) {\n return;\n }\n\n this._willNotify = true;\n // it's possible a cache adhoc notifies us,\n // in which case we sync flush\n if (this._store._cbs) {\n this._store._schedule('notify', () => this._flushNotifications());\n } else {\n // TODO @runspired determine if relationship mutations should schedule\n // into join/run vs immediate flush\n this._flushNotifications();\n }\n }\n\n /** @internal */\n private _flushNotifications(): void {\n if (this._willNotify === false) {\n return;\n }\n\n const pending = this._pendingNotifies;\n this._pendingNotifies = new Map();\n this._willNotify = false;\n\n // deliver all relationship keys pending for a given identifier as a single\n // batch instead of one `notify` call per key: subscribers still receive one\n // notification per key (in Set-insertion order), but the per-call overhead\n // (subscriber lookups, buffer scheduling, etc) that `notify` would otherwise\n // repeat for every key is paid only once per identifier. This mirrors the\n // same N*M concern `attributes` notifications have (the json-api Cache\n // batches a record's changed attribute keys into a single `notifyChange`\n // Set for the same reason): a single push/mutation pass can dirty many\n // relationships across many records at once, and each of those records\n // funnels through this same per-identifier `pending` Set.\n //\n // Keys touched with more than one distinct channel during this window\n // (e.g. once unscoped and once on `'local'`) are re-grouped by channel\n // below so that each distinct channel is still handed off to `notify` as\n // a single `Set<string>` batch call (never one call per key) -- `notify`'s\n // own buffer (see NotificationManager) is what dedupes/coalesces these\n // per-channel batches back down to a single delivery per subscriber.\n pending.forEach((channelsByKey, identifier) => {\n const keysByChannel = new Map<NotificationChannel | undefined, Set<string>>();\n channelsByKey.forEach((channels, key) => {\n channels.forEach((channel) => {\n let keys = keysByChannel.get(channel);\n if (!keys) {\n keys = new Set();\n keysByChannel.set(channel, keys);\n }\n keys.add(key);\n });\n });\n keysByChannel.forEach((keys, channel) => {\n this._store.notifications.notify(identifier, 'relationships', keys, channel);\n });\n });\n }\n\n notifyChange(identifier: ResourceKey, namespace: 'added' | 'removed', key: null): void;\n notifyChange(identifier: RequestKey, namespace: 'added' | 'updated' | 'removed', key: null): void;\n notifyChange(\n identifier: ResourceKey,\n namespace: 'attributes',\n key: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): void;\n notifyChange(\n identifier: ResourceKey,\n namespace: NotificationType,\n key: string | null,\n channel?: NotificationChannel\n ): void;\n notifyChange(\n identifier: ResourceKey | RequestKey,\n namespace: NotificationType | 'added' | 'removed' | 'updated',\n key: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier) || isRequestKey(identifier));\n\n // TODO do we still get value from this?\n if (namespace === 'relationships' && key) {\n assert(`Expected a single relationship key`, typeof key === 'string');\n this._scheduleNotification(identifier as ResourceKey, key, channel);\n return;\n }\n\n // @ts-expect-error\n this._store.notifications.notify(identifier, namespace, key, channel);\n }\n\n get schema(): SchemaService {\n return this._store.schema;\n }\n\n setRecordId(identifier: ResourceKey, id: string): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier));\n this._store._instanceCache.setRecordId(identifier, id);\n }\n\n hasRecord(identifier: ResourceKey): boolean {\n return Boolean(this._store._instanceCache.peek(identifier));\n }\n\n disconnectRecord(identifier: ResourceKey): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier));\n this._store._instanceCache.disconnect(identifier);\n this._pendingNotifies.delete(identifier);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateCacheCapabilitiesManager extends CacheCapabilitiesManager {\n _store: PrivateStore;\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n CacheCapabilitiesManager.prototype.getSchemaDefinitionService = function () {\n // FIXME add deprecation for this\n return this.schema;\n };\n}\n\n/**\n * Upgrade the type for {@link CacheCapabilitiesManager} to {@link PrivateCacheCapabilitiesManager}.\n *\n * @private\n */\nexport function assertPrivateCapabilities(manager: unknown): asserts manager is PrivateCacheCapabilitiesManager {}\n","import { warn } from '@ember/debug';\n\nimport { LOG_INSTANCE_CACHE } from '@warp-drive/core/build-config/debugging';\nimport { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { OpaqueRecordInstance } from '../../-types/q/record-instance.ts';\nimport { createReactiveDocument, type ReactiveDocument } from '../../../reactive/-private/document.ts';\nimport { _CHECKOUT, ReactiveResource } from '../../../reactive/-private/record.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { Cache } from '../../../types/cache.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { TypedRecordInstance, TypeFromInstance, TypeFromInstanceOrString } from '../../../types/record.ts';\nimport type { ResourceSchema } from '../../../types/schema/fields.ts';\nimport { log, logGroup } from '../debug/utils.ts';\nimport { CacheCapabilitiesManager } from '../managers/cache-capabilities-manager.ts';\nimport type { CacheManager } from '../managers/cache-manager.ts';\nimport type { CreateRecordProperties, Store } from '../store-service.ts';\n\ntype Destroyable = {\n isDestroyed: boolean;\n isDestroying: boolean;\n destroy(): void;\n};\n\nfunction isDestroyable(record: OpaqueRecordInstance): record is Destroyable {\n return Boolean(record && typeof record === 'object' && typeof (record as Destroyable).destroy === 'function');\n}\n\nconst RecordCache = getOrSetGlobal('RecordCache', new Map<OpaqueRecordInstance, ResourceKey>());\n\nexport function peekResourceKey(record: OpaqueRecordInstance): ResourceKey | undefined {\n return RecordCache.get(record);\n}\n\n/**\n Retrieves the unique referentially-stable {@link ResourceKey}\n assigned to the given record instance.\n\n ```js\n import { recordIdentifierFor } from \"@warp-drive/core\";\n // ... gain access to a record, for instance with peekRecord or findRecord\n const record = store.peekRecord(\"user\", \"1\");\n // get the identifier for the record (see docs for ResourceKey)\n const identifier = recordIdentifierFor(record);\n // access the identifier's properties.\n const { id, type, lid } = identifier;\n ```\n\n @public\n @param record a record instance previously obstained from the store.\n */\nexport function recordIdentifierFor<T extends TypedRecordInstance>(record: T): ResourceKey<TypeFromInstance<T>>;\nexport function recordIdentifierFor(record: OpaqueRecordInstance): ResourceKey;\nexport function recordIdentifierFor<T>(record: T): ResourceKey<TypeFromInstanceOrString<T>> {\n assert(`${String(record)} is not a ReactiveResource or Model known to WarpDrive`, RecordCache.has(record));\n return RecordCache.get(record)! as ResourceKey<TypeFromInstanceOrString<T>>;\n}\n\n/**\n * Assigns the given {@link ResourceKey} as the identifier for a record instance,\n * enabling later lookup via {@link recordIdentifierFor}.\n *\n * In debug builds, asserts that the record has not already been assigned a\n * different identifier.\n *\n * @private\n */\nexport function setRecordIdentifier(record: OpaqueRecordInstance, identifier: ResourceKey): void {\n if (DEBUG) {\n if (RecordCache.has(record) && RecordCache.get(record) !== identifier) {\n throw new Error(`${String(record)} was already assigned an identifier`);\n }\n }\n\n /*\n It would be nice to do a reverse check here that an identifier has not\n previously been assigned a record; however, unload + rematerialization\n prevents us from having a great way of doing so when CustomRecordClasses\n don't necessarily give us access to a `isDestroyed` for dematerialized\n instance.\n */\n\n RecordCache.set(record, identifier);\n}\nexport function removeRecordIdentifier(record: OpaqueRecordInstance): void {\n if (DEBUG) {\n if (!RecordCache.has(record)) {\n throw new Error(`${String(record)} had no assigned identifier to remove`);\n }\n }\n RecordCache.delete(record);\n}\n\n/**\n * Module-level lookup of the {@link Store} that owns a given record instance\n * (or {@link ResourceKey}), used by {@link storeFor}.\n *\n * @private\n */\nexport const StoreMap: Map<unknown, Store> = getOrSetGlobal('StoreMap', new Map<OpaqueRecordInstance, Store>());\n\n/**\n * We may eventually make this public, but its likely better for this to be killed off\n * @private\n */\nexport function storeFor(record: OpaqueRecordInstance, ignoreMissing: boolean): Store | null {\n const store = StoreMap.get(record);\n\n assert(\n `A record in a disconnected state cannot utilize the store. This typically means the record has been destroyed, most commonly by unloading it.`,\n ignoreMissing || store\n );\n return store ?? null;\n}\n\nexport type Caches = {\n record: Map<ResourceKey, OpaqueRecordInstance>;\n document: Map<RequestKey, ReactiveDocument<OpaqueRecordInstance | OpaqueRecordInstance[] | null | undefined>>;\n};\n\n/**\n * The internal cache of materialized record and document instances for a {@link Store}.\n *\n * Maps {@link ResourceKey}s to their materialized record instances and\n * {@link RequestKey}s to their {@link ReactiveDocument} instances, instantiating\n * them on demand and coordinating their teardown against the underlying {@link Cache}.\n */\nexport class InstanceCache {\n /** The {@link Store} instance this cache belongs to. */\n declare store: Store;\n /** The underlying {@link Cache} instance backing this store, lazily assigned by the {@link Store}. */\n declare cache: Cache;\n /** The {@link CacheCapabilitiesManager} given to the {@link Cache} to allow it to interact with the store. */\n declare _storeWrapper: CacheCapabilitiesManager;\n\n /** Reserved for a future {@link CacheManager} reference; currently unassigned and unused. */\n declare __cacheManager: CacheManager;\n /** The materialized record and document instances for this store, keyed by {@link ResourceKey} and {@link RequestKey} respectively. */\n declare __instances: Caches;\n\n constructor(store: Store) {\n this.store = store;\n this.__instances = {\n record: new Map(),\n document: new Map(),\n };\n\n this._storeWrapper = new CacheCapabilitiesManager(this.store);\n\n store.cacheKeyManager.__configureMerge(\n (identifier: ResourceKey, matchedIdentifier: ResourceKey, resourceData: unknown) => {\n let keptIdentifier = identifier;\n if (identifier.id !== matchedIdentifier.id) {\n // @ts-expect-error TODO this needs to be fixed\n keptIdentifier = 'id' in resourceData && identifier.id === resourceData.id ? identifier : matchedIdentifier;\n } else if (identifier.type !== matchedIdentifier.type) {\n keptIdentifier = // @ts-expect-error TODO this needs to be fixed\n 'type' in resourceData && identifier.type === resourceData.type ? identifier : matchedIdentifier;\n }\n const staleIdentifier = identifier === keptIdentifier ? matchedIdentifier : identifier;\n\n // check for duplicate entities\n const keptHasRecord = this.__instances.record.has(keptIdentifier);\n const staleHasRecord = this.__instances.record.has(staleIdentifier);\n\n // we cannot merge entities when both have records\n // (this may not be strictly true, we could probably swap the cache data the record points at)\n if (keptHasRecord && staleHasRecord) {\n // TODO we probably don't need to throw these errors anymore\n // we can probably just \"swap\" what data source the abandoned\n // record points at so long as\n // it itself is not retained by the store in any way.\n // @ts-expect-error TODO this needs to be fixed\n if ('id' in resourceData) {\n throw new Error(\n `Failed to update the 'id' for the ResourceKey '${identifier.type}:${String(identifier.id)} (${\n identifier.lid\n })' to '${String(resourceData.id)}', because that id is already in use by '${\n matchedIdentifier.type\n }:${String(matchedIdentifier.id)} (${matchedIdentifier.lid})'`\n );\n }\n\n assert(\n `Failed to update the ResourceKey '${identifier.type}:${String(identifier.id)} (${\n identifier.lid\n })' to merge with the detected duplicate identifier '${matchedIdentifier.type}:${String(\n matchedIdentifier.id\n )} (${String(matchedIdentifier.lid)})'`\n );\n }\n\n this.store.cache.patch({\n op: 'mergeIdentifiers',\n record: staleIdentifier,\n value: keptIdentifier,\n });\n\n /*\n TODO @runspired consider adding this to make polymorphism even nicer\n if (identifier.type !== matchedIdentifier.type) {\n this.store._graph?.registerPolymorphicType(identifier.type, matchedIdentifier.type);\n }\n */\n\n this.unloadRecord(staleIdentifier);\n return keptIdentifier;\n }\n );\n }\n /** Returns the materialized record instance for the given {@link ResourceKey} if one exists, without creating one. */\n peek(identifier: ResourceKey): Cache | OpaqueRecordInstance | undefined {\n return this.__instances.record.get(identifier);\n }\n\n /** Returns the {@link ReactiveDocument} for the given {@link RequestKey}, creating and caching an empty one if none exists yet. */\n getDocument<T>(identifier: RequestKey): ReactiveDocument<T> {\n let doc = this.__instances.document.get(identifier);\n if (!doc) {\n doc = createReactiveDocument<T>(this.store, identifier, null);\n this.__instances.document.set(identifier, doc);\n }\n return doc as ReactiveDocument<T>;\n }\n\n /** Returns the materialized record instance for the given {@link ResourceKey}, instantiating one via the {@link Store} if it does not already exist. */\n getRecord(identifier: ResourceKey): OpaqueRecordInstance {\n let record = this.__instances.record.get(identifier);\n\n if (!record) {\n record = _createRecord(this, identifier, {});\n }\n\n return record;\n }\n\n /**\n * Determines whether the record for the given {@link ResourceKey} is considered loaded.\n *\n * New records are always considered loaded unless they have been deleted. Existing\n * records are considered loaded so long as they are not empty (e.g. after being\n * unloaded), or, when `filterDeleted` is `true`, so long as their deletion has not\n * been committed.\n */\n recordIsLoaded(identifier: ResourceKey, filterDeleted = false): boolean {\n const cache = this.cache;\n if (!cache) {\n return false;\n }\n const isNew = cache.isNew(identifier);\n const isEmpty = cache.isEmpty(identifier);\n\n // if we are new we must consider ourselves loaded\n if (isNew) {\n return !cache.isDeleted(identifier);\n }\n // even if we have a past request, if we are now empty we are not loaded\n // typically this is true after an unloadRecord call\n\n // if we are not empty, not new && we have a fulfilled request then we are loaded\n // we should consider allowing for something to be loaded that is simply \"not empty\".\n // which is how RecordState currently handles this case; however, RecordState is buggy\n // in that it does not account for unloading.\n return filterDeleted && cache.isDeletionCommitted(identifier) ? false : !isEmpty;\n }\n\n /**\n * Fully removes a {@link ResourceKey} from the store: forgets it from the graph and\n * the store's cache key manager, clears its pending request state, and removes it\n * from {@link StoreMap}.\n *\n * Expects that any materialized record for the identifier has already been destroyed.\n */\n disconnect(identifier: ResourceKey): void {\n const record = this.__instances.record.get(identifier);\n assert(\n 'Cannot destroy record while it is still materialized',\n !isDestroyable(record) || record.isDestroyed || record.isDestroying\n );\n\n this.store._graph?.remove(identifier);\n\n this.store.cacheKeyManager.forgetRecordIdentifier(identifier);\n StoreMap.delete(identifier);\n this.store._requestCache._clearEntries(identifier);\n if (LOG_INSTANCE_CACHE) {\n log('reactive-ui', '', identifier.type, identifier.lid, 'disconnected', '');\n }\n }\n\n /**\n * Unloads the record for the given {@link ResourceKey}: tears down its materialized\n * instance (if any) and removes its data from the underlying {@link Cache}, disconnecting\n * the identifier entirely if there is no cache to own it.\n *\n * Asserts that no mutation request is currently in flight for the record.\n */\n unloadRecord(identifier: ResourceKey): void {\n if (DEBUG) {\n const requests = this.store.getRequestStateService().getPendingRequestsForRecord(identifier);\n if (\n requests.some((req) => {\n return req.type === 'mutation';\n })\n ) {\n assert(`You can only unload a record which is not inFlight. '${String(identifier)}'`);\n }\n }\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(`InstanceCache: unloading record for ${String(identifier)}`);\n }\n\n // TODO is this join still necessary?\n this.store._join(() => {\n unloadRecord(this, identifier);\n });\n }\n\n /** Unloads all records, or, when `type` is provided, only those records of that resource type. */\n clear(type?: string): void {\n const cache = this.store.cacheKeyManager._cache;\n if (type === undefined) {\n // it would be cool if we could just de-ref cache here\n // but probably would require WeakRef models to do so.\n cache.resources.forEach((identifier) => {\n this.unloadRecord(identifier);\n });\n } else {\n const typeCache = cache.resourcesByType;\n const identifiers = typeCache[type]?.lid;\n if (identifiers) {\n identifiers.forEach((identifier) => {\n // if (rds.has(identifier)) {\n this.unloadRecord(identifier);\n // }\n // TODO we don't remove the identifier, should we?\n });\n }\n }\n }\n\n /**\n * Updates the `id` for a {@link ResourceKey} that did not previously have one, e.g. after\n * a newly created record has been saved to the server, and notifies subscribers of the\n * identity change.\n */\n // TODO this should move into something coordinating operations\n setRecordId(identifier: ResourceKey, id: string): void {\n const { type, lid } = identifier;\n const oldId = identifier.id;\n\n // ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record)\n assert(\n `'${type}' was saved to the server, but the response does not have an id and your record does not either.`,\n !(id === null && oldId === null)\n );\n\n // ID absolutely can't be different than oldID if oldID is not null\n // TODO this assertion and restriction may not strictly be needed in the identifiers world\n assert(\n `Cannot update the id for '${type}:${lid}' from '${String(oldId)}' to '${id}'.`,\n !(oldId !== null && id !== oldId)\n );\n\n // ID can be null if oldID is not null (altered ID in response for a record)\n // however, this is more than likely a developer error.\n if (oldId !== null && id === null) {\n warn(\n `Your ${type} record was saved to the server, but the response does not have an id.`,\n !(oldId !== null && id === null)\n );\n return;\n }\n\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: updating id to '${id}' for record ${String(identifier)}`);\n }\n\n const existingIdentifier = this.store.cacheKeyManager.peekResourceKey({ type, id });\n assert(\n `'${type}' was saved to the server, but the response returned the new id '${id}', which has already been used with another record.'`,\n !existingIdentifier || existingIdentifier === identifier\n );\n\n if (identifier.id === null) {\n // TODO potentially this needs to handle merged result\n this.store.cacheKeyManager.updateRecordIdentifier(identifier, { type, id });\n }\n\n // TODO update resource cache if needed ?\n // TODO handle consequences of identifier merge for notifications\n this.store.notifications.notify(identifier, 'identity', null);\n }\n}\n\nexport function getNewRecord(\n instances: InstanceCache,\n identifier: ResourceKey,\n properties: CreateRecordProperties\n): OpaqueRecordInstance {\n let record = instances.__instances.record.get(identifier);\n\n if (!record) {\n record = _createRecord(instances, identifier, properties);\n\n if (record instanceof ReactiveResource && instances.store.schema.resource) {\n // this is a work around until we introduce a new async createRecord API\n const schema = instances.store.schema.resource(identifier) as ResourceSchema;\n if (!schema.legacy) {\n const editable = _CHECKOUT(record);\n if (properties) {\n Object.assign(editable, properties);\n }\n return editable;\n }\n }\n }\n\n return record;\n}\n\nfunction _createRecord(\n instances: InstanceCache,\n identifier: ResourceKey,\n properties: CreateRecordProperties\n): OpaqueRecordInstance {\n assert(\n `Cannot create a new record instance while the store is being destroyed`,\n !instances.store.isDestroying && !instances.store.isDestroyed\n );\n\n const record = instances.store.instantiateRecord(identifier, properties);\n\n setRecordIdentifier(record, identifier);\n StoreMap.set(record, instances.store);\n instances.__instances.record.set(identifier, record);\n\n if (LOG_INSTANCE_CACHE) {\n logGroup('reactive-ui', '', identifier.type, identifier.lid, 'created', '');\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n\n return record;\n}\n\n/**\n * Resets the module-level record-to-identifier and record/identifier-to-store lookup\n * caches used by {@link recordIdentifierFor} and {@link storeFor}.\n *\n * Leaked for test and legacy use only; not intended for application use.\n *\n * @private\n */\nexport function _clearCaches(): void {\n RecordCache.clear();\n StoreMap.clear();\n}\n\nfunction unloadRecord(instances: InstanceCache, identifier: ResourceKey) {\n const record = instances.__instances.record.get(identifier);\n const cache = instances.cache;\n\n if (record) {\n instances.store.teardownRecord(record);\n instances.__instances.record.delete(identifier);\n StoreMap.delete(record);\n RecordCache.delete(record);\n\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: destroyed record for ${String(identifier)}`);\n }\n }\n\n if (cache) {\n cache.unloadRecord(identifier);\n StoreMap.delete(identifier);\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: destroyed cache for ${String(identifier)}`);\n }\n } else {\n instances.disconnect(identifier);\n }\n\n instances.store._requestCache._clearEntries(identifier);\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: unloaded RecordData for ${String(identifier)}`);\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n}\n","import type { Cache, ChangedAttributesHash, RelationshipDiff } from '../../../types/cache.ts';\nimport type { Change } from '../../../types/cache/change.ts';\nimport type { Operation } from '../../../types/cache/operations.ts';\nimport type { CollectionRelationship, ResourceRelationship } from '../../../types/cache/relationship.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { Value } from '../../../types/json/raw.ts';\nimport type { StructuredDataDocument, StructuredDocument } from '../../../types/request.ts';\nimport type {\n CollectionResourceDataDocument,\n ResourceDocument,\n SingleResourceDataDocument,\n} from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { StoreRequestContext } from '../cache-handler/handler.ts';\n\n/**\n * The CacheManager wraps a Cache enforcing that only\n * the public API surface area is exposed.\n *\n * Hence, it is the value of `Store.cache`, wrapping\n * the cache instance returned by `Store.createCache`.\n *\n * It handles translating between cache versions when\n * necessary, for instance when a Store is configured\n * to use both a v1 and a v2 cache depending on some\n * heuristic.\n *\n * Starting with the v2 spec, the cache is designed such\n * that it must be implemented as a singleton.\n *\n * @class CacheManager\n * @public\n */\nexport class CacheManager implements Cache {\n version = '2' as const;\n\n /** @internal */\n declare private ___cache: Cache;\n\n constructor(cache: Cache) {\n this.___cache = cache;\n }\n\n // Cache Management\n // ================\n\n /**\n * Cache the response to a request\n *\n * Unlike `store.push` which has UPSERT\n * semantics, `put` has `replace` semantics similar to\n * the `http` method `PUT`\n *\n * the individually cacheable\n * e resource data it may contain\n * should upsert, but the document data surrounding it should\n * fully replace any existing information\n *\n * Note that in order to support inserting arbitrary data\n * to the cache that did not originate from a request `put`\n * should expect to sometimes encounter a document with only\n * a `content` member and therefor must not assume the existence\n * of `request` and `response` on the document.\n *\n * @public\n */\n put<T>(doc: StructuredDocument<T> | { content: T }): ResourceDocument {\n return this.___cache.put(doc);\n }\n\n /**\n * Perform an operation on the cache to update the remote state.\n *\n * @public\n * @param op the operation to perform\n */\n patch(op: Operation | Operation[]): void {\n this.___cache.patch(op);\n }\n\n /**\n * Update resource data with a local mutation. Currently supports operations\n * on relationships only.\n *\n * @public\n */\n mutate(mutation: LocalRelationshipOperation): void {\n this.___cache.mutate(mutation);\n }\n\n /**\n * Peek resource data from the Cache.\n *\n * In development, if the return value\n * is JSON the return value\n * will be deep-cloned and deep-frozen\n * to prevent mutation thereby enforcing cache\n * Immutability.\n *\n * This form of peek is useful for implementations\n * that want to feed raw-data from cache to the UI\n * or which want to interact with a blob of data\n * directly from the presentation cache.\n *\n * An implementation might want to do this because\n * de-referencing records which read from their own\n * blob is generally safer because the record does\n * not require retaining connections to the Store\n * and Cache to present data on a per-field basis.\n *\n * This generally takes the place of `getAttr` as\n * an API and may even take the place of `getRelationship`\n * depending on implementation specifics, though this\n * latter usage is less recommended due to the advantages\n * of the Graph handling necessary entanglements and\n * notifications for relational data.\n *\n * @public\n * @return the known resource data\n */\n peek(cacheKey: ResourceKey): unknown;\n peek(cacheKey: RequestKey): ResourceDocument | null;\n peek(cacheKey: ResourceKey | RequestKey): unknown {\n return this.___cache.peek(cacheKey as ResourceKey);\n }\n\n peekRemoteState(cacheKey: ResourceKey): unknown;\n peekRemoteState(cacheKey: RequestKey): ResourceDocument | null;\n peekRemoteState(cacheKey: ResourceKey | RequestKey): unknown {\n return this.___cache.peekRemoteState(cacheKey as ResourceKey);\n }\n /**\n * Peek the Cache for the existing request data associated with\n * a cacheable request\n *\n * @public\n */\n peekRequest(key: RequestKey): StructuredDocument<ResourceDocument> | null {\n return this.___cache.peekRequest(key);\n }\n\n /**\n * Push resource data from a remote source into the cache for this ResourceKey\n *\n * @public\n * @return if `hasRecord` is true then calculated key changes should be returned\n */\n upsert(key: ResourceKey, data: unknown, hasRecord: boolean): void | string[] {\n return this.___cache.upsert(key, data, hasRecord);\n }\n\n // Cache Forking Support\n // =====================\n\n /**\n * Create a fork of the cache from the current state.\n *\n * Applications should typically not call this method themselves,\n * preferring instead to fork at the Store level, which will\n * utilize this method to fork the cache.\n *\n * @public\n */\n fork(): Promise<Cache> {\n return this.___cache.fork();\n }\n\n /**\n * Merge a fork back into a parent Cache.\n *\n * Applications should typically not call this method themselves,\n * preferring instead to merge at the Store level, which will\n * utilize this method to merge the caches.\n *\n * @public\n */\n merge(cache: Cache): Promise<void> {\n return this.___cache.merge(cache);\n }\n\n /**\n * Generate the list of changes applied to all\n * record in the store.\n *\n * Each individual resource or document that has\n * been mutated should be described as an individual\n * `Change` entry in the returned array.\n *\n * A `Change` is described by an object containing up to\n * three properties: (1) the `ResourceKey` of the entity that\n * changed; (2) the `op` code of that change being one of\n * `upsert` or `remove`, and if the op is `upsert` a `patch`\n * containing the data to merge into the cache for the given\n * entity.\n *\n * This `patch` is opaque to the Store but should be understood\n * by the Cache and may expect to be utilized by an Adapter\n * when generating data during a `save` operation.\n *\n * It is generally recommended that the `patch` contain only\n * the updated state, ignoring fields that are unchanged\n *\n * ```ts\n * interface Change {\n * key: ResourceKey | RequestKey;\n * op: 'upsert' | 'remove';\n * patch?: unknown;\n * }\n * ```\n *\n * @public\n */\n diff(): Promise<Change[]> {\n return this.___cache.diff();\n }\n\n // SSR Support\n // ===========\n\n /**\n * Serialize the entire contents of the Cache into a Stream\n * which may be fed back into a new instance of the same Cache\n * via `cache.hydrate`.\n *\n * @public\n */\n dump(): Promise<ReadableStream<unknown>> {\n return this.___cache.dump();\n }\n\n /**\n * hydrate a Cache from a Stream with content previously serialized\n * from another instance of the same Cache, resolving when hydration\n * is complete.\n *\n * This method should expect to be called both in the context of restoring\n * the Cache during application rehydration after SSR **AND** at unknown\n * times during the lifetime of an already booted application when it is\n * desired to bulk-load additional information into the cache. This latter\n * behavior supports optimizing pre/fetching of data for route transitions\n * via data-only SSR modes.\n *\n * @public\n */\n hydrate(stream: ReadableStream<unknown>): Promise<void> {\n return this.___cache.hydrate(stream);\n }\n\n // Cache\n // =====\n\n // Resource Support\n // ================\n\n /**\n * [LIFECYCLE] Signal to the cache that a new record has been instantiated on the client\n *\n * It returns properties from options that should be set on the record during the create\n * process. This return value behavior is deprecated.\n *\n * @public\n */\n clientDidCreate(key: ResourceKey, options?: Record<string, unknown>): Record<string, unknown> {\n return this.___cache.clientDidCreate(key, options);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * will be part of a save transaction.\n *\n * @public\n * @param key\n */\n willCommit(key: ResourceKey | ResourceKey[], context: StoreRequestContext): void {\n this.___cache.willCommit(key, context);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * was successfully updated as part of a save transaction.\n *\n * @public\n */\n didCommit(\n key: ResourceKey,\n result: StructuredDataDocument<SingleResourceDataDocument> | null\n ): SingleResourceDataDocument;\n didCommit(\n key: ResourceKey[],\n result: StructuredDataDocument<SingleResourceDataDocument> | null\n ): SingleResourceDataDocument;\n didCommit(\n key: ResourceKey[],\n result: StructuredDataDocument<CollectionResourceDataDocument> | null\n ): CollectionResourceDataDocument;\n didCommit(\n key: ResourceKey | ResourceKey[],\n result: StructuredDataDocument<SingleResourceDataDocument | CollectionResourceDataDocument> | null\n ): CollectionResourceDataDocument | SingleResourceDataDocument {\n // @ts-expect-error TS doesn't enable proxying overload calls\n return this.___cache.didCommit(key, result);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * was update via a save transaction failed.\n *\n * @public\n */\n commitWasRejected(key: ResourceKey | ResourceKey[], errors?: ApiError[]): void {\n this.___cache.commitWasRejected(key, errors);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that all data for a resource\n * should be cleared.\n *\n * @public\n */\n unloadRecord(key: ResourceKey): void {\n this.___cache.unloadRecord(key);\n }\n\n // Granular Resource Data APIs\n // ===========================\n\n /**\n * Retrieve the data for an attribute from the cache\n *\n * @public\n */\n getAttr(key: ResourceKey, propertyName: string): Value | undefined {\n return this.___cache.getAttr(key, propertyName);\n }\n\n /**\n * Retrieve the remote state for an attribute from the cache\n *\n * @public\n */\n getRemoteAttr(key: ResourceKey, propertyName: string): Value | undefined {\n return this.___cache.getRemoteAttr(key, propertyName);\n }\n\n /**\n * Mutate the data for an attribute in the cache\n *\n * @public\n */\n setAttr(key: ResourceKey, propertyName: string, value: Value): void {\n this.___cache.setAttr(key, propertyName, value);\n }\n\n /**\n * Query the cache for the changed attributes of a resource.\n *\n * @public\n */\n changedAttrs(key: ResourceKey): ChangedAttributesHash {\n return this.___cache.changedAttrs(key);\n }\n\n /**\n * Query the cache for whether any mutated attributes exist\n *\n * @public\n */\n hasChangedAttrs(key: ResourceKey): boolean {\n return this.___cache.hasChangedAttrs(key);\n }\n\n /**\n * Tell the cache to discard any uncommitted mutations to attributes\n *\n * @public\n * @return the names of attributes that were restored\n */\n rollbackAttrs(key: ResourceKey): string[] {\n return this.___cache.rollbackAttrs(key);\n }\n\n // Relationships\n // =============\n\n /**\n * Query the cache for the changes to relationships of a resource.\n *\n * Returns a map of relationship names to RelationshipDiff objects.\n *\n * ```ts\n * type RelationshipDiff =\n | {\n kind: 'collection';\n remoteState: ResourceKey[];\n additions: Set<ResourceKey>;\n removals: Set<ResourceKey>;\n localState: ResourceKey[];\n reordered: boolean;\n }\n | {\n kind: 'resource';\n remoteState: ResourceKey | null;\n localState: ResourceKey | null;\n };\n ```\n *\n * @public\n */\n changedRelationships(key: ResourceKey): Map<string, RelationshipDiff> {\n return this.___cache.changedRelationships(key);\n }\n\n /**\n * Query the cache for whether any mutated attributes exist\n *\n * @public\n */\n hasChangedRelationships(key: ResourceKey): boolean {\n return this.___cache.hasChangedRelationships(key);\n }\n\n /**\n * Tell the cache to discard any uncommitted mutations to relationships.\n *\n * This will also discard the change on any appropriate inverses.\n *\n * This method is a candidate to become a mutation\n *\n * @public\n * @return the names of relationships that were restored\n */\n rollbackRelationships(key: ResourceKey): string[] {\n return this.___cache.rollbackRelationships(key);\n }\n\n /**\n * Query the cache for the current state of a relationship property\n *\n * @public\n * @return resource relationship object\n */\n getRelationship(key: ResourceKey, propertyName: string): ResourceRelationship | CollectionRelationship {\n return this.___cache.getRelationship(key, propertyName);\n }\n\n /**\n * Query the cache for the remote state of a relationship property\n *\n * @public\n * @return resource relationship object\n */\n getRemoteRelationship(key: ResourceKey, propertyName: string): ResourceRelationship | CollectionRelationship {\n return this.___cache.getRemoteRelationship(key, propertyName);\n }\n\n // Resource State\n // ===============\n\n /**\n * Update the cache state for the given resource to be marked as locally deleted,\n * or remove such a mark.\n *\n * @public\n */\n setIsDeleted(key: ResourceKey, isDeleted: boolean): void {\n this.___cache.setIsDeleted(key, isDeleted);\n }\n\n /**\n * Query the cache for any validation errors applicable to the given resource.\n *\n * @public\n */\n getErrors(key: ResourceKey): ApiError[] {\n return this.___cache.getErrors(key);\n }\n\n /**\n * Query the cache for whether a given resource has any available data\n *\n * @public\n */\n isEmpty(key: ResourceKey): boolean {\n return this.___cache.isEmpty(key);\n }\n\n /**\n * Query the cache for whether a given resource was created locally and not\n * yet persisted.\n *\n * @public\n */\n isNew(key: ResourceKey): boolean {\n return this.___cache.isNew(key);\n }\n\n /**\n * Query the cache for whether a given resource is marked as deleted (but not\n * necessarily persisted yet).\n *\n * @public\n */\n isDeleted(key: ResourceKey): boolean {\n return this.___cache.isDeleted(key);\n }\n\n /**\n * Query the cache for whether a given resource has been deleted and that deletion\n * has also been persisted.\n *\n * @public\n */\n isDeletionCommitted(key: ResourceKey): boolean {\n return this.___cache.isDeletionCommitted(key);\n }\n}\n","import { LOG_METRIC_COUNTS, LOG_NOTIFICATIONS } from '@warp-drive/core/build-config/debugging';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { willSyncFlushWatchers } from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport { log } from '../debug/utils.ts';\nimport type { Store } from '../store-service.ts';\nimport { isRequestKey, isResourceKey } from './cache-key-manager.ts';\n\nexport type UnsubscribeToken = object;\n\n/**\n * The kinds of change notifications the {@link NotificationManager} can emit for a resource.\n */\nexport type CacheOperation = 'added' | 'removed' | 'updated' | 'state';\n/**\n * The kinds of change notifications the {@link NotificationManager} can emit for a request document.\n */\nexport type DocumentCacheOperation = 'invalidated' | 'added' | 'removed' | 'updated' | 'state';\n\nfunction isCacheOperationValue(value: NotificationType | DocumentCacheOperation): value is DocumentCacheOperation {\n return (\n value === 'added' || value === 'state' || value === 'updated' || value === 'removed' || value === 'invalidated'\n );\n}\n\n/**\n * The full set of notification kinds the {@link NotificationManager} can emit for a resource,\n * including both {@link CacheOperation}s and finer-grained field-level change notifications.\n */\nexport type NotificationType = 'attributes' | 'relationships' | 'identity' | 'errors' | 'meta' | CacheOperation;\n\n/**\n * The shape accepted by {@link NotificationManager.notify} and\n * {@link CacheCapabilitiesManager.notifyChange} for delivering many keys for\n * the `'attributes'` or `'relationships'` namespaces in a single call\n * instead of once per key.\n *\n * @since 5.9.0\n * @public\n */\nexport type NotifyKeys = Set<string>;\n\n/**\n * A change to a resource's `attributes` or `relationships` can be relevant to\n * a \"local\" view of the resource (its mutable/editable state), a \"remote\" view\n * (its last-known-persisted state), or both.\n *\n * Each view subscribes to its own channel and, when notified, re-pulls its own\n * projection of the data: a remote-only reader (e.g. PolarisMode's default\n * immutable record) subscribes `'remote'` and re-reads remote state; an\n * editable/reconciled reader (a legacy record, or an editable checkout)\n * subscribes `'local'` (the same as omitting the channel) and re-reads local\n * state. A notifier that knows which projection changed tags the notification\n * with that channel; each tag is delivered only to that channel's subscribers.\n * A change affecting both projections is either notified unscoped or once per\n * channel. An unscoped notify cannot guarantee which view changed, so it\n * reaches every subscriber -- this keeps every pre-channel `notify` callsite\n * (and any custom cache that doesn't know about channels) fully compatible.\n *\n * The full delivery matrix:\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * Channel only applies to the `'attributes'` and `'relationships'`\n * notification types. All other types (`'errors'`,\n * `'identity'`, `'state'`, and the various `CacheOperation`/\n * `DocumentCacheOperation` values) are never filtered by channel since they\n * have no local/remote duality.\n *\n * @public\n */\nexport type NotificationChannel = 'local' | 'remote';\n\n/**\n * Well-known sentinel recorded in a {@link ChannelSet} for a touch that\n * carried no channel. An unscoped touch always reaches every subscriber\n * regardless of what channel(s) the same key was also touched with, so its\n * presence in the set short-circuits channel filtering.\n */\nconst UnscopedChannel: '___(unique) Symbol(UnscopedChannel)' = getOrSetGlobal('UnscopedChannel', Symbol('unscoped'));\n\n/**\n * The set of channels (if any) a given `'attributes'`/`'relationships'` touch\n * was tagged with while buffered. {@link UnscopedChannel} is included in this\n * set when at least one of the coalesced touches was itself unscoped (no\n * channel given).\n */\ntype ChannelSet = Set<NotificationChannel | typeof UnscopedChannel>;\n\nexport interface NotificationCallback {\n (cacheKey: ResourceKey, notificationType: 'attributes' | 'relationships', key?: string): void;\n (cacheKey: ResourceKey, notificationType: 'errors' | 'meta' | 'identity' | 'state'): void;\n (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n // (cacheKey: ResourceKey, notificationType: NotificationType, key?: string): void;\n}\n\nexport interface ResourceOperationCallback {\n // resource updates\n (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n}\n\nexport interface DocumentOperationCallback {\n // document updates\n (cacheKey: RequestKey, notificationType: DocumentCacheOperation): void;\n}\n\nfunction keyToString(key: string | NotifyKeys | null | undefined): string {\n return key instanceof Set ? Array.from(key).join(', ') : key || '';\n}\n\n/**\n * Merges an incoming `notify()` call for a single identifier into that\n * identifier's pending-notifications buffer, coalescing redundant work within\n * a single flush window.\n *\n * The buffer is a `Map` from namespace (`'attributes'`, `'relationships'`,\n * `'state'`, etc.) to a \"bucket\". Using a `Map` means the *first* time a\n * namespace is touched during this flush window fixes its position in\n * iteration order; every subsequent touch to that same namespace (regardless\n * of how much later, or how many other namespaces fired in between) updates\n * its value in place without moving it. This preserves the relative order in\n * which *different* namespaces first fired, while intentionally not tracking\n * the arrival order of repeated touches to the *same* namespace - those are\n * provably safe to coalesce because subscribers never receive anything about\n * a notification beyond `(cacheKey, type, key?)`.\n *\n * For every namespace other than `'attributes'`/`'relationships'`, subscriber\n * callbacks never receive a key at all (and channel never applies to them -\n * see {@link NotificationChannel}), so the bucket is simply `null`, used\n * purely as a \"this namespace fired at least once\" presence marker; multiple\n * firings within one flush all collapse to the same single marker.\n *\n * For `'attributes'`/`'relationships'`, a key (or channel) *does* matter, so\n * the bucket is one of:\n * - a `Map<string, ChannelSet>`: the normal case, mapping each specific key\n * touched to the set of channels it was touched with ({@link UnscopedChannel}\n * in that set means at least one of those touches was itself unscoped).\n * - a `ChannelSet` directly: a wildcard meaning \"an unspecified set of keys\n * changed\" - a strict superset of any specific key list, per the existing\n * contract of {@link CacheCapabilitiesManager.notifyChange} - tagged with\n * the set of channels any of the coalesced keyless (or post-wildcard\n * keyed) touches carried.\n *\n * A keyless call always upgrades the bucket to the wildcard form. When\n * upgrading away from a `Map`, every channel ever recorded against any of\n * its specific keys is folded into the new wildcard `ChannelSet` - the\n * wildcard must remain a superset not just key-wise but channel-wise too, or\n * a channel-scoped subscriber that would have heard about one of those\n * specific keys could silently stop hearing about it once the bucket flips\n * to wildcard. Once a bucket is a wildcard it can never downgrade back to a\n * `Map`; a keyed touch that arrives after that point still folds its channel\n * into the wildcard's `ChannelSet` (the specific key itself is discarded,\n * since the wildcard already covers it).\n */\nfunction mergeIntoBuffer(\n buffer: Map<NotificationType | DocumentCacheOperation, Map<string, ChannelSet> | ChannelSet | null>,\n value: NotificationType | CacheOperation | DocumentCacheOperation,\n key: string | NotifyKeys | null | undefined,\n channel: NotificationChannel | undefined\n): void {\n if (value !== 'attributes' && value !== 'relationships') {\n // presence-only namespaces: multiple firings within one flush are\n // lossless to coalesce into a single marker.\n buffer.set(value, null);\n return;\n }\n\n const existing = buffer.get(value) as Map<string, ChannelSet> | ChannelSet | undefined;\n\n if (key === null || key === undefined) {\n // a keyless call is a wildcard: fold this touch's channel (and, if\n // upgrading from a keyed Map, every channel ever recorded against any of\n // its specific keys) into the wildcard ChannelSet.\n const channels: ChannelSet = existing instanceof Set ? existing : new Set();\n if (existing instanceof Map) {\n for (const channelsForKey of existing.values()) {\n for (const ch of channelsForKey) channels.add(ch);\n }\n }\n channels.add(channel ?? UnscopedChannel);\n buffer.set(value, channels);\n return;\n }\n\n if (existing instanceof Set) {\n // already a wildcard: specific keys can never downgrade it back to a\n // Map, but this touch's channel still needs to be folded in.\n existing.add(channel ?? UnscopedChannel);\n return;\n }\n\n const map = existing ?? new Map<string, ChannelSet>();\n if (!existing) {\n buffer.set(value, map);\n }\n\n const keys = key instanceof Set ? key : [key];\n for (const k of keys) {\n let channels = map.get(k);\n if (!channels) {\n channels = new Set();\n map.set(k, channels);\n }\n channels.add(channel ?? UnscopedChannel);\n }\n}\n\n/**\n * Given the set of channels a touch (or coalesced group of touches) was\n * recorded with, determines whether a subscriber scoped to `subscriberChannel`\n * should be delivered to (see the delivery matrix on\n * {@link NotificationChannel}): a subscriber hears a touch-set if any of its\n * touches was unscoped or tagged with the subscriber's own channel; a\n * touch-set exclusively tagged with the *other* channel is skipped.\n */\nfunction shouldDeliverToChannel(channels: ChannelSet, subscriberChannel: NotificationChannel): boolean {\n return channels.has(UnscopedChannel) || channels.has(subscriberChannel);\n}\n\nfunction count(label: string) {\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[label] = (globalThis.__WarpDriveMetricCountData[label] || 0) + 1;\n}\n\nfunction asInternalToken(token: unknown): asserts token is {\n for: RequestKey | ResourceKey | 'resource' | 'document';\n} & (NotificationCallback | ResourceOperationCallback | DocumentOperationCallback) {\n assert(`Expected a token with a 'for' property`, token && typeof token === 'function' && 'for' in token);\n}\n\nfunction _unsubscribe(\n token: UnsubscribeToken,\n cache: Map<\n 'resource' | 'document' | RequestKey | ResourceKey,\n Array<NotificationCallback | ResourceOperationCallback | DocumentOperationCallback>\n >\n) {\n asInternalToken(token);\n const cacheKey = token.for;\n if (LOG_NOTIFICATIONS) {\n if (!cacheKey) {\n // oxlint-disable-next-line no-console\n console.log('Passed unknown unsubscribe token to unsubscribe', cacheKey);\n }\n }\n if (cacheKey) {\n const callbacks = cache.get(cacheKey);\n if (!callbacks) {\n return;\n }\n\n const index = callbacks.indexOf(token);\n if (index === -1) {\n assert(`Cannot unsubscribe a token that is not subscribed`, index !== -1);\n return;\n }\n\n callbacks.splice(index, 1);\n }\n}\n\n/**\n * The NotificationManager provides the ability to subscribe to\n * changes to Cache state.\n *\n * This Feature is what allows WarpDrive to create subscriptions that\n * work with any framework or change-notification system.\n *\n * @hideconstructor\n * @public\n */\nexport class NotificationManager {\n /** @internal */\n declare private store: Store;\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _buffered: Map<\n RequestKey | ResourceKey,\n Map<NotificationType | DocumentCacheOperation, Map<string, ChannelSet> | ChannelSet | null>\n >;\n /** @internal */\n declare private _cache: Map<\n RequestKey | ResourceKey | 'resource' | 'document',\n Array<NotificationCallback | ResourceOperationCallback | DocumentOperationCallback>\n >;\n /** @internal */\n declare private _hasFlush: boolean;\n /** @internal */\n declare private _onFlushCB?: () => void;\n\n constructor(store: Store) {\n this.store = store;\n this.isDestroyed = false;\n this._buffered = new Map();\n this._hasFlush = false;\n this._cache = new Map();\n }\n\n /**\n * Subscribe to changes for a given ResourceKey, RequestKey, or addition/removal of any resource\n * or document.\n *\n * ```ts\n * export type CacheOperation = 'added' | 'removed' | 'updated' | 'state';\n *\n * export interface NotificationCallback {\n * (cacheKey: ResourceKey, notificationType: 'attributes' | 'relationships', key?: string): void;\n * (cacheKey: ResourceKey, notificationType: 'errors' | 'meta' | 'identity' | 'state'): void;\n * (cacheKey: ResourceKey, notificationType: NotificationType, key?: string): void;\n * }\n * export interface ResourceOperationCallback {\n * // resource updates\n * (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n * }\n * export interface DocumentOperationCallback {\n * // document updates\n * (cacheKey: RequestKey, notificationType: CacheOperation): void;\n * }\n * ```\n *\n * A `channel` may be provided when subscribing to a `ResourceKey`. Its\n * effect is that the subscription skips `'attributes'`/`'relationships'`\n * notifications explicitly tagged with the *other* channel; unscoped\n * notifications, and notifications for all other notification types, always\n * reach the subscriber. Subscribing `'local'` and omitting the channel are\n * the same thing. See {@link NotificationChannel}.\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * @public\n * @return an opaque token to be used with unsubscribe\n */\n subscribe(cacheKey: ResourceKey, callback: NotificationCallback, channel?: NotificationChannel): UnsubscribeToken;\n subscribe(cacheKey: 'resource', callback: ResourceOperationCallback): UnsubscribeToken;\n subscribe(cacheKey: 'document' | RequestKey, callback: DocumentOperationCallback): UnsubscribeToken;\n subscribe(\n cacheKey: RequestKey | ResourceKey | 'resource' | 'document',\n callback: NotificationCallback | ResourceOperationCallback | DocumentOperationCallback,\n channel?: NotificationChannel\n ): UnsubscribeToken {\n assert(`Expected not to be destroyed`, !this.isDestroyed);\n assert(\n `Expected to receive a stable Identifier to subscribe to`,\n cacheKey === 'resource' || cacheKey === 'document' || isResourceKey(cacheKey) || isRequestKey(cacheKey)\n );\n let callbacks = this._cache.get(cacheKey);\n assert(`expected to receive a valid callback`, typeof callback === 'function');\n assert(`cannot subscribe with the same callback twice`, !callbacks || !callbacks.includes(callback));\n // we use the callback as the cancellation token\n //@ts-expect-error\n callback.for = cacheKey;\n //@ts-expect-error stashed only for ResourceKey subscriptions; see shouldDeliverToChannel.\n // Defaults to 'local' rather than leaving it unscoped -- see NotificationChannel.\n callback.channel = channel ?? 'local';\n\n if (!callbacks) {\n callbacks = [];\n this._cache.set(cacheKey, callbacks);\n }\n\n callbacks.push(callback);\n return callback;\n }\n\n /**\n * remove a previous subscription\n *\n * @public\n */\n unsubscribe(token: UnsubscribeToken): void {\n if (!this.isDestroyed) {\n _unsubscribe(token, this._cache);\n }\n }\n\n /**\n * Custom Caches and Application Code should not call this method directly.\n *\n * When notifying `'attributes'` or `'relationships'` for many keys on the\n * same `cacheKey` at once (for instance, when a bulk update to a single\n * record touches many fields) `key` may be supplied as a `Set<string>`\n * instead of being called once per key. The `Set` is iterated as-is (it is\n * never converted to or from an array internally). This delivers the\n * exact same sequence of individual notifications to subscribers (each\n * subscriber callback is still invoked once per key, in order) while\n * paying the per-call overhead (validity checks, subscriber lookups,\n * buffer/flush scheduling) only once for the whole batch instead of once\n * per key.\n *\n * A `channel` may be supplied for the `'attributes'`/`'relationships'`\n * namespaces. Tagging a notification `'local'` declares \"only the local\n * (reconciled/editable) view changed\"; tagging it `'remote'` declares \"only\n * the remote view changed\". Each tag is delivered only to that channel's\n * subscribers. Omitting the channel reaches every subscriber regardless of\n * its channel. See {@link NotificationChannel}.\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * @private\n */\n notify(\n cacheKey: ResourceKey,\n value: 'attributes' | 'relationships',\n key?: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): boolean;\n notify(cacheKey: ResourceKey, value: 'errors' | 'meta' | 'identity' | 'state', key?: null): boolean;\n notify(cacheKey: ResourceKey, value: CacheOperation, key?: null): boolean;\n notify(cacheKey: RequestKey, value: DocumentCacheOperation, key?: null): boolean;\n notify(\n cacheKey: ResourceKey | RequestKey,\n value: NotificationType | CacheOperation | DocumentCacheOperation,\n key?: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): boolean {\n if (this.isDestroyed) {\n return false;\n }\n assert(\n `Notify does not accept a key argument for the namespace '${value}'. Received key '${keyToString(key)}'.`,\n !key || value === 'attributes' || value === 'relationships'\n );\n assert(\n `Notify does not accept a channel argument for the namespace '${value}'. Received channel '${channel || ''}'.`,\n !channel || value === 'attributes' || value === 'relationships'\n );\n if (!isResourceKey(cacheKey) && !isRequestKey(cacheKey)) {\n if (LOG_NOTIFICATIONS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Notifying: Expected to receive a stable Identifier to notify '${value}' '${keyToString(\n key\n )}' with, but ${String(cacheKey)} is not in the cache`,\n cacheKey\n );\n }\n return false;\n }\n\n const _hasSubscribers = hasSubscribers(this._cache, cacheKey, value);\n if (_hasSubscribers) {\n let buffer = this._buffered.get(cacheKey);\n if (!buffer) {\n buffer = new Map();\n this._buffered.set(cacheKey, buffer);\n }\n\n mergeIntoBuffer(buffer, value, key, channel);\n\n if (LOG_METRIC_COUNTS) {\n count(`notify ${'type' in cacheKey ? cacheKey.type : '<document>'} ${value} ${keyToString(key)}`);\n }\n\n if (!this._scheduleNotify()) {\n if (LOG_NOTIFICATIONS) {\n log(\n 'notify',\n 'buffered',\n `${'type' in cacheKey ? cacheKey.type : 'document'}`,\n cacheKey.lid,\n `${value}`,\n keyToString(key)\n );\n }\n }\n } else {\n if (LOG_NOTIFICATIONS) {\n log(\n 'notify',\n 'discarded',\n `${'type' in cacheKey ? cacheKey.type : 'document'}`,\n cacheKey.lid,\n `${value}`,\n keyToString(key)\n );\n }\n if (LOG_METRIC_COUNTS) {\n count(`DISCARDED notify ${'type' in cacheKey ? cacheKey.type : '<document>'} ${value} ${keyToString(key)}`);\n }\n }\n\n return _hasSubscribers;\n }\n\n /** @internal */\n _onNextFlush(cb: () => void): void {\n this._onFlushCB = cb;\n }\n\n /** @internal */\n private _scheduleNotify(): boolean {\n const asyncFlush = this.store._enableAsyncFlush;\n\n if (this._hasFlush) {\n if (asyncFlush !== false && !willSyncFlushWatchers()) {\n return false;\n }\n }\n\n if (asyncFlush && !willSyncFlushWatchers()) {\n this._hasFlush = true;\n return false;\n }\n\n this._flush();\n return true;\n }\n\n /** @internal */\n _flush(): void {\n const buffered = this._buffered;\n if (buffered.size) {\n this._buffered = new Map();\n for (const [cacheKey, states] of buffered) {\n // `states` iterates in the order each namespace first fired during\n // this flush window (see `mergeIntoBuffer`).\n for (const [value, bucket] of states) {\n if (bucket === null) {\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, null);\n } else if (bucket instanceof Set) {\n // wildcard: one notification, key `null`, filtered by the union\n // of channels any of the coalesced keyless touches carried.\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, null, bucket);\n } else {\n for (const [key, channels] of bucket) {\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, key, channels);\n }\n }\n }\n }\n }\n\n this._hasFlush = false;\n this._onFlushCB?.();\n this._onFlushCB = undefined;\n }\n\n /** @internal */\n destroy(): void {\n this.isDestroyed = true;\n this._cache.clear();\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateNotificationManager extends NotificationManager {\n _flush(): void;\n}\n\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey,\n value: 'attributes' | 'relationships',\n key: string | null,\n channels?: ChannelSet\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey,\n value: 'errors' | 'meta' | 'identity' | 'state',\n key: null\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey | RequestKey,\n value: CacheOperation,\n key: null\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey | RequestKey,\n value: NotificationType | CacheOperation,\n key: string | null,\n channels?: ChannelSet\n): boolean {\n if (LOG_NOTIFICATIONS) {\n log('notify', '', `${'type' in cacheKey ? cacheKey.type : 'document'}`, cacheKey.lid, `${value}`, key || '');\n }\n\n // TODO for documents this will need to switch based on Identifier kind\n if (isCacheOperationValue(value)) {\n const callbackMap = cache.get(isRequestKey(cacheKey) ? 'document' : 'resource') as Array<\n ResourceOperationCallback | DocumentOperationCallback\n >;\n\n if (callbackMap) {\n callbackMap.forEach((cb: ResourceOperationCallback | DocumentOperationCallback) => {\n (cb as ResourceOperationCallback)(cacheKey as ResourceKey, value);\n });\n }\n }\n\n const callbacks = cache.get(cacheKey);\n if (!callbacks || !callbacks.length) {\n return false;\n }\n callbacks.forEach((cb) => {\n if (channels) {\n // @ts-expect-error channel is stashed on the callback only for ResourceKey subscriptions;\n // always concrete since `subscribe` defaults it to 'local'.\n const subscriberChannel = cb.channel as NotificationChannel;\n if (!shouldDeliverToChannel(channels, subscriberChannel)) {\n return;\n }\n }\n // @ts-expect-error overload doesn't narrow within body\n cb(cacheKey, value, key);\n });\n return true;\n}\n\nfunction hasSubscribers(\n cache: NotificationManager['_cache'],\n cacheKey: RequestKey | ResourceKey,\n value: NotificationType | CacheOperation | DocumentCacheOperation\n): boolean {\n const hasSubscriber = Boolean(cache.get(cacheKey)?.length);\n\n if (hasSubscriber || !isCacheOperationValue(value)) {\n return hasSubscriber;\n }\n\n const callbackMap = cache.get(isRequestKey(cacheKey) ? 'document' : 'resource') as Array<\n ResourceOperationCallback | DocumentOperationCallback\n >;\n return Boolean(callbackMap?.length);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { Context } from '../../../reactive/-private';\nimport type { BaseFinderOptions } from '../../../types';\nimport type { LocalRelationshipOperation } from '../../../types/graph';\nimport type { ResourceKey } from '../../../types/identifier';\nimport type { Store } from '../store-service';\nimport type { NativeProxy } from './native-proxy-type-fix';\nimport type { ReactiveResourceArray } from './resource-array';\n\n/**\n * LegacyArrays have the capability of updating via `array.update()`\n * and saving each contained record individually via `array.save()`\n */\nexport interface LegacyArray<T = unknown> extends ReactiveResourceArray<T> {\n /**\n The flag to signal a `RecordArray` is currently loading data.\n Example\n ```javascript\n let people = store.peekAll('person');\n people.isUpdating; // false\n people.update();\n people.isUpdating; // true\n ```\n */\n isUpdating: boolean;\n /** @internal */\n _updatingPromise: Promise<LegacyArray<T>> | null;\n\n /**\n Used to get the latest version of all of the records in this array\n from the adapter.\n\n Example\n\n ```javascript\n let people = store.peekAll('person');\n people.isUpdating; // false\n\n people.update().then(function() {\n people.isUpdating; // false\n });\n\n people.isUpdating; // true\n ```\n\n @public\n */\n update(this: LegacyArray<T>): Promise<LegacyArray<T>>;\n\n /**\n Saves all of the records in the `RecordArray`.\n\n Example\n\n ```js\n let messages = store.peekAll('message');\n messages.forEach(function(message) {\n message.hasBeenSeen = true;\n });\n messages.save();\n ```\n\n @public\n */\n save(this: LegacyArray<T>): Promise<LegacyArray<T>>;\n}\n\nexport function upgradeThis(obj: unknown): asserts obj is LegacyArray {}\n\nexport function update(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n if (this.isUpdating) {\n return this._updatingPromise!;\n }\n\n this.isUpdating = true;\n\n // @ts-expect-error\n // oxlint-disable-next-line typescript/no-unsafe-call\n const updatingPromise = this._update() as Promise<IdentifierArray>;\n void updatingPromise.finally(() => {\n this._updatingPromise = null;\n if (this.isDestroying || this.isDestroyed) {\n return;\n }\n this.isUpdating = false;\n });\n\n this._updatingPromise = updatingPromise;\n\n return updatingPromise;\n}\n\nexport function save(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n\n const context = this[Context];\n const promise = Promise.all(this.map((record) => context.store.saveRecord(record))).then(() => this);\n\n return promise;\n}\n\nexport type KeyType = string | symbol | number;\nconst ARRAY_GETTER_METHODS = new Set<KeyType>([\n Symbol.iterator,\n 'concat',\n 'entries',\n 'every',\n 'fill',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'forEach',\n 'includes',\n 'indexOf',\n 'join',\n 'keys',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'values',\n]);\nconst ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\nexport function isArrayGetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_GETTER_METHODS.has(prop);\n}\nexport function isArraySetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_SETTER_METHODS.has(prop);\n}\n\nexport function convertToInt(prop: KeyType): number | null {\n if (typeof prop === 'symbol') return null;\n\n const num = Number(prop);\n\n if (isNaN(num)) return null;\n\n return num % 1 === 0 ? num : null;\n}\n\nexport type ForEachCB<T> = (record: T, index: number, context: typeof NativeProxy<ResourceKey[], T[]>) => void;\nexport function safeForEach<T>(\n instance: typeof NativeProxy<ResourceKey[], T[]>,\n arr: ResourceKey[],\n store: Store,\n callback: ForEachCB<T>,\n target: unknown\n): typeof NativeProxy<ResourceKey[], T[]> {\n if (target === undefined) {\n target = null;\n }\n // clone to prevent mutation\n arr = arr.slice();\n assert('`forEach` expects a function as first argument.', typeof callback === 'function');\n\n // because we retrieveLatest above we need not worry if array is mutated during iteration\n // by unloadRecord/rollbackAttributes\n // push/add/removeObject may still be problematic\n // but this is a more traditionally expected forEach bug.\n const length = arr.length; // we need to access length to ensure we are consumed\n\n for (let index = 0; index < length; index++) {\n callback.call(target, store._instanceCache.getRecord(arr[index]) as T, index, instance);\n }\n\n return instance;\n}\n\ntype PromiseTo<T> = Omit<Promise<T>, typeof Symbol.toStringTag>;\ntype PromiseManyArray<T> = {\n length: number;\n content: ReactiveResourceArray<T> | null;\n promise: Promise<ReactiveResourceArray<T>> | null;\n} & PromiseTo<ReactiveResourceArray<T>>;\nexport interface MinimumManager {\n _syncArray(array: ReactiveResourceArray): void;\n mutate?(mutation: LocalRelationshipOperation): void;\n reloadHasMany?<T>(key: string, options?: BaseFinderOptions): Promise<ReactiveResourceArray> | PromiseManyArray<T>;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { SignalStore, WarpDriveSignal } from '../../../signals/-private';\nimport { consumeInternalSignal, getOrCreateInternalSignal } from '../../../signals/-private';\nimport type { ExtensionDef } from '../schema';\n\nexport type ProxiedMethod = (...args: unknown[]) => unknown;\nexport function expectNever(value: never): void {}\n\nexport function isExtensionProp(\n extensions: Map<string | symbol, ExtensionDef> | null,\n prop: string | number | symbol\n): prop is string | symbol {\n return Boolean(extensions && typeof prop !== 'number' && extensions.has(prop));\n}\n\nexport function performObjectExtensionGet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol\n): unknown {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method': {\n return desc.fn;\n }\n case 'readonly-value': {\n return desc.value;\n }\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n // we don't consume this signal, since its not a true local.\n return signal.value;\n }\n case 'readonly-field':\n case 'mutable-field': {\n return desc.get.call(receiver);\n }\n case 'writeonly-field': {\n assert(`Cannot get extended field ${String(prop)} as its definition has only a setter`);\n return undefined;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return undefined;\n }\n }\n}\n\nexport function performExtensionSet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol,\n value: unknown\n): boolean {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method':\n case 'readonly-value':\n case 'readonly-field':\n assert(`Cannot set extension field ${String(prop)} as it is a ${desc.kind}`);\n return false;\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n if (signal.value !== value) {\n // we don't notify this signal, since its not a true local.\n signal.value = value;\n }\n return true;\n }\n case 'writeonly-field':\n case 'mutable-field': {\n desc.set.call(receiver, value);\n return true;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return false;\n }\n }\n}\n\nexport function performArrayExtensionGet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol,\n _SIGNAL: WarpDriveSignal,\n boundFns: Map<string | symbol | number, ProxiedMethod>,\n transaction: (v: boolean) => void\n): unknown {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method': {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n transaction(true);\n const result = Reflect.apply(desc.fn, receiver, arguments) as unknown;\n transaction(false);\n return result;\n };\n\n boundFns.set(prop, fn);\n }\n\n return fn;\n }\n case 'mutable-field':\n case 'readonly-field': {\n return desc.get.call(receiver);\n }\n case 'readonly-value': {\n return desc.value;\n }\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n // we don't consume this signal, since its not a true local.\n return signal.value;\n }\n case 'writeonly-field': {\n assert(`Cannot get extended field ${String(prop)} as its definition has only a setter`);\n return undefined;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return undefined;\n }\n }\n}\n","/* oxlint-disable typescript/no-explicit-any */\n/*\n We redefine Proxy because the native Proxy type treats the `target` and\n `receiver` as the same type incorrectly.\n\n We ported this from Typescript's own Proxy types on 3/10/2024.\n*/\ninterface ProxyHandler<T extends object> {\n /**\n * A trap method for a function call.\n * @param target The original callable object which is being proxied.\n * @internal\n */\n apply?(target: T, thisArg: any, argArray: any[]): any;\n\n /**\n * A trap for the `new` operator.\n * @param target The original object which is being proxied.\n * @param newTarget The constructor that was originally called.\n * @internal\n */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n construct?(target: T, argArray: any[], newTarget: Function): object;\n\n /**\n * A trap for `Object.defineProperty()`.\n * @param target The original object which is being proxied.\n * @return A `Boolean` indicating whether or not the property has been defined.\n * @internal\n */\n defineProperty?(target: T, property: string | symbol, attributes: PropertyDescriptor): boolean;\n\n /**\n * A trap for the `delete` operator.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to delete.\n * @return A `Boolean` indicating whether or not the property was deleted.\n * @internal\n */\n deleteProperty?(target: T, p: string | symbol): boolean;\n\n /**\n * A trap for getting a property value.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to get.\n * @param receiver The proxy or an object that inherits from the proxy.\n * @internal\n */\n get?(target: T, p: string | symbol, receiver: any): any;\n\n /**\n * A trap for `Object.getOwnPropertyDescriptor()`.\n * @param target The original object which is being proxied.\n * @param p The name of the property whose description should be retrieved.\n * @internal\n */\n getOwnPropertyDescriptor?(target: T, p: string | symbol): PropertyDescriptor | undefined;\n\n /**\n * A trap for the `[[GetPrototypeOf]]` internal method.\n * @param target The original object which is being proxied.\n * @internal\n */\n getPrototypeOf?(target: T): object | null;\n\n /**\n * A trap for the `in` operator.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to check for existence.\n * @internal\n */\n has?(target: T, p: string | symbol): boolean;\n\n /**\n * A trap for `Object.isExtensible()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n isExtensible?(target: T): boolean;\n\n /**\n * A trap for `Reflect.ownKeys()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n ownKeys?(target: T): ArrayLike<string | symbol>;\n\n /**\n * A trap for `Object.preventExtensions()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n preventExtensions?(target: T): boolean;\n\n /**\n * A trap for setting a property value.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to set.\n * @param receiver The object to which the assignment was originally directed.\n * @return A `Boolean` indicating whether or not the property was set.\n * @internal\n */\n set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean;\n\n /**\n * A trap for `Object.setPrototypeOf()`.\n * @param target The original object which is being proxied.\n * @param newPrototype The object's new prototype or `null`.\n * @internal\n */\n setPrototypeOf?(target: T, v: object | null): boolean;\n}\n\ninterface ProxyConstructor {\n /**\n * Creates a revocable Proxy object.\n * @param target A target object to wrap with Proxy.\n * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.\n * @internal\n */\n revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void };\n\n /**\n * Creates a Proxy object. The Proxy object allows you to create an object that can be used in place of the\n * original object, but which may redefine fundamental Object operations like getting, setting, and defining\n * properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs.\n * @param target A target object to wrap with Proxy.\n * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.\n * @internal\n */\n new <TSource extends object, TTarget extends object>(target: TSource, handler: ProxyHandler<TSource>): TTarget;\n}\n\n/**\n * The global `Proxy` constructor, retyped with the corrected\n * {@link ProxyConstructor} signature above so that `target` and `receiver`\n * may differ.\n *\n * @private\n */\nexport const NativeProxy: ProxyConstructor = Proxy as unknown as ProxyConstructor;\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { DEPRECATE_COMPUTED_CHAINS } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { OpaqueRecordInstance } from '../../-types/q/record-instance.ts';\nimport type { ExtensionDef } from '../../../reactive.ts';\nimport { Context } from '../../../reactive/-private.ts';\nimport {\n isExtensionProp,\n performArrayExtensionGet,\n performExtensionSet,\n} from '../../../reactive/-private/fields/extension.ts';\nimport type { SignalStore, WarpDriveSignal } from '../../../signals/-private.ts';\nimport {\n ARRAY_SIGNAL,\n consumeInternalSignal,\n createInternalSignal,\n createSignalDescriptor,\n notifyInternalSignal,\n Signals,\n withSignalStore,\n} from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { CollectionField } from '../../../types/schema/fields.ts';\nimport { recordIdentifierFor } from '../caches/instance-cache.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport type { Store } from '../store-service.ts';\nimport type { ForEachCB, KeyType, MinimumManager } from './-utils.ts';\nimport { convertToInt, isArrayGetter, isArraySetter, safeForEach } from './-utils.ts';\nimport { NativeProxy } from './native-proxy-type-fix.ts';\n\nconst IS_COLLECTION: '___(unique) Symbol(IS_COLLECTION)' = getOrSetGlobal('IS_COLLECTION', Symbol.for('Collection'));\nfunction isContextProp(prop: string | symbol | number): prop is keyof ReactiveResourceArrayContext {\n return prop === 'destroy' || prop === 'isDestroying' || prop === 'isDestroyed';\n}\ntype ProxiedMethod = (...args: unknown[]) => unknown;\n\n// these are \"internally\" mutable, they should not be mutated by consumers\n// though this is not currently enforced.\n//\n// all of these should become gated by field-type as they shouldn't be available\n// on request results or non-legacy relationships.\nconst MUTABLE_PROPS = [\n '_updatingPromise',\n 'isDestroying',\n 'isDestroyed',\n 'query',\n 'isUpdating',\n 'isLoaded',\n 'meta',\n 'links',\n 'isAsync',\n 'isPolymorphic',\n 'identifier',\n 'cache',\n 'key',\n 'DEPRECATED_CLASS_NAME',\n];\n\ninterface ReactiveResourceArrayCreateOptions {\n // passed in\n store: Store;\n manager: MinimumManager;\n editable: boolean;\n source: ResourceKey[];\n\n // reactive, passed in\n data: ObjectValue | null;\n\n // non-reactive, passed in\n features: Record<string | symbol, unknown> | null;\n extensions: Map<string | symbol, ExtensionDef> | null;\n\n // not-accessible except by the context\n options: Record<string, unknown> | null;\n\n destroy: null | ((this: ReactiveResourceArray, clear: boolean) => void);\n mutate:\n | null\n | ((\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n ) => unknown);\n}\n\ninterface ReactiveResourceArrayContext extends ReactiveResourceArrayCreateOptions {\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n mutate: (\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n ) => unknown;\n\n // generated\n signals: SignalStore;\n signal: WarpDriveSignal;\n isDestroying: boolean;\n isDestroyed: boolean;\n transaction: boolean;\n boundFns: Map<KeyType, ProxiedMethod>;\n}\n\n/**\n * A reactive Array of records, backed by a {@link ResourceKey} array in the\n * cache. Returned by {@link Store.request} for collection responses and used\n * as the base for relationship and legacy record-array types such as\n * {@link LegacyLiveArray}, {@link LegacyQueryArray} and {@link LegacyManyArray}.\n *\n * Behaves like a native Array: `Array.isArray(arr)` and `arr instanceof Array`\n * both report `true`. The array stays in sync with the cache, updating\n * reactively as the underlying {@link ResourceKey}s change.\n *\n * @public\n */\nexport interface ReactiveResourceArray<T = unknown> extends Omit<Array<T>, '[]'> {\n /** @internal */\n isDestroying: boolean;\n /** @internal */\n isDestroyed: boolean;\n /** @internal */\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n /** @internal */\n [IS_COLLECTION]: boolean;\n /** @internal */\n [Context]: ReactiveResourceArrayContext;\n}\n\n/**\n * A variant of {@link ReactiveResourceArray} that exposes its otherwise\n * internal-only members (including the `Context` symbol used to reach the\n * array's private bookkeeping). Used to upgrade a {@link ReactiveResourceArray}\n * for intimate access by `@warp-drive/legacy`.\n *\n * @private\n */\nexport interface PrivateReactiveResourceArray<T = unknown> extends Omit<Array<T>, '[]'> {\n /** @private */\n isDestroying: boolean;\n /** @private */\n isDestroyed: boolean;\n /** @private */\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n /** @private */\n [IS_COLLECTION]: boolean;\n /** @private */\n [Context]: ReactiveResourceArrayContext;\n}\n\nexport interface TargetArray extends Array<ResourceKey> {\n /** @internal */\n [Context]: ReactiveResourceArrayContext;\n}\n\n// this will error if someone tries to call\n// A(identifierArray) since it is not configurable\n// which is preferable to the `meta` override we used\n// before which required importing all of Ember\nconst ARR_BRACKET_DESC = {\n enumerable: true,\n configurable: false,\n get: function () {\n // here to support computed chains\n // and {{#each}}\n if (DEPRECATE_COMPUTED_CHAINS) {\n return this;\n }\n },\n};\n\nconst IS_UPDATING_DESC = createSignalDescriptor('isUpdating', false);\nconst ArrayHandler: ProxyHandler<ResourceKey[]> = {\n getOwnPropertyDescriptor<R extends typeof NativeProxy<ResourceKey[], unknown[]>>(target: TargetArray, prop: keyof R) {\n if (prop === '[]') {\n // proxies do not allow you to report a descriptor as non-configurable\n // if there is no descriptor or the underlying descriptor is configurable\n const underlying = Reflect.getOwnPropertyDescriptor(target, prop);\n if (!underlying) {\n Object.defineProperty(target, prop, ARR_BRACKET_DESC);\n }\n return ARR_BRACKET_DESC;\n }\n if (prop === 'isUpdating') {\n return IS_UPDATING_DESC;\n }\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n\n get<R extends typeof NativeProxy<ResourceKey[], unknown[]>>(\n target: TargetArray,\n prop: keyof R,\n receiver: R\n ): unknown {\n const CONTEXT = target[Context];\n\n // we place this prop first as it needs initialized\n // prior to the signal check below\n if (prop === Signals) return CONTEXT.signals;\n\n const index = convertToInt(prop);\n if (\n // prettier-ignore\n CONTEXT.signal.isStale &&\n (\n index !== null ||\n prop === 'length' ||\n prop === '[]' ||\n (CONTEXT.data && prop in CONTEXT.data) ||\n isArrayGetter(prop)\n )\n ) {\n CONTEXT.manager._syncArray(receiver as unknown as ReactiveResourceArray);\n CONTEXT.signal.isStale = false;\n }\n\n if (index !== null) {\n const identifier = target[index];\n if (!CONTEXT.transaction) {\n consumeInternalSignal(CONTEXT.signal);\n }\n return identifier && CONTEXT.store._instanceCache.getRecord(identifier);\n }\n\n if (prop === 'length') return (consumeInternalSignal(CONTEXT.signal), target.length);\n if (prop === '[]') return (consumeInternalSignal(CONTEXT.signal), receiver);\n // TODO move this to ?? so its only on subclasses\n if (prop === 'isUpdating') return IS_UPDATING_DESC.get!.call(receiver);\n if (prop === IS_COLLECTION) return true;\n if (prop === Context) return CONTEXT;\n if (isContextProp(prop)) {\n return CONTEXT[prop];\n }\n\n if (CONTEXT.data && prop in CONTEXT.data) {\n // all props in data are reactive props.\n return (consumeInternalSignal(CONTEXT.signal), CONTEXT.data[prop]);\n }\n\n if (isArrayGetter(prop)) {\n let fn = CONTEXT.boundFns.get(prop);\n\n if (fn === undefined) {\n if (prop === 'forEach') {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n CONTEXT.transaction = true;\n const result = safeForEach(\n receiver,\n target,\n CONTEXT.store,\n arguments[0] as ForEachCB<unknown>,\n arguments[1]\n );\n CONTEXT.transaction = false;\n return result;\n };\n } else {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n CONTEXT.transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n CONTEXT.transaction = false;\n return result;\n };\n }\n\n CONTEXT.boundFns.set(prop, fn);\n }\n\n return fn;\n }\n\n if (isArraySetter(prop)) {\n let fn = CONTEXT.boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n if (!CONTEXT.editable) {\n assert(`Mutating this array of records via ${String(prop)} is not allowed.`, CONTEXT.editable);\n return;\n }\n const args: unknown[] = Array.prototype.slice.call(arguments);\n assert(`Cannot start a new array transaction while a previous transaction is underway`, !CONTEXT.transaction);\n CONTEXT.transaction = true;\n const result = CONTEXT.mutate(target, receiver, prop as string, args, CONTEXT.signal);\n CONTEXT.transaction = false;\n return result;\n };\n\n CONTEXT.boundFns.set(prop, fn);\n }\n\n return fn;\n }\n\n if (CONTEXT.features && prop in CONTEXT.features) {\n let fn = CONTEXT.boundFns.get(prop);\n if (fn) return fn;\n\n // @ts-expect-error\n const outcome: unknown = CONTEXT.features[prop];\n\n if (typeof outcome === 'function') {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n return Reflect.apply(outcome as ProxiedMethod, receiver, arguments) as unknown;\n };\n\n CONTEXT.boundFns.set(prop, fn);\n return fn;\n }\n\n return (consumeInternalSignal(CONTEXT.signal), outcome);\n }\n\n if (isExtensionProp(CONTEXT.extensions, prop)) {\n return performArrayExtensionGet(\n receiver,\n CONTEXT.extensions!,\n CONTEXT.signals,\n prop,\n CONTEXT.signal,\n CONTEXT.boundFns,\n (v: boolean) => void (CONTEXT.transaction = v)\n );\n }\n\n // this Proxy get trap must return raw property values, including methods, unbound\n // oxlint-disable-next-line typescript/unbound-method\n return target[prop as keyof ResourceKey[]];\n },\n\n set(\n target: TargetArray,\n prop: KeyType,\n value: unknown,\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>\n ): boolean {\n const CONTEXT = target[Context];\n if (prop === Signals) {\n CONTEXT.signals = value as SignalStore;\n return true;\n }\n\n if (!CONTEXT.editable && !MUTABLE_PROPS.includes(prop as string)) {\n assert(`Mutating ${String(prop)} on this Array is not allowed.`, CONTEXT.editable);\n return false;\n }\n if (prop === 'length') {\n if (!CONTEXT.transaction && value === 0) {\n CONTEXT.transaction = true;\n CONTEXT.mutate(target, receiver, 'length 0', [], CONTEXT.signal);\n CONTEXT.transaction = false;\n return true;\n } else if (CONTEXT.transaction) {\n return Reflect.set(target, prop, value);\n } else {\n assert(`unexpected length set`);\n }\n }\n\n if (isContextProp(prop)) {\n // @ts-expect-error\n CONTEXT[prop] = value;\n return true;\n }\n\n if (CONTEXT.data && prop in CONTEXT.data) {\n CONTEXT.data[prop as string] = (value || null) as Value;\n return true;\n }\n\n // TODO move this to subclass\n if (prop === 'isUpdating') {\n IS_UPDATING_DESC.set!.call(receiver, value);\n return true;\n }\n\n if (isExtensionProp(CONTEXT.extensions, prop)) {\n return performExtensionSet(receiver, CONTEXT.extensions!, CONTEXT.signals, prop, value);\n }\n\n const index = convertToInt(prop);\n\n // we do not allow \"holey\" arrays and so if the index is\n // greater than length then we will disallow setting it.\n // however, there is a special case for \"unshift\" with more than\n // one item being inserted since current items will be moved to the\n // new indices first.\n // we \"loosely\" detect this by just checking whether we are in\n // a transaction.\n if (index === null || index > target.length) {\n if (index !== null && CONTEXT.transaction) {\n const identifier = recordIdentifierFor(value);\n assert(`Cannot set index ${index} past the end of the array.`, isResourceKey(identifier));\n target[index] = identifier;\n return true;\n } else if (CONTEXT.features && prop in CONTEXT.features) {\n CONTEXT.features[prop] = value;\n return true;\n }\n return false;\n }\n\n const original: ResourceKey | undefined = target[index];\n const newIdentifier = extractIdentifierFromRecord(value);\n assert(`Expected a record`, newIdentifier && isResourceKey(newIdentifier));\n // We generate \"transactions\" whenever a setter method on the array\n // is called and might bulk update multiple array cells. Fundamentally,\n // all array operations decompose into individual cell replacements.\n // e.g. a push is really a \"replace cell at next index with new value\"\n // or a splice is \"shift all values left/right by X and set out of new\n // bounds cells to undefined\"\n //\n // so, if we are in a transaction, then this is not a user generated change\n // but one generated by a setter method. In this case we want to only apply\n // the change to the target array and not call the MUTATE method.\n // If there is no transaction though, then this means the user themselves has\n // directly changed the value of a specific index and we need to thus generate\n // a mutation for that change.\n // e.g. \"arr.push(newVal)\" is handled by a \"addToRelatedRecords\" mutation within\n // a transaction.\n // while \"arr[arr.length] = newVal;\" is handled by this replace cell code path.\n if (!CONTEXT.transaction) {\n CONTEXT.mutate(target, receiver, 'replace cell', [index, original, newIdentifier], CONTEXT.signal);\n } else {\n target[index] = newIdentifier;\n }\n\n return true;\n },\n\n deleteProperty(target: TargetArray, prop: string | symbol): boolean {\n const CONTEXT = target[Context];\n assert(`Deleting keys on managed arrays is disallowed`, CONTEXT.transaction);\n if (!CONTEXT.transaction) {\n return false;\n }\n return Reflect.deleteProperty(target, prop);\n },\n\n getPrototypeOf() {\n return Array.prototype as ReactiveResourceArray;\n },\n};\n\nconst ILLEGAL_MUTATION = () => {\n assert(`ILLEGAL OPERATION: This ReactiveResourceArray is immutable`);\n};\n\nexport function createReactiveResourceArray<T>(options: ReactiveResourceArrayCreateOptions): ReactiveResourceArray<T> {\n const TARGET = options.source as TargetArray;\n const context = {\n store: options.store,\n manager: options.manager,\n editable: options.editable,\n source: options.source,\n data: options.data,\n features: options.features,\n extensions: options.extensions,\n options: options.options,\n destroy: options.destroy || destroy,\n mutate: options.mutate || ILLEGAL_MUTATION,\n signals: null as unknown as SignalStore,\n signal: null as unknown as WarpDriveSignal,\n isDestroying: false,\n isDestroyed: false,\n transaction: false,\n boundFns: new Map(),\n } satisfies ReactiveResourceArrayContext;\n TARGET[Context] = context;\n\n const proxy = new NativeProxy<ResourceKey[], T[]>(TARGET, ArrayHandler) as ReactiveResourceArray<T>;\n if (DEBUG) {\n Object.defineProperty(TARGET, '__SHOW_ME_THE_DATA_(debug mode only)__', {\n enumerable: false,\n configurable: true,\n get() {\n return proxy.slice();\n },\n });\n }\n\n // we entangle the signal on the returned proxy since that is\n // the object that other code will be interfacing with.\n // when a mutation occurs\n // we track all mutations within the call\n // and forward them as one\n withSignalStore(proxy);\n context.signal = createInternalSignal(context.signals, proxy, ARRAY_SIGNAL, undefined);\n\n return proxy;\n}\n\n// Ensure instanceof works correctly\n// Object.setPrototypeOf(IdentifierArray.prototype, Array.prototype);\n\nfunction extractIdentifierFromRecord(record: OpaqueRecordInstance | null) {\n if (!record) {\n return null;\n }\n\n assert(\n `All elements of a ReactiveResourceArray must be instances of a ReactiveResource, you passed $${typeof record}`,\n (function () {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n })()\n );\n\n return recordIdentifierFor(record);\n}\n\nexport function destroy(this: ReactiveResourceArray, clear: boolean): void {\n const context = this[Context];\n this.isDestroying = !clear;\n // changing the reference breaks the Proxy\n // this[SOURCE] = [];\n context.source.length = 0;\n notifyInternalSignal(context.signal);\n this.isDestroyed = !clear;\n}\n\nexport interface ReactiveRequestCollectionCreateArgs {\n // passed in\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n\n options: {\n requestKey: RequestKey;\n } | null;\n}\n\nexport function createRequestCollection(config: ReactiveRequestCollectionCreateArgs): ReactiveResourceArray {\n return createReactiveResourceArray({\n store: config.store,\n manager: config.manager,\n editable: false,\n source: config.source,\n data: null,\n features: null,\n extensions: null,\n options: config.options,\n destroy: null,\n mutate: null,\n });\n}\n\nexport interface ReactiveRelatedCollectionCreateArgs {\n // passed in\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n\n // not-accessible except by the context\n options: {\n resourceKey: ResourceKey;\n path: string[];\n field: CollectionField;\n };\n\n editable: boolean;\n extensions: Map<string | symbol, ExtensionDef> | null;\n}\n\nexport function createRelatedCollection(config: ReactiveRelatedCollectionCreateArgs): ReactiveResourceArray {\n return createReactiveResourceArray({\n store: config.store,\n manager: config.manager,\n editable: config.editable,\n source: config.source,\n data: null,\n features: null,\n extensions: config.extensions,\n options: config.options,\n destroy: null,\n mutate: null,\n });\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { TypeFromInstanceOrString } from '../../../types/record.ts';\nimport type { Store } from '../store-service.ts';\nimport type { LegacyArray, MinimumManager } from './-utils.ts';\nimport { save, update } from './-utils.ts';\nimport type { ReactiveResourceArray } from './resource-array.ts';\nimport { createReactiveResourceArray } from './resource-array.ts';\n\n/**\n * LiveArrays contain all the known records for a given `ResourceType`.\n *\n * ### Basic Example\n *\n * For instance, if an application were to have a `'user'` type:\n *\n * ```ts\n * const usersLiveArray = store.peekAll('user');\n * ```\n *\n * ---\n *\n * \n *\n * ### LiveArrays are Arrays\n *\n * LiveArrays have all array APIs, and will report `true`\n * for both `liveArray instanceof Array` and `Array.isArray(liveArray)`\n *\n * ---\n *\n * \n *\n * ### Reactive\n *\n * The array is \"live\" as it will reactively update any time new\n * users are added to the store's cache.\n *\n * There is only one LiveArray instance per ResourceType, and it\n * can be accessed either via {@link Store.peekAll} or {@link Store.findAll}\n *\n * ```ts\n * const users = await store.findAll('user');\n * const peekedUsers = store.peekAll('user');\n * peekedUsers === users; // true\n * ```\n *\n * ---\n *\n * \n *\n * ### New Records\n *\n * Records in the `\"new\"` state (created locally on the client\n * but not yet saved) appear in LiveArrays if they are in LegacyMode.\n *\n * PolarisMode records in the `\"new\"` state do not appear in LiveArrays.\n *\n * ---\n *\n * \n *\n * ### Polymorphism\n *\n * LiveArrays are not polymorphic. If your application has an abstract\n * type \"car\" with concrete types \"ferrari\" and \"bmw\", then \"ferrari\"\n * and \"bmw\" will have populated LiveArrays, but the LiveArray for \"car\"\n * would be empty.\n *\n * @legacy we recommend againt using LiveArrays. Use {@link Store.request} instead\n */\nexport interface LegacyLiveArray<T = unknown> extends LegacyArray<T> {\n /**\n * Whether this LiveArray has loaded. LiveArrays are always considered\n * loaded once created.\n */\n isLoaded: boolean;\n\n /** @internal */\n DEPRECATED_CLASS_NAME: string;\n\n /**\n * The resource type (`ResourceType`) whose records this LiveArray contains.\n */\n modelName: TypeFromInstanceOrString<T>;\n}\n\n/**\n * The options for {@link createLegacyLiveArray}\n *\n * @private\n */\nexport interface LegacyLiveArrayCreateOptions {\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n type: string;\n}\n\n/**\n * Creates a {@link LegacyLiveArray}\n *\n * @internal\n */\nexport function createLegacyLiveArray(options: LegacyLiveArrayCreateOptions): LegacyLiveArray {\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: false,\n source: options.source,\n data: null,\n features: {\n modelName: options.type,\n update,\n _update: _updateLiveArray,\n save,\n DEPRECATED_CLASS_NAME: 'LiveArray',\n isUpdating: false,\n isLoaded: true,\n _updatingPromise: null,\n },\n extensions: null,\n options: null,\n destroy: null,\n mutate: null,\n }) as LegacyLiveArray;\n}\n\nfunction upgradeThis(obj: unknown): asserts obj is LegacyLiveArray {}\n\nfunction _updateLiveArray(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n const context = this[Context];\n assert(`_update cannot be used with this array`, this.modelName);\n // @ts-expect-error typescript is unable to handle the complexity of\n // T = unknown, modelName = string\n // T extends TypedRecordInstance, modelName = TypeFromInstance<T>\n // both being valid options to pass through here.\n return context.store.findAll<T>(this.modelName, { reload: true });\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport type { ObjectValue } from '../../../types/json/raw.ts';\nimport type { ImmutableRequestInfo } from '../../../types/request.ts';\nimport type { Links, Meta, PaginationLinks } from '../../../types/spec/json-api-raw.ts';\nimport type { RecordArrayManager } from '../managers/record-array-manager.ts';\nimport { type MinimumManager, save, update } from './-utils.ts';\nimport type { LegacyLiveArray, LegacyLiveArrayCreateOptions } from './legacy-live-array.ts';\nimport { createReactiveResourceArray, destroy, type ReactiveResourceArray } from './resource-array.ts';\n\n/**\n * QueryArrays contain the primary records returned when querying\n * for records by `ResourceType`.\n *\n * ### Basic Example\n *\n * For instance, if an application were to have a `'user'` type:\n *\n * ```ts\n * const users = await store.query('user', { name: 'Chris' });\n * ```\n *\n * ---\n *\n * \n *\n * ### QueryArrays are Arrays\n *\n * QueryArrays have all array APIs, and will report `true`\n * for both `queryArray instanceof Array` and `Array.isArray(queryArray)`\n *\n * However, any mutation of the array will throw an error.\n *\n * ---\n *\n * \n *\n * ### Reactive\n *\n * If a record in a QueryArray is deleted and unloaded, it will be\n * automatically removed from the array.\n *\n * ---\n *\n * \n *\n * ### Immutable\n *\n * Records cannot be directly added to or removed from a QueryArray.\n *\n * ---\n *\n * \n *\n * ### Polymorphism\n *\n * QueryArrays are not intended to be polymorphic. If your application has\n * an abstract type \"car\" with concrete types \"ferrari\" and \"bmw\", a query\n * which returns primary data containing both ferraris and bmws will *likely*\n * work, but it is not guaranteed.\n *\n * In contrast, the {@link ReactiveResourceArray} returned when using {@link Store.request}\n * is guaranteed to work with polymorphic responses.\n *\n * ---\n *\n * \n *\n * ### Memory Leaks\n *\n * QueryArrays are meant to be long lived. They can be refreshed using\n * `array.update()`, and destroyed via `array.destroy()`.\n *\n * Unlike most Reactive state in WarpDrive, applications must choose to call\n * `destroy` when the `QueryArray` is no longer needed, else the array instance\n * will be retained until either the application or the store which created it\n * are destroyed. Destroying a QueryArray does not remove its records\n * from the cache, but it does remove the array as well as the overhead it requires\n * from the store for book-keeping.\n *\n * @legacy we recommend againt using QueryArrays. Use {@link Store.request} instead\n */\nexport interface LegacyQueryArray<T = unknown> extends LegacyLiveArray<T> {\n /**\n * The query originally passed to `store.query()` that produced this\n * QueryArray. Used by `update()` to re-run the query.\n */\n query: ImmutableRequestInfo | Record<string, unknown> | null;\n destroy(): void;\n\n /**\n * The JSON:API `links` included in the response that produced this\n * QueryArray, if any.\n */\n links: PaginationLinks | Links | null;\n\n /**\n * The JSON:API `meta` included in the response that produced this\n * QueryArray, if any.\n */\n meta: Meta | null;\n}\n\n/**\n * The options for {@link createLegacyQueryArray}\n *\n * See also {@link LegacyLiveArrayCreateOptions} which\n * this extends.\n *\n * @internal\n */\nexport interface LegacyQueryArrayCreateOptions extends LegacyLiveArrayCreateOptions {\n query: ImmutableRequestInfo | Record<string, unknown> | null;\n isLoaded: boolean;\n links: PaginationLinks | Links | null;\n meta: Meta | null;\n}\n\n/**\n * Creates a {@link LegacyQueryArray}\n *\n * Options: {@link LegacyQueryArrayCreateOptions}\n *\n * @internal\n */\nexport function createLegacyQueryArray<T = unknown>(options: LegacyQueryArrayCreateOptions): LegacyQueryArray<T> {\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: false,\n source: options.source,\n data: {\n links: options.links,\n meta: options.meta,\n } as ObjectValue,\n features: {\n query: options.query,\n modelName: options.type,\n update,\n _update: _updateCollection,\n save,\n DEPRECATED_CLASS_NAME: 'LegacyQueryArray',\n isUpdating: false,\n isLoaded: options.isLoaded,\n _updatingPromise: null,\n },\n extensions: null,\n options: null,\n destroy: destroyCollection,\n mutate: null,\n }) as LegacyQueryArray<T>;\n}\n\nfunction _updateCollection(this: LegacyQueryArray): Promise<LegacyQueryArray> {\n const context = this[Context];\n const { query } = this;\n\n assert(`update cannot be used with this array`, this.modelName);\n assert(`update cannot be used with no query`, query);\n // @ts-expect-error typescript is unable to handle the complexity of\n // T = unknown, modelName = string\n // T extends TypedRecordInstance, modelName = TypeFromInstance<T>\n // both being valid options to pass through here.\n const promise = context.store.query<T>(this.modelName, query as Record<string, unknown>, { _recordArray: this });\n\n return promise;\n}\n\nfunction upgradeManager(obj: MinimumManager): asserts obj is RecordArrayManager {}\n\nfunction destroyCollection(this: ReactiveResourceArray, clear: boolean): void {\n destroy.call(this, clear ?? false);\n const { manager } = this[Context];\n upgradeManager(manager);\n manager._managed.delete(this);\n manager._pending.delete(this);\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport { notifyInternalSignal } from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { ImmutableRequestInfo } from '../../../types/request.ts';\nimport type { CollectionResourceDocument } from '../../../types/spec/json-api-raw.ts';\nimport type { LegacyLiveArray } from '../record-arrays/legacy-live-array.ts';\nimport { createLegacyLiveArray } from '../record-arrays/legacy-live-array.ts';\nimport {\n createLegacyQueryArray,\n type LegacyQueryArray,\n type LegacyQueryArrayCreateOptions,\n} from '../record-arrays/legacy-query.ts';\nimport {\n createRequestCollection,\n type ReactiveRequestCollectionCreateArgs,\n type ReactiveResourceArray,\n} from '../record-arrays/resource-array.ts';\nimport type { Store } from '../store-service.ts';\nimport type { CacheOperation, DocumentCacheOperation, UnsubscribeToken } from './notification-manager.ts';\n\nconst FAKE_ARR = getOrSetGlobal('FAKE_ARR', {});\nconst SLICE_BATCH_SIZE = 4761;\n/**\n * This is a clever optimization.\n *\n * clever optimizations rarely stand the test of time, so if you're\n * ever curious or think something better is possible please benchmark\n * and discuss. The benchmark for this at the time of writing is in\n * `scripts/benchmark-push.js`\n *\n * This approach turns out to be 150x faster in Chrome and node than\n * simply using push or concat. It's highly susceptible to the specifics\n * of the batch size, and may require tuning.\n *\n * Clever optimizations should always come with a `why`. This optimization\n * exists for two reasons.\n *\n * 1) array.push(...objects) and Array.prototype.push.apply(arr, objects)\n * are susceptible to stack overflows. The size of objects at which this\n * occurs varies by environment, browser, and current stack depth and memory\n * pressure; however, it occurs in all browsers in fairly pristine conditions\n * somewhere around 125k to 200k elements. Since WarpDrive regularly encounters\n * arrays larger than this in size, we cannot use push.\n *\n * 2) `array.concat` or simply setting the array to a new reference is often an\n * easier approach; however, native Proxy to an array cannot swap it's target array\n * and attempts at juggling multiple array sources have proven to be victim to a number\n * of browser implementation bugs. Should these bugs be addressed then we could\n * simplify to using `concat`, however, do note this is currently 150x faster\n * than concat, and due to the overloaded signature of concat will likely always\n * be faster.\n *\n * Sincerely,\n * - runspired (Chris Thoburn) 08/21/2022\n *\n * @private\n * @param target the array to push into\n * @param source the items to push into target\n */\nexport function fastPush<T>(target: T[], source: T[]): void {\n let batch;\n while (source.length > SLICE_BATCH_SIZE) {\n batch = source.splice(0, SLICE_BATCH_SIZE);\n target.push(...batch);\n }\n target.push(...source);\n}\n\ninterface LegacyQueryInit {\n type: string;\n query: ImmutableRequestInfo | Record<string, unknown>;\n}\ninterface AnonymousRequestCollectionInit {\n source: ResourceKey[];\n}\ninterface RequestCollectionInit {\n source: ResourceKey[];\n requestKey: RequestKey;\n}\n\ntype CollectionInit = LegacyQueryInit | AnonymousRequestCollectionInit | RequestCollectionInit;\n\ntype ChangeSet = Map<ResourceKey, 'add' | 'del'>;\n\n/**\n @hideconstructor\n @private\n*/\nexport class RecordArrayManager {\n /** @internal */\n declare private store: Store;\n\n /** @internal */\n declare private isDestroying: boolean;\n\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _set: Map<ReactiveResourceArray, Set<ResourceKey>>;\n /**\n * LiveArray (peekAll/findAll) array instances\n * keyed by their ResourceType.\n *\n * @internal\n */\n declare _live: Map<string, LegacyLiveArray>;\n /** @internal */\n declare _managed: Set<ReactiveResourceArray>;\n /**\n * Buffered changes to apply keyed by the array to\n * which to apply them to.\n *\n * @internal\n */\n declare _pending: Map<ReactiveResourceArray, ChangeSet>;\n /**\n * An inverse map from ResourceKey to the list\n * of arrays it can be found in, useful for fast updates\n * when state changes to a resource occur.\n *\n * @internal\n */\n declare private _identifiers: Map<ResourceKey, Set<ReactiveResourceArray>>;\n /**\n * When we do not yet have a LiveArray, this keeps track of\n * the added/removed identifiers to enable us to more efficiently\n * produce the LiveArray later.\n *\n * It's possible that using a Set and only storing additions instead of\n * additions and deletes would be more efficient.\n *\n * @internal\n */\n declare private _staged: Map<string, ChangeSet>;\n /** @internal */\n declare private _subscription: UnsubscribeToken;\n /** @internal */\n declare private _documentSubscription: UnsubscribeToken;\n /**\n * KeyedArrays are arrays associated to a specific RequestKey.\n * @internal\n */\n declare private _keyedArrays: Map<string, ReactiveResourceArray>;\n /**\n * The visibility set tracks whether a given identifier should\n * be shown in RecordArrays. It is used to dedupe added/removed\n * and state change events.\n *\n * As a Map, it grows to be very large - there may be ways to\n * reduce its size by instead migrating to it functioning as\n * an exclusion list. Any entry not in the list would be considered\n * visible.\n * @internal\n */\n declare private _visibilitySet: Map<ResourceKey, boolean>;\n\n constructor(options: { store: Store }) {\n this.store = options.store;\n this.isDestroying = false;\n this.isDestroyed = false;\n this._live = new Map();\n this._managed = new Set();\n this._pending = new Map();\n this._staged = new Map();\n this._keyedArrays = new Map();\n this._identifiers = new Map();\n this._set = new Map();\n this._visibilitySet = new Map();\n\n this._documentSubscription = this.store.notifications.subscribe(\n 'document',\n (identifier: RequestKey, type: DocumentCacheOperation) => {\n if (type === 'updated' && this._keyedArrays.has(identifier.lid)) {\n const array = this._keyedArrays.get(identifier.lid)!;\n this.dirtyArray(array, 0, true);\n }\n }\n );\n\n this._subscribeToResourceChanges();\n }\n\n /** @internal */\n private _subscribeToResourceChanges() {\n this._subscription = this.store.notifications.subscribe(\n 'resource',\n (identifier: ResourceKey, type: CacheOperation) => {\n const schema = this.store.schema.resource?.(identifier);\n // If we are a polaris mode schema\n // and we are in the `isNew` state, we are kept hidden from\n // record arrays.\n if (schema && (!('legacy' in schema) || !schema.legacy)) {\n if (this.store.cache.isNew(identifier)) {\n return;\n }\n }\n\n if (type === 'added') {\n this._visibilitySet.set(identifier, true);\n this.identifierAdded(identifier);\n } else if (type === 'removed') {\n this._visibilitySet.set(identifier, false);\n this.identifierRemoved(identifier);\n } else if (type === 'state') {\n this.identifierChanged(identifier);\n }\n }\n );\n }\n\n /** @internal */\n _syncArray(array: ReactiveResourceArray): void {\n const pending = this._pending.get(array);\n const isLegacyQuery = isLegacyQueryArray(array);\n\n if ((isLegacyQuery && !pending) || this.isDestroying || this.isDestroyed) {\n return;\n }\n\n // first flush any staged changes\n if (pending) {\n sync(array, pending, this._set.get(array)!);\n this._pending.delete(array);\n }\n\n // then pull new state if required\n if (!isLegacyQuery && !isLegacyLiveArray(array)) {\n const context = array[Context];\n const signal = context.signal;\n const identifier = context.options!.requestKey as RequestKey;\n\n // we only need to rebuild the array from cache if a full sync is required\n // due to notification that the cache has changed\n if (signal.value === 'cache-sync') {\n const doc = this.store.cache.peek(identifier);\n assert(`Expected to find a document for ${identifier.lid} but found none`, doc);\n const data = !('data' in doc) || !Array.isArray(doc.data) ? [] : doc.data;\n // TODO technically we should destroy here if\n // !('data' in doc) || !Array.isArray(doc.data)\n // is true.\n this.populateManagedArray(array, data, null);\n }\n }\n }\n\n mutate(mutation: LocalRelationshipOperation): void {\n this.store.cache.mutate(mutation);\n }\n\n /**\n Get the `RecordArray` for a modelName, which contains all loaded records of\n given modelName.\n\n @private\n */\n liveArrayFor(type: string): LegacyLiveArray {\n let array = this._live.get(type);\n const identifiers: ResourceKey[] = [];\n const staged = this._staged.get(type);\n if (staged) {\n staged.forEach((value, key) => {\n if (value === 'add') {\n identifiers.push(key);\n }\n });\n this._staged.delete(type);\n }\n\n if (!array) {\n array = createLegacyLiveArray({\n store: this.store,\n manager: this,\n source: identifiers,\n type,\n });\n this._live.set(type, array);\n this._set.set(array, new Set(identifiers));\n }\n\n return array;\n }\n\n getCollection(config: LegacyQueryInit): LegacyQueryArray;\n getCollection(config: AnonymousRequestCollectionInit): ReactiveResourceArray;\n getCollection(config: RequestCollectionInit): ReactiveResourceArray;\n getCollection(config: CollectionInit): ReactiveResourceArray {\n if ('requestKey' in config && this._keyedArrays.has(config.requestKey.lid)) {\n return this._keyedArrays.get(config.requestKey.lid)!;\n }\n\n let array: ReactiveResourceArray;\n if ('requestKey' in config) {\n const options: ReactiveRequestCollectionCreateArgs = {\n store: this.store,\n manager: this,\n source: config.source,\n options: {\n requestKey: config.requestKey,\n },\n };\n array = createRequestCollection(options);\n this._keyedArrays.set(config.requestKey.lid, array);\n this._set.set(array, new Set(config.source));\n associate(this._identifiers, array, config.source);\n } else if ('query' in config) {\n const options: LegacyQueryArrayCreateOptions = {\n store: this.store,\n manager: this,\n source: [],\n type: config.type,\n query: config.query,\n isLoaded: false,\n links: null,\n meta: null,\n };\n array = createLegacyQueryArray(options);\n this._set.set(array, new Set());\n } else {\n const options: ReactiveRequestCollectionCreateArgs = {\n store: this.store,\n manager: this,\n source: config.source,\n options: null,\n };\n array = createRequestCollection(options);\n this._set.set(array, new Set(config.source));\n associate(this._identifiers, array, config.source);\n }\n\n this._managed.add(array);\n return array;\n }\n\n /** @internal */\n private dirtyArray(array: ReactiveResourceArray, delta: number, shouldSyncFromCache: boolean): void {\n if (array === FAKE_ARR) {\n return;\n }\n const signal = array[Context].signal;\n if (!signal.isStale || delta > 0) {\n notifyInternalSignal(signal);\n\n // when the cache has updated for our array, we need to\n // do a full rebuild of the array\n signal.value = shouldSyncFromCache ? 'cache-sync' : 'patch';\n }\n }\n\n /** @internal */\n private _getPendingFor(\n identifier: ResourceKey,\n includeManaged: boolean,\n isRemove?: boolean\n ): Map<ReactiveResourceArray, ChangeSet> | void {\n if (this.isDestroying || this.isDestroyed) {\n return;\n }\n\n const liveArray = this._live.get(identifier.type);\n const allPending = this._pending;\n const pending: Map<ReactiveResourceArray, ChangeSet> = new Map();\n\n if (includeManaged) {\n const managed = this._identifiers.get(identifier);\n if (managed) {\n managed.forEach((arr) => {\n let changes = allPending.get(arr);\n if (!changes) {\n changes = new Map();\n allPending.set(arr, changes);\n }\n pending.set(arr, changes);\n });\n }\n }\n\n // during unloadAll we can ignore removes since we've already\n // cleared the array.\n if (liveArray && liveArray[Context].source.length === 0 && isRemove) {\n const pendingLive = allPending.get(liveArray);\n if (!pendingLive || pendingLive.size === 0) {\n return pending;\n }\n }\n\n if (!liveArray) {\n // start building a changeset for when we eventually\n // do have a live array\n let changes = this._staged.get(identifier.type);\n if (!changes) {\n changes = new Map();\n this._staged.set(identifier.type, changes);\n }\n pending.set(FAKE_ARR as ReactiveResourceArray, changes);\n } else {\n let changes = allPending.get(liveArray);\n if (!changes) {\n changes = new Map();\n allPending.set(liveArray, changes);\n }\n pending.set(liveArray, changes);\n }\n\n return pending;\n }\n\n /**\n * @private\n */\n populateManagedArray(\n array: ReactiveResourceArray,\n identifiers: ResourceKey[],\n payload: CollectionResourceDocument | null\n ): void {\n this._pending.delete(array);\n const source = array[Context].source;\n assert(\n `The new state of the collection should not be using the same array reference as the original state.`,\n source !== identifiers\n );\n const old = source.slice();\n source.length = 0;\n fastPush(source, identifiers);\n this._set.set(array, new Set(identifiers));\n\n if (isLegacyQueryArray(array)) {\n notifyInternalSignal(array[Context].signal);\n array.meta = payload?.meta || null;\n array.links = payload?.links || null;\n array.isLoaded = true;\n }\n\n disassociate(this._identifiers, array, old);\n associate(this._identifiers, array, identifiers);\n }\n\n /** @internal */\n private identifierAdded(identifier: ResourceKey): void {\n const changeSets = this._getPendingFor(identifier, false);\n if (changeSets) {\n changeSets.forEach((changes, array) => {\n const existing = changes.get(identifier);\n if (existing === 'del') {\n changes.delete(identifier);\n } else {\n changes.set(identifier, 'add');\n\n this.dirtyArray(array, changes.size, false);\n }\n });\n }\n }\n\n /** @internal */\n private identifierRemoved(identifier: ResourceKey): void {\n const changeSets = this._getPendingFor(identifier, true, true);\n if (changeSets) {\n changeSets.forEach((changes, array) => {\n const existing = changes.get(identifier);\n if (existing === 'add') {\n changes.delete(identifier);\n } else {\n changes.set(identifier, 'del');\n\n this.dirtyArray(array, changes.size, false);\n }\n });\n }\n }\n\n /** @internal */\n private identifierChanged(identifier: ResourceKey): void {\n const newState = this.store._instanceCache.recordIsLoaded(identifier, true);\n\n // if the change matches the most recent direct added/removed\n // state, then we can ignore it\n if (this._visibilitySet.get(identifier) === newState) {\n return;\n }\n\n if (newState) {\n this.identifierAdded(identifier);\n } else {\n this.identifierRemoved(identifier);\n }\n }\n\n pause(): void {\n this.store.notifications.unsubscribe(this._subscription);\n }\n resume(): void {\n this._subscribeToResourceChanges();\n }\n\n /**\n * @internal\n */\n clear(isClear = true): void {\n for (const array of this._live.values()) {\n array.destroy(isClear);\n }\n for (const array of this._managed.values()) {\n array.destroy(isClear);\n }\n this._managed.clear();\n this._identifiers.clear();\n this._pending.clear();\n for (const set of this._set.values()) {\n set.clear();\n }\n this._visibilitySet.clear();\n }\n\n destroy(): void {\n this.isDestroying = true;\n this.clear(false);\n this._live.clear();\n this.store.notifications.unsubscribe(this._subscription);\n this.store.notifications.unsubscribe(this._documentSubscription);\n this.isDestroyed = true;\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRecordArrayManager extends RecordArrayManager {\n _live: Map<string, LegacyLiveArray>;\n _pending: Map<ReactiveResourceArray, ChangeSet>;\n _managed: Set<ReactiveResourceArray>;\n clear(isClear?: boolean): void;\n}\n\nfunction associate(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifiers: ResourceKey[]\n) {\n for (let i = 0; i < identifiers.length; i++) {\n const identifier = identifiers[i];\n let cache = ArraysCache.get(identifier);\n if (!cache) {\n cache = new Set();\n ArraysCache.set(identifier, cache);\n }\n cache.add(array);\n }\n}\n\nfunction disassociate(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifiers: ResourceKey[]\n) {\n for (let i = 0; i < identifiers.length; i++) {\n disassociateIdentifier(ArraysCache, array, identifiers[i]);\n }\n}\n\nexport function disassociateIdentifier(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifier: ResourceKey\n): void {\n const cache = ArraysCache.get(identifier);\n if (cache) {\n cache.delete(array);\n }\n}\n\nfunction sync(array: ReactiveResourceArray, changes: Map<ResourceKey, 'add' | 'del'>, arraySet: Set<ResourceKey>) {\n const state = array[Context].source;\n const adds: ResourceKey[] = [];\n const removes: ResourceKey[] = [];\n changes.forEach((value, key) => {\n if (value === 'add') {\n // likely we want to keep a Set along-side\n if (arraySet.has(key)) {\n return;\n }\n adds.push(key);\n arraySet.add(key);\n } else {\n if (arraySet.has(key)) {\n removes.push(key);\n arraySet.delete(key);\n }\n }\n });\n if (removes.length) {\n if (removes.length === state.length) {\n state.length = 0;\n // changing the reference breaks the Proxy\n // state = array[SOURCE] = [];\n } else {\n removes.forEach((i) => {\n const index = state.indexOf(i);\n if (index !== -1) {\n state.splice(index, 1);\n arraySet.delete(i);\n }\n });\n }\n }\n\n if (adds.length) {\n fastPush(state, adds);\n // changing the reference breaks the Proxy\n // else we could do this\n /*\n if (state.length === 0) {\n array[SOURCE] = adds;\n } else {\n array[SOURCE] = state.concat(adds);\n }\n */\n }\n}\n\nfunction isLegacyQueryArray(array: ReactiveResourceArray): array is LegacyQueryArray {\n const context = array[Context];\n return context.features !== null && context.features.DEPRECATED_CLASS_NAME === 'LegacyQueryArray';\n}\n\nfunction isLegacyLiveArray(array: ReactiveResourceArray): array is LegacyLiveArray {\n const context = array[Context];\n return context.features !== null && context.features.DEPRECATED_CLASS_NAME === 'LiveArray';\n}\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { FindRecordOptions } from '../../-types/q/store.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { Store } from '../store-service.ts';\n\nconst Touching: '___(unique) Symbol(Touching)' = getOrSetGlobal('Touching', Symbol('touching'));\nexport const RequestPromise: '___(unique) Symbol(RequestPromise)' = getOrSetGlobal('RequestPromise', Symbol('promise'));\nconst EMPTY_ARR: RequestCacheRequestState[] = DEBUG ? (Object.freeze([]) as unknown as RequestCacheRequestState[]) : [];\n\n/**\n * The base shape for a query or mutation operation tracked by the\n * {@link RequestStateService} for a given resource.\n */\nexport interface Operation {\n /** the name of the operation being performed, e.g. `'findRecord'` or `'saveRecord'`. */\n op: string;\n /** the options supplied for the operation, if any. */\n options: FindRecordOptions | undefined;\n /** the resource identifier the operation is being performed for. */\n recordIdentifier: ResourceKey;\n}\n\n/**\n * A {@link Operation} tracked by the {@link RequestStateService} representing\n * a `findRecord` query for a resource.\n */\nexport interface FindRecordQuery extends Operation {\n /** identifies this operation as a `findRecord` query. */\n op: 'findRecord';\n}\n\n/**\n * A {@link Operation} tracked by the {@link RequestStateService} representing\n * a `saveRecord` mutation for a resource.\n */\nexport interface SaveRecordMutation extends Operation {\n /** identifies this operation as a `saveRecord` mutation. */\n op: 'saveRecord';\n}\n\n/**\n * Describes the request associated with a {@link RequestCacheRequestState},\n * as tracked by the {@link RequestStateService}.\n */\nexport interface Request {\n /** the operation(s) being performed by this request. */\n data: Operation[];\n /** options supplied for the request, if any. */\n options?: Record<string, unknown>;\n}\n\nexport type RequestStates = 'pending' | 'fulfilled' | 'rejected';\n\n/**\n * The tracked state of a request as reported by the {@link RequestStateService},\n * e.g. via {@link RequestStateService.subscribeForRecord} or\n * {@link RequestStateService.getPendingRequestsForRecord}.\n */\nexport interface RequestCacheRequestState {\n /** the current lifecycle state of the request. */\n state: RequestStates;\n /** whether the request is a `query` (find) or a `mutation` (save). */\n type: 'query' | 'mutation';\n /** the {@link Request} describing the operation(s) this state is for. */\n request: Request;\n /** the response for the request, present once it has settled. */\n response?: Response;\n}\n\nexport interface Response {\n // rawData: unknown;\n data: unknown;\n}\n\ninterface InternalRequest extends RequestCacheRequestState {\n [Touching]: ResourceKey[];\n [RequestPromise]?: Promise<unknown>;\n}\n\ntype RecordOperation = FindRecordQuery | SaveRecordMutation;\nexport type RequestSubscription = (requestState: RequestCacheRequestState) => void;\n\nfunction hasRecordIdentifier(op: Operation): op is RecordOperation {\n return 'recordIdentifier' in op;\n}\n\n/**\n * The RequestStateService is used to track the state of requests\n * for fetching or updating known resource identifies that are inflight.\n *\n * @hideconstructor\n * @public\n */\nexport class RequestStateService {\n /** @internal */\n _pending: Map<ResourceKey, InternalRequest[]> = new Map();\n /** @internal */\n private _done: Map<ResourceKey, InternalRequest[]> = new Map();\n /** @internal */\n private _subscriptions: Map<ResourceKey, RequestSubscription[]> = new Map();\n /** @internal */\n private _toFlush: InternalRequest[] = [];\n /** @internal */\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n /** @internal */\n _clearEntries(identifier: ResourceKey): void {\n this._done.delete(identifier);\n }\n /** @internal */\n _enqueue<T>(promise: Promise<T>, queryRequest: Request): Promise<T> {\n const query = queryRequest.data[0];\n if (hasRecordIdentifier(query)) {\n const identifier = query.recordIdentifier;\n const type = query.op === 'saveRecord' ? ('mutation' as const) : ('query' as const);\n if (!this._pending.has(identifier)) {\n this._pending.set(identifier, []);\n }\n const request: InternalRequest = {\n state: 'pending',\n request: queryRequest,\n type,\n } as InternalRequest;\n request[Touching] = [query.recordIdentifier];\n request[RequestPromise] = promise;\n this._pending.get(identifier)!.push(request);\n this._triggerSubscriptions(request);\n return promise.then(\n (result) => {\n this._dequeue(identifier, request);\n const finalizedRequest = {\n state: 'fulfilled',\n request: queryRequest,\n type,\n response: { data: result },\n } as InternalRequest;\n finalizedRequest[Touching] = request[Touching];\n this._addDone(finalizedRequest);\n this._triggerSubscriptions(finalizedRequest);\n return result;\n },\n (error) => {\n this._dequeue(identifier, request);\n const finalizedRequest = {\n state: 'rejected',\n request: queryRequest,\n type,\n response: { data: error },\n } as InternalRequest;\n finalizedRequest[Touching] = request[Touching];\n this._addDone(finalizedRequest);\n this._triggerSubscriptions(finalizedRequest);\n throw error;\n }\n );\n }\n assert(`Expected a well formed query`);\n }\n\n /** @internal */\n private _triggerSubscriptions(req: InternalRequest): void {\n if (req.state === 'pending') {\n this._flushRequest(req);\n return;\n }\n this._toFlush.push(req);\n\n if (this._toFlush.length === 1) {\n this._store.notifications._onNextFlush(() => {\n this._flush();\n });\n }\n }\n\n /** @internal */\n private _flush(): void {\n this._toFlush.forEach((req) => {\n this._flushRequest(req);\n });\n this._toFlush = [];\n }\n\n /** @internal */\n private _flushRequest(req: InternalRequest): void {\n req[Touching].forEach((identifier: ResourceKey) => {\n const subscriptions = this._subscriptions.get(identifier);\n if (subscriptions) {\n subscriptions.forEach((callback) => callback(req));\n }\n });\n }\n\n /** @internal */\n private _dequeue(identifier: ResourceKey, request: InternalRequest): void {\n const pending = this._pending.get(identifier)!;\n this._pending.set(\n identifier,\n pending.filter((req) => req !== request)\n );\n }\n\n /** @internal */\n private _addDone(request: InternalRequest): void {\n request[Touching].forEach((identifier) => {\n // TODO add support for multiple\n const requestDataOp = request.request.data[0].op;\n let requests = this._done.get(identifier);\n\n if (requests) {\n requests = requests.filter((req) => {\n // TODO add support for multiple\n let data: Operation;\n if (Array.isArray(req.request.data)) {\n data = req.request.data[0];\n } else {\n data = req.request.data;\n }\n return data.op !== requestDataOp;\n });\n }\n requests = requests || [];\n requests.push(request);\n this._done.set(identifier, requests);\n });\n }\n\n /**\n * Subscribe to requests for a given resource identity.\n *\n * The callback will receive the current state of the request.\n *\n * ```ts\n * interface RequestState {\n * state: 'pending' | 'fulfilled' | 'rejected';\n * type: 'query' | 'mutation';\n * request: Request;\n * response?: { data: unknown };\n * }\n * ```\n *\n * Note: It should be considered dangerous to use this API for more than simple\n * state derivation or debugging. The `request` and `response` properties are poorly\n * spec'd and may change unexpectedly when shifting what Handlers are in use or how\n * requests are issued from the Store.\n *\n * We expect to revisit this API in the near future as we continue to refine the\n * RequestManager ergonomics, as a simpler but more powerful direct integration\n * with the RequestManager for these purposes is likely to be a better long-term\n * design.\n *\n * @public\n * @param {ResourceKey} identifier\n * @param {(state: RequestCacheRequestState) => void} callback\n */\n subscribeForRecord(identifier: ResourceKey, callback: RequestSubscription): void {\n let subscriptions = this._subscriptions.get(identifier);\n if (!subscriptions) {\n subscriptions = [];\n this._subscriptions.set(identifier, subscriptions);\n }\n subscriptions.push(callback);\n }\n\n /**\n * Retrieve all active requests for a given resource identity.\n *\n * @public\n * @param {ResourceKey} identifier\n * @return {RequestCacheRequestState[]} an array of request states for any pending requests for the given identifier\n */\n getPendingRequestsForRecord(identifier: ResourceKey): RequestCacheRequestState[] {\n return this._pending.get(identifier) || EMPTY_ARR;\n }\n\n /**\n * Retrieve the last completed request for a given resource identity.\n *\n * @public\n * @param {ResourceKey} identifier\n * @return {RequestCacheRequestState | null} the state of the most recent request for the given identifier\n */\n getLastRequestForRecord(identifier: ResourceKey): RequestCacheRequestState | null {\n const requests = this._done.get(identifier);\n if (requests) {\n return requests[requests.length - 1];\n }\n return null;\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRequestStateService extends RequestStateService {\n _pending: Map<ResourceKey, InternalRequest[]>;\n _clearEntries(identifier: ResourceKey): void;\n _enqueue<T>(promise: Promise<T>, queryRequest: Request): Promise<T>;\n}\n","export default function esCompat(m) {\n return m?.__esModule ? m : { default: m, ...m };\n}\n","// this import location is deprecated but breaks in 4.8 and older\nimport { deprecate } from '@ember/debug';\n\nimport { dependencySatisfies, importSync, macroCondition } from '@embroider/macros';\n\nimport {\n __INTERNAL_LOG_NATIVE_MAP_SET_COUNTS,\n LOG_METRIC_COUNTS,\n LOG_REQUESTS,\n} from '@warp-drive/core/build-config/debugging';\nimport {\n DEPRECATE_STORE_EXTENDS_EMBER_OBJECT,\n ENABLE_LEGACY_SCHEMA_SERVICE,\n} from '@warp-drive/core/build-config/deprecations';\nimport { DEBUG, TESTING } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { CacheCapabilitiesManager } from '../-types/q/cache-capabilities-manager.ts';\nimport type { OpaqueRecordInstance } from '../-types/q/record-instance.ts';\nimport type { Graph } from '../../graph/-private.ts';\n// oxlint-disable-next-line no-unused-vars\nimport { ReactiveResource } from '../../reactive.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { ReactiveDocument } from '../../reactive/-private/document.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheHandler as CacheHandlerInterface, Future } from '../../request.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { Fetch } from '../../request/-private/fetch.ts';\nimport type { PrivateRequestManager, RequestManager } from '../../request/-private/manager.ts';\nimport type { Cache } from '../../types/cache.ts';\nimport type { PersistedResourceKey, ResourceKey } from '../../types/identifier.ts';\nimport type { TypedRecordInstance, TypeFromInstance } from '../../types/record.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheOptions, RequestInfo } from '../../types/request.ts';\nimport { EnableHydration } from '../../types/request.ts';\nimport { getRuntimeConfig, setLogging } from '../../types/runtime.ts';\nimport type { SchemaService } from '../../types/schema/schema-service.ts';\nimport type { ResourceDocument } from '../../types/spec/document.ts';\nimport type {\n CollectionResourceDocument,\n EmptyResourceDocument,\n JsonApiDocument,\n ResourceIdentifierObject,\n SingleResourceDocument,\n} from '../../types/spec/json-api-raw.ts';\nimport type { Type } from '../../types/symbols.ts';\n// DEPRECATED STORE METHODS -- see the second `Store` interface below\nimport type {\n FindAllOptions,\n FindRecordOptions,\n LegacyResourceQuery,\n ModelSchema,\n QueryOptions,\n RecordReference,\n} from '../deprecated/-private.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheHandler, StoreRequestInput } from './cache-handler/handler.ts';\nimport type { CachePolicy } from './cache-handler/types.ts';\nimport {\n getNewRecord,\n InstanceCache,\n peekResourceKey,\n recordIdentifierFor,\n storeFor,\n} from './caches/instance-cache.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { PrivateCacheKeyManager, setIdentifierGenerationMethod } from './managers/cache-key-manager.ts';\nimport { CacheKeyManager } from './managers/cache-key-manager.ts';\nimport { CacheManager } from './managers/cache-manager.ts';\nimport type { PrivateNotificationManager } from './managers/notification-manager.ts';\nimport { NotificationManager } from './managers/notification-manager.ts';\nimport type { PrivateRecordArrayManager } from './managers/record-array-manager.ts';\nimport { RecordArrayManager } from './managers/record-array-manager.ts';\nimport type { PrivateRequestStateService } from './network/request-cache.ts';\nimport { RequestPromise, RequestStateService } from './network/request-cache.ts';\nimport type { LegacyLiveArray } from './record-arrays/legacy-live-array.ts';\nimport type { LegacyQueryArray } from './record-arrays/legacy-query.ts';\nimport { coerceId, ensureStringId } from './utils/coerce-id.ts';\nimport { normalizeModelName } from './utils/normalize-model-name.ts';\n\nif (TESTING) {\n // @ts-expect-error adding to globalThis\n globalThis.setWarpDriveLogging = setLogging;\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveRuntimeConfig = getRuntimeConfig;\n}\n\nif (LOG_METRIC_COUNTS) {\n // @ts-expect-error adding to globalThis\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData = globalThis.__WarpDriveMetricCountData || {};\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveMetricCounts = () => {\n // @ts-expect-error\n // oxlint-disable-next-line\n return structuredClone(globalThis.__WarpDriveMetricCountData);\n };\n\n // @ts-expect-error adding to globalThis\n globalThis.resetWarpDriveMetricCounts = () => {\n // @ts-expect-error\n globalThis.__WarpDriveMetricCountData = {};\n };\n\n if (__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS) {\n // @ts-expect-error adding to globalThis\n globalThis.__primitiveInstanceId = 0;\n\n function interceptAndLog(\n klassName: 'Set' | 'Map' | 'WeakSet' | 'WeakMap',\n methodName: 'add' | 'set' | 'delete' | 'has' | 'get' | 'constructor'\n ) {\n const klass = globalThis[klassName];\n\n if (methodName === 'constructor') {\n const instantiationLabel = `new ${klassName}()`;\n // @ts-expect-error\n globalThis[klassName] = class extends klass {\n // @ts-expect-error\n constructor(...args) {\n // oxlint-disable-next-line\n super(...args);\n // @ts-expect-error\n\n const instanceId = globalThis.__primitiveInstanceId++;\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[instantiationLabel] =\n // @ts-expect-error\n // oxlint-disable-next-line\n (globalThis.__WarpDriveMetricCountData[instantiationLabel] || 0) + 1;\n // @ts-expect-error\n this.instanceName = `${klassName}:${instanceId} - ${new Error().stack?.split('\\n')[2]}`;\n }\n };\n } else {\n // @ts-expect-error\n // oxlint-disable-next-line\n const original = klass.prototype[methodName];\n const logName = `${klassName}.${methodName}`;\n\n // @ts-expect-error\n klass.prototype[methodName] = function (...args) {\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[logName] = (globalThis.__WarpDriveMetricCountData[logName] || 0) + 1;\n // @ts-expect-error\n const { instanceName } = this;\n if (!instanceName) {\n // @ts-expect-error\n const instanceId = globalThis.__primitiveInstanceId++;\n // @ts-expect-error\n this.instanceName = `${klassName}.${methodName}:${instanceId} - ${new Error().stack?.split('\\n')[2]}`;\n }\n const instanceLogName = `${logName} (${instanceName})`;\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[instanceLogName] =\n // @ts-expect-error\n // oxlint-disable-next-line\n (globalThis.__WarpDriveMetricCountData[instanceLogName] || 0) + 1;\n // oxlint-disable-next-line\n return original.apply(this, args);\n };\n }\n }\n\n interceptAndLog('Set', 'constructor');\n interceptAndLog('Set', 'add');\n interceptAndLog('Set', 'delete');\n interceptAndLog('Set', 'has');\n interceptAndLog('Set', 'set');\n interceptAndLog('Set', 'get');\n\n interceptAndLog('Map', 'constructor');\n interceptAndLog('Map', 'set');\n interceptAndLog('Map', 'delete');\n interceptAndLog('Map', 'has');\n interceptAndLog('Map', 'add');\n interceptAndLog('Map', 'get');\n\n interceptAndLog('WeakSet', 'constructor');\n interceptAndLog('WeakSet', 'add');\n interceptAndLog('WeakSet', 'delete');\n interceptAndLog('WeakSet', 'has');\n interceptAndLog('WeakSet', 'set');\n interceptAndLog('WeakSet', 'get');\n\n interceptAndLog('WeakMap', 'constructor');\n interceptAndLog('WeakMap', 'set');\n interceptAndLog('WeakMap', 'delete');\n interceptAndLog('WeakMap', 'has');\n interceptAndLog('WeakMap', 'add');\n interceptAndLog('WeakMap', 'get');\n }\n}\n\nexport { storeFor };\n\n// We inline this list of methods to avoid importing EmberObject\ntype EmberObjectKey =\n | '_debugContainerKey'\n | '_super'\n | 'addObserver'\n | 'cacheFor'\n | 'concatenatedProperties'\n | 'decrementProperty'\n | 'destroy'\n | 'get'\n | 'getProperties'\n | 'incrementProperty'\n | 'init'\n | 'isDestroyed'\n | 'isDestroying'\n | 'mergedProperties'\n | 'notifyPropertyChange'\n | 'removeObserver'\n | 'reopen'\n | 'set'\n | 'setProperties'\n | 'toggleProperty'\n | 'toString'\n | 'willDestroy';\n\ntype DSModelKeys =\n | '___(unique) Symbol(Store)'\n | '___private_notifications'\n | '___recordState'\n | '_createSnapshot'\n | 'adapterError'\n | 'attr'\n | 'belongsTo'\n | 'changedAttributes'\n | 'currentState'\n | 'deleteRecord'\n | 'destroyRecord'\n | 'dirtyType'\n | 'eachAttribute'\n | 'eachRelationship'\n | 'errors'\n | 'hasDirtyAttributes'\n | 'hasMany'\n | 'inverseFor'\n | 'isDeleted'\n | 'isEmpty'\n | 'isError'\n | 'isLoaded'\n | 'isLoading'\n | 'isNew'\n | 'isReloading'\n | 'isSaving'\n | 'isValid'\n | 'relationshipFor'\n | 'reload'\n | 'rollbackAttributes'\n | 'save'\n | 'serialize'\n | 'store'\n | 'unloadRecord';\n\ntype CompatStore = Store & {\n adapterFor?: (\n type: string,\n _allowMissing?: boolean\n ) => undefined | { generateIdForRecord?(store: Store, type: string, properties: object): string };\n};\nfunction upgradeStore(store: Store): asserts store is CompatStore {}\n\ntype DownlevelArrays<T> = T extends Array<infer U> ? U[] : T;\ntype AwaitedKeys<T> = { [K in keyof T & string]: DownlevelArrays<Awaited<T[K]>> };\n\n// `AwaitedKeys` is needed here to resolve any promise types like `PromiseBelongsTo`.\ntype FilteredKeys<T> = AwaitedKeys<Omit<T, typeof Type | EmberObjectKey | DSModelKeys | 'constructor'>>;\n\ntype MaybeHasId = { id?: string | null };\n/**\n * Currently only records that extend object can be created via\n * store.createRecord. This is a limitation of the current API,\n * but can be worked around by creating a new identifier, running\n * the cache.clientDidCreate method, and then peeking the record\n * for the identifier.\n *\n * To assign primary key to a record during creation, only `id` will\n * work correctly for `store.createRecord`, other primary key may be\n * handled by updating the record after creation or using the flow\n * described above.\n *\n * TODO: These are limitations we want to (and can) address. If you\n * have need of lifting these limitations, please open an issue.\n *\n */\nexport type CreateRecordProperties<T = MaybeHasId & Record<string, unknown>> = T extends TypedRecordInstance\n ? Partial<FilteredKeys<T>>\n : T extends MaybeHasId\n ? MaybeHasId & Partial<FilteredKeys<T>>\n : MaybeHasId & Record<string, unknown>;\n\nexport interface CreateContext {\n lid?: string;\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype ConstructorFunction = new (...args: any[]) => any;\n// oxlint-disable-next-line typescript/no-extraneous-class\nconst EmptyClass: ConstructorFunction = class {\n // oxlint-disable-next-line no-useless-constructor\n constructor(args?: unknown) {}\n};\nconst _BaseClass = macroCondition(dependencySatisfies('ember-source', '*'))\n ? DEPRECATE_STORE_EXTENDS_EMBER_OBJECT\n ? (importSync('@ember/object') as typeof EmptyClass)\n : EmptyClass\n : EmptyClass;\n\nconst BaseClass: typeof EmptyClass = (_BaseClass as unknown as { default?: typeof EmptyClass }).default\n ? ((_BaseClass as unknown as { default?: typeof EmptyClass }).default as typeof EmptyClass)\n : _BaseClass;\n\nif (BaseClass !== EmptyClass) {\n deprecate(\n `The Store class extending from EmberObject is deprecated.\nPlease remove usage of EmberObject APIs and mark your class as not requiring it.\n\nTo mark the class as no longer extending from EmberObject, in ember-cli-build.js\nset the following config:\n\n\\`\\`\\`js\nconst app = new EmberApp(defaults, {\n emberData: {\n deprecations: {\n DEPRECATE_STORE_EXTENDS_EMBER_OBJECT: false\n }\n }\n});\n\\`\\`\\`\n`,\n false,\n {\n id: 'ember-data:deprecate-store-extends-ember-object',\n until: '6.0',\n for: 'ember-data',\n url: 'https://deprecations.emberjs.com/id/ember-data-deprecate-store-extends-ember-object',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n }\n );\n}\n\nexport interface Store {\n /**\n * Instantiation hook allowing applications or addons to configure the store\n * to utilize a custom Cache implementation.\n *\n * This hook should not be called directly by consuming applications or libraries.\n * Use `Store.cache` to access the Cache instance.\n *\n * @public\n */\n createCache(capabilities: CacheCapabilitiesManager): Cache;\n\n /**\n * A hook which an app or addon may implement. Called when\n * the Store is attempting to create a Record Instance for\n * a resource.\n *\n * This hook can be used to select or instantiate any desired\n * mechanism of presenting cache data to the ui for access\n * mutation, and interaction.\n *\n * @param identifier - The Resource CacheKey\n * @param createRecordArgs - An object containing any properties passed to `store.createRecord`\n * @return A record instance\n * @public\n */\n // oxlint-disable-next-line no-unused-vars\n instantiateRecord<T>(identifier: ResourceKey, createRecordArgs: { [key: string]: unknown }): OpaqueRecordInstance;\n\n /**\n * A hook which an app or addon may implement. Called when\n * the Store is destroying a Record Instance. This hook should\n * be used to teardown any custom record instances instantiated\n * with `instantiateRecord`.\n *\n * @public\n * @param record\n */\n teardownRecord(record: OpaqueRecordInstance): void;\n\n /**\n * This hook enables an app to supply a SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method will only be called once to instantiate the singleton\n * service, which can then be accessed via `store.schema`.\n *\n * For Example, to use the default SchemaService for ReactiveResource\n *\n * ```ts\n * import { SchemaService } from '@warp-drive/core/reactive';\n *\n * class extends Store {\n * createSchemaService() {\n * return new SchemaService();\n * }\n * }\n * ```\n *\n * Or to use the SchemaService for @warp-drive/legacy/model\n *\n * ```ts\n * import { buildSchema } from '@warp-drive/legacy/model';\n *\n * class extends Store {\n * createSchemaService() {\n * return buildSchema(this);\n * }\n * }\n * ```\n *\n * If you wish to chain services, you must either\n * instantiate each schema source directly or super to retrieve\n * an existing service. For convenience, when migrating from\n * `@warp-drive/legacy/model` to {@link ReactiveResource} a\n * SchemaService is provided that handles this transition\n * for you:\n *\n * ```ts\n * import { DelegatingSchemaService } from '@warp-drive/legacy/model/migration-support';\n * import { SchemaService } from '@warp-drive/core/reactive';\n *\n * class extends Store {\n * createSchemaService() {\n * const schema = new SchemaService();\n * return new DelegatingSchemaService(this, schema);\n * }\n * }\n * ```\n *\n * When using the DelegateSchemaService, the schema will first\n * be sourced from directly registered schemas, then will fallback\n * to sourcing a schema from available models if no schema is found.\n *\n * @public\n */\n createSchemaService(): SchemaService;\n\n /**\n * DEPRECATED - Use the property `store.schema` instead.\n *\n * Provides access to the SchemaDefinitionService instance\n * for this Store instance.\n *\n * The SchemaDefinitionService can be used to query for\n * information about the schema of a resource.\n *\n * @deprecated\n * @public\n */\n getSchemaDefinitionService(): SchemaService;\n\n /**\n * DEPRECATED - Use `createSchemaService` instead.\n *\n * Allows an app to register a custom SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method can only be called more than once, but only one schema\n * definition service may exist. Therefore if you wish to chain services\n * you must lookup the existing service and close over it with the new\n * service by accessing `store.schema` prior to registration.\n *\n * For Example:\n *\n * ```ts\n * import { Store } from '@warp-drive/core';\n *\n * class SchemaDelegator {\n * constructor(schema) {\n * this._schema = schema;\n * }\n *\n * hasResource(resource: { type: string }): boolean {\n * if (AbstractSchemas.has(resource.type)) {\n * return true;\n * }\n * return this._schema.hasResource(resource);\n * }\n *\n * attributesDefinitionFor(identifier: ResourceKey | { type: string }): AttributesSchema {\n * return this._schema.attributesDefinitionFor(identifier);\n * }\n *\n * relationshipsDefinitionFor(identifier: ResourceKey | { type: string }): RelationshipsSchema {\n * const schema = AbstractSchemas.get(identifier.type);\n * return schema || this._schema.relationshipsDefinitionFor(identifier);\n * }\n * }\n *\n * export default class extends Store {\n * constructor(...args) {\n * super(...args);\n *\n * const schema = this.createSchemaService();\n * this.registerSchemaDefinitionService(new SchemaDelegator(schema));\n * }\n * }\n * ```\n *\n * @deprecated\n * @public\n */\n registerSchemaDefinitionService(schema: SchemaService): void;\n\n /**\n * DEPRECATED - Use `createSchemaService` instead.\n *\n * Allows an app to register a custom SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method can only be called more than once, but only one schema\n * definition service may exist. Therefore if you wish to chain services\n * you must lookup the existing service and close over it with the new\n * service by accessing `store.schema` prior to registration.\n *\n * For Example:\n *\n * ```ts\n * import { Store } from '@warp-drive/core';\n *\n * class SchemaDelegator {\n * constructor(schema) {\n * this._schema = schema;\n * }\n *\n * hasResource(resource: { type: string }): boolean {\n * if (AbstractSchemas.has(resource.type)) {\n * return true;\n * }\n * return this._schema.hasResource(resource);\n * }\n *\n * attributesDefinitionFor(identifier: ResourceKey | { type: string }): AttributesSchema {\n * return this._schema.attributesDefinitionFor(identifier);\n * }\n *\n * relationshipsDefinitionFor(identifier: ResourceKey | { type: string }): RelationshipsSchema {\n * const schema = AbstractSchemas.get(identifier.type);\n * return schema || this._schema.relationshipsDefinitionFor(identifier);\n * }\n * }\n *\n * export default class extends Store {\n * constructor(...args) {\n * super(...args);\n *\n * const schema = this.schema;\n * this.registerSchema(new SchemaDelegator(schema));\n * }\n * }\n * ```\n *\n * @deprecated\n * @public\n */\n registerSchema(schema: SchemaService): void;\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// DEPRECATED STORE METHODS\n//\n// A second, separate `export interface Store {}` (TypeScript merges\n// same-named interfaces declared within a module) rather than a single\n// merged block with the interface above, so this can be found and removed\n// as its own unit.\n//\n// These signatures used to live in `../deprecated/store.ts` as a cross-file\n// `declare module '../-private/store-service' { interface Store {...} }`\n// augmentation. That stopped working once `Store` began being emitted\n// through an entry-based, rolled-up `.d.ts` build (tsdown/rolldown-plugin-dts):\n// `Store` gets hoisted into a shared, hash-named chunk whenever 2+ entries\n// reference it (which is always), and a cross-file module augmentation can't\n// target an unstable chunk name -- it silently fails to attach for any\n// consumer not importing through the exact one path the augmentation happened\n// to specify, which in practice is every real consumer. Same-module interface\n// merging has no such problem, since it's resolved before any bundling happens.\n//\n// The runtime implementations of these methods still live in\n// `../deprecated/store.ts`, gated behind the `ENABLE_LEGACY_REQUEST_METHODS`\n// deprecation flag. Delete this interface (and the `Store` import it drops\n// from `../deprecated/store.ts`'s `declare module` block) once those methods\n// are fully removed.\n/////////////////////////////////////////////////////////////////////////////\nexport interface Store {\n /**\n This method returns a record for a given identifier or type and id combination.\n\n The `findRecord` method will always resolve its promise with the same\n object for a given identifier or type and `id`.\n\n The `findRecord` method will always return a **promise** that will be\n resolved with the record.\n\n **Example 1**\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model({ post_id }) {\n return this.store.findRecord('post', post_id);\n }\n }\n ```\n\n **Example 2**\n\n `findRecord` can be called with a single identifier argument instead of the combination\n of `type` (modelName) and `id` as separate arguments. You may recognize this combo as\n the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model({ post_id: id }) {\n return this.store.findRecord({ type: 'post', id });\n }\n }\n ```\n\n **Example 3**\n\n If you have previously received an lid via an Identifier for this record, and the record\n has already been assigned an id, you can find the record again using just the lid.\n\n ```js [app/routes/post.js]\n store.findRecord({ lid });\n ```\n\n If the record is not yet available, the store will ask the adapter's `findRecord`\n method to retrieve and supply the necessary data. If the record is already present\n in the store, it depends on the reload behavior _when_ the returned promise\n resolves.\n\n ### Preloading\n\n You can optionally `preload` specific attributes and relationships that you know of\n by passing them via the passed `options`.\n\n For example, if your Ember route looks like `/posts/1/comments/2` and your API route\n for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment\n without also fetching the post you can pass in the post to the `findRecord` call:\n\n ```js [app/routes/post-comments.js]\n export default class PostRoute extends Route {\n model({ post_id, comment_id: id }) {\n return this.store.findRecord({ type: 'comment', id, { preload: { post: post_id }} });\n }\n }\n ```\n\n In your adapter you can then access this id without triggering a network request via the\n snapshot:\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'comment')\n let postId = snapshot.belongsTo('post', { id: true });\n\n return fetch(`./posts/${postId}/comments/${id}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n This could also be achieved by supplying the post id to the adapter via the adapterOptions\n property on the options hash.\n\n ```js [app/routes/post-comments.js]\n export default class PostRoute extends Route {\n model({ post_id, comment_id: id }) {\n return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });\n }\n }\n ```\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'comment')\n let postId = snapshot.adapterOptions.post;\n\n return fetch(`./posts/${postId}/comments/${id}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n If you have access to the post model you can also pass the model itself to preload:\n\n ```javascript\n let post = await store.findRecord('post', '1');\n let comment = await store.findRecord('comment', '2', { post: myPostModel });\n ```\n\n ### Reloading\n\n The reload behavior is configured either via the passed `options` hash or\n the result of the adapter's `shouldReloadRecord`.\n\n If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates\n to `true`, then the returned promise resolves once the adapter returns\n data, regardless if the requested record is already in the store:\n\n ```js\n store.push({\n data: {\n id: 1,\n type: 'post',\n revision: 1\n }\n });\n\n // adapter#findRecord resolves with\n // [\n // {\n // id: 1,\n // type: 'post',\n // revision: 2\n // }\n // ]\n store.findRecord('post', '1', { reload: true }).then(function(post) {\n post.revision; // 2\n });\n ```\n\n If no reload is indicated via the above mentioned ways, then the promise\n immediately resolves with the cached version in the store.\n\n ### Background Reloading\n\n Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,\n then a background reload is started, which updates the records' data, once\n it is available:\n\n ```js\n // app/adapters/post.js\n import ApplicationAdapter from \"./application\";\n\n export default class PostAdapter extends ApplicationAdapter {\n shouldReloadRecord(store, snapshot) {\n return false;\n },\n\n shouldBackgroundReloadRecord(store, snapshot) {\n return true;\n }\n });\n\n // ...\n\n store.push({\n data: {\n id: 1,\n type: 'post',\n revision: 1\n }\n });\n\n let blogPost = store.findRecord('post', '1').then(function(post) {\n post.revision; // 1\n });\n\n // later, once adapter#findRecord resolved with\n // [\n // {\n // id: 1,\n // type: 'post',\n // revision: 2\n // }\n // ]\n\n blogPost.revision; // 2\n ```\n\n If you would like to force or prevent background reloading, you can set a\n boolean value for `backgroundReload` in the options object for\n `findRecord`.\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { backgroundReload: false });\n }\n }\n ```\n\n If you pass an object on the `adapterOptions` property of the options\n argument it will be passed to your adapter via the snapshot\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, {\n adapterOptions: { subscribe: false }\n });\n }\n }\n ```\n\n ```js [app/adapters/post.js]\n import MyCustomAdapter from './custom-adapter';\n\n export default class PostAdapter extends MyCustomAdapter {\n findRecord(store, type, id, snapshot) {\n if (snapshot.adapterOptions.subscribe) {\n // ...\n }\n // ...\n }\n }\n ```\n\n See {@link Store.peekRecord | peekRecord} to get the cached version of a record.\n\n ### Retrieving Related Model Records\n\n If you use an adapter such as the\n [JSONAPIAdapter](/api/@warp-drive/legacy/adapter/json-api/classes/JSONAPIAdapter)\n which supports the [{json:api} specification](http://jsonapi.org/) and if your server\n endpoint supports the use of an\n ['include' query parameter](http://jsonapi.org/format/#fetching-includes),\n you can use `findRecord()` or `findAll()` to automatically retrieve additional records related to\n the one you request by supplying an `include` parameter in the `options` object.\n\n For example, given a `post` model that has a `hasMany` relationship with a `comment`\n model, when we retrieve a specific post we can have the server also return that post's\n comments in the same request:\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { include: ['comments'] });\n }\n }\n ```\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'post')\n let includes = snapshot.adapterOptions.include;\n\n return fetch(`./posts/${postId}?include=${includes}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n In this case, the post's comments would then be available in your template as\n `model.comments`.\n\n Multiple relationships can be requested using an `include` parameter consisting of a\n list of relationship names, while nested relationships can be specified\n using a dot-separated sequence of relationship names. So to request both the post's\n comments and the authors of those comments the request would look like this:\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });\n }\n }\n ```\n\n ### Retrieving Specific Fields by Type\n\n If your server endpoint supports the use of a ['fields' query parameter](https://jsonapi.org/format/#fetching-sparse-fieldsets),\n you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.\n\n 1. Implement `buildQuery` in your adapter.\n\n ```js [app/adapters/application.js]\n buildQuery(snapshot) {\n let query = super.buildQuery(...arguments);\n\n let { fields } = snapshot.adapterOptions;\n\n if (fields) {\n query.fields = fields;\n }\n\n return query;\n }\n ```\n\n 2. Then pass through the applicable fields to your `findRecord` request.\n\n Given a `post` model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.\n\n ```js [app/routes/post.js]\n export default class extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });\n }\n }\n ```\n\n Moreover, you can filter attributes on related models as well. If a `post` has a `belongsTo` relationship to a user,\n just include the relationship key and attributes.\n\n ```js [app/routes/post.js]\n export default class extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });\n }\n }\n ```\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type - either a string representing the name of the resource or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record\n @param id - optional object with options for the request only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved\n @param options - if the first param is a string this will be the optional options for the request. See examples for available options.\n */\n findRecord<T>(type: TypeFromInstance<T>, id: string | number, options?: FindRecordOptions): Promise<T>;\n /** @deprecated */\n findRecord(type: string, id: string | number, options?: FindRecordOptions): Promise<unknown>;\n /** @deprecated */\n findRecord<T>(resource: ResourceIdentifierObject<TypeFromInstance<T>>, options?: FindRecordOptions): Promise<T>;\n /** @deprecated */\n findRecord(resource: ResourceIdentifierObject, options?: FindRecordOptions): Promise<unknown>;\n\n /**\n `findAll` asks the adapter's `findAll` method to find the records for the\n given type, and returns a promise which will resolve with all records of\n this type present in the store, even if the adapter only returns a subset\n of them.\n\n ```js [app/routes/authors.js]\n export default class AuthorsRoute extends Route {\n model(params) {\n return this.store.findAll('author');\n }\n }\n ```\n\n _When_ the returned promise resolves depends on the reload behavior,\n configured via the passed `options` hash and the result of the adapter's\n `shouldReloadAll` method.\n\n ### Reloading\n\n If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to\n `true`, then the returned promise resolves once the adapter returns data,\n regardless if there are already records in the store:\n\n ```js\n store.push({\n data: {\n id: 'first',\n type: 'author'\n }\n });\n\n // adapter#findAll resolves with\n // [\n // {\n // id: 'second',\n // type: 'author'\n // }\n // ]\n store.findAll('author', { reload: true }).then(function(authors) {\n authors.getEach('id'); // ['first', 'second']\n });\n ```\n\n If no reload is indicated via the above mentioned ways, then the promise\n immediately resolves with all the records currently loaded in the store.\n\n ### Background Reloading\n\n Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,\n then a background reload is started. Once this resolves, the array with\n which the promise resolves, is updated automatically so it contains all the\n records in the store:\n\n ```js [app/adapters/application.js]\n import { Adapter } from '@warp-drive/legacy/adapter';\n\n export default class ApplicationAdapter extends Adapter {\n shouldReloadAll(store, snapshotsArray) {\n return false;\n },\n\n shouldBackgroundReloadAll(store, snapshotsArray) {\n return true;\n }\n });\n\n // ...\n\n store.push({\n data: {\n id: 'first',\n type: 'author'\n }\n });\n\n let allAuthors;\n store.findAll('author').then(function(authors) {\n authors.getEach('id'); // ['first']\n\n allAuthors = authors;\n });\n\n // later, once adapter#findAll resolved with\n // [\n // {\n // id: 'second',\n // type: 'author'\n // }\n // ]\n\n allAuthors.getEach('id'); // ['first', 'second']\n ```\n\n If you would like to force or prevent background reloading, you can set a\n boolean value for `backgroundReload` in the options object for\n `findAll`.\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model() {\n return this.store.findAll('post', { backgroundReload: false });\n }\n }\n ```\n\n If you pass an object on the `adapterOptions` property of the options\n argument it will be passed to you adapter via the `snapshotRecordArray`\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model(params) {\n return this.store.findAll('post', {\n adapterOptions: { subscribe: false }\n });\n }\n }\n ```\n\n ```js [app/adapters/post.js]\n import MyCustomAdapter from './custom-adapter';\n\n export default class UserAdapter extends MyCustomAdapter {\n findAll(store, type, sinceToken, snapshotRecordArray) {\n if (snapshotRecordArray.adapterOptions.subscribe) {\n // ...\n }\n // ...\n }\n }\n ```\n\n See {@link Store.peekAll | peekAll} to get an array of current records in the\n store, without waiting until a reload is finished.\n\n ### Retrieving Related Model Records\n\n If you use an adapter such as the default\n [JSONAPIAdapter](/api/@warp-drive/legacy/adapter/json-api/classes/JSONAPIAdapter)\n that supports the [JSON API specification](http://jsonapi.org/) and if your server\n endpoint supports the use of an\n ['include' query parameter](http://jsonapi.org/format/#fetching-includes),\n you can use `findAll()` to automatically retrieve additional records related to\n those requested by supplying an `include` parameter in the `options` object.\n\n For example, given a `post` model that has a `hasMany` relationship with a `comment`\n model, when we retrieve all of the post records we can have the server also return\n all of the posts' comments in the same request:\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model() {\n return this.store.findAll('post', { include: ['comments'] });\n }\n }\n ```\n Multiple relationships can be requested using an `include` parameter consisting of a\n list or relationship names, while nested relationships can be specified\n using a dot-separated sequence of relationship names. So to request both the posts'\n comments and the authors of those comments the request would look like this:\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model() {\n return this.store.findAll('post', { include: ['comments','comments.author'] });\n }\n }\n ```\n\n See {@link Store.query | query} to only get a subset of records from the server.\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type the name of the resource\n @param options\n */\n findAll<T>(type: TypeFromInstance<T>, options?: FindAllOptions): Promise<LegacyLiveArray<T>>;\n /** @deprecated */\n findAll(type: string, options?: FindAllOptions): Promise<LegacyLiveArray>;\n\n /**\n This method delegates a query to the adapter. This is the one place where\n adapter-level semantics are exposed to the application.\n\n Each time this method is called a new request is made through the adapter.\n\n Exposing queries this way seems preferable to creating an abstract query\n language for all server-side queries, and then require all adapters to\n implement them.\n\n ---\n\n If you do something like this:\n\n ```js\n store.query('person', { page: 1 });\n ```\n\n The request made to the server will look something like this:\n\n ```http\n GET \"/api/v1/person?page=1\"\n ```\n\n ---\n\n If you do something like this:\n\n ```js\n store.query('person', { ids: ['1', '2', '3'] });\n ```\n\n The request made to the server will look something like this:\n\n ```\n GET \"/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3\"\n decoded: \"/api/v1/person?ids[]=1&ids[]=2&ids[]=3\"\n ```\n\n This method returns a promise, which is resolved with a\n {@link LegacyQueryArray} once the server returns.\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type the name of the resource\n @param query a query to be used by the adapter\n @param options optional, may include `adapterOptions` hash which will be passed to adapter.query\n */\n query<T>(type: TypeFromInstance<T>, query: LegacyResourceQuery, options?: QueryOptions): Promise<LegacyQueryArray<T>>;\n /** @deprecated */\n query(type: string, query: LegacyResourceQuery, options?: QueryOptions): Promise<LegacyQueryArray>;\n\n /**\n This method makes a request for one record, where the `id` is not known\n beforehand (if the `id` is known, use {@link Store.findRecord | findRecord}\n instead).\n\n This method can be used when it is certain that the server will return a\n single object for the primary data.\n\n Each time this method is called a new request is made through the adapter.\n\n Let's assume our API provides an endpoint for the currently logged in user\n\n ```ts\n // GET /api/user/me\n {\n data: {\n type: 'user',\n id: '1234',\n attributes: {\n username: 'admin'\n }\n }\n }\n ```\n\n Since the specific `id` of the `user` is not known beforehand, we can use\n `queryRecord` to get the user:\n\n ```ts\n const user = await store.queryRecord('user', { me: true });\n user.username; // admin\n ```\n\n The request is made through the adapters' `queryRecord`:\n\n ```ts [app/adapters/user.ts]\n import Adapter from '@warp-drive/legacy/adapter';\n\n export default class UserAdapter extends Adapter {\n async queryRecord(modelName, query) {\n if (query.me) {\n const response = await fetch('/api/me');\n return await response.json();\n }\n throw new Error('Unsupported query');\n }\n }\n ```\n\n Note: the primary use case for `store.queryRecord` is when a single record\n is queried and the `id` is not known beforehand. In all other cases\n `store.query` and using the first item of the array is likely the preferred\n way:\n\n ```\n // GET /users?username=unique\n {\n data: [{\n id: 1234,\n type: 'user',\n attributes: {\n username: \"unique\"\n }\n }]\n }\n ```\n\n ```js\n store.query('user', { username: 'unique' }).then(function(users) {\n return users.firstObject;\n }).then(function(user) {\n let id = user.id;\n });\n ```\n\n This method returns a promise, which resolves with the found record.\n\n If the adapter returns no data for the primary data of the payload, then\n `queryRecord` resolves with `null`:\n\n ```\n // GET /users?username=unique\n {\n data: null\n }\n ```\n\n ```js\n store.queryRecord('user', { username: 'unique' }).then(function(user) {\n // user is null\n });\n ```\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type\n @param query an opaque query to be used by the adapter\n @param options optional, may include `adapterOptions` hash which will be passed to adapter.queryRecord\n @return promise which resolves with the found record or `null`\n */\n queryRecord<T>(type: TypeFromInstance<T>, query: LegacyResourceQuery, options?: QueryOptions): Promise<T | null>;\n /** @deprecated */\n queryRecord(type: string, query: LegacyResourceQuery, options?: QueryOptions): Promise<unknown | null>;\n\n /**\n Get the reference for the specified record.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', '1');\n\n // check if the user is loaded\n let isLoaded = userRef.value() !== null;\n\n // get the record of the reference (null if not yet available)\n let user = userRef.value();\n\n // get the identifier of the reference\n if (userRef.remoteType() === 'id') {\n let id = userRef.id();\n }\n\n // load user (via store.find)\n userRef.load().then(...)\n\n // or trigger a reload\n userRef.reload().then(...)\n\n // provide data for reference\n userRef.push({ id: 1, username: '@user' }).then(function(user) {\n userRef.value() === user;\n });\n ```\n\n @public\n @deprecated use {@link Store.request} for loading and {@link Store.cache} for direct data insertion instead\n @until 6.0\n @since 2.5.0\n @param resource - modelName (string) or Identifier (object)\n @param id\n */\n getReference(resource: string | ResourceIdentifierObject, id: string | number): RecordReference;\n\n /**\n Returns the schema for a particular resource type (modelName).\n\n When used with [Model](/api/@warp-drive/legacy/model/classes/Model) the return is the model class,\n but this is not guaranteed.\n\n If looking to query attribute or relationship information it is\n recommended to use `getSchemaDefinitionService` instead. This method\n should be considered legacy and exists primarily to continue to support\n Adapter/Serializer APIs which expect it's return value in their method\n signatures.\n\n The class of a model might be useful if you want to get a list of all the\n relationship names of the model.\n\n @public\n @deprecated use {@link Store.schema} instead\n @until 6.0\n @param type\n */\n modelFor<T>(type: TypeFromInstance<T>): ModelSchema<T>;\n /** @deprecated */\n modelFor(type: string): ModelSchema;\n\n /**\n * Trigger a save for a Record.\n *\n * Returns a promise resolving with the same record when the save is complete.\n *\n * @deprecated use {@link Store.request} instead\n * @until 6.0\n * @public\n * @param record\n * @param options\n */\n saveRecord<T>(record: T, options?: Record<string, unknown>): Promise<T>;\n}\n\n/**\n * ```ts\n * import { Store } from '@warp-drive/core';\n * ```\n *\n * The `Store` is the central piece of the ***Warp*Drive** experience. It connects\n * requests for data with schemas, caching and reactivity.\n *\n * While it's easy to use ***just*** ***Warp*Drive**'s request management, most projects will find they\n * require far more than basic fetch management. For this reason it's often best to start with a `Store`\n * even when you aren't sure yet.\n *\n * Most projects will only have a single `Store`, though using multiple distinct stores\n * is possible.\n *\n * @public\n * @hideconstructor\n */\nexport class Store extends BaseClass {\n /** @internal */\n declare readonly recordArrayManager: RecordArrayManager;\n\n /**\n * Provides access to the {@link NotificationManager} associated\n * with this Store instance.\n *\n * The NotificationManager can be used to subscribe to\n * changes to the cache.\n *\n * @public\n */\n declare readonly notifications: NotificationManager;\n\n /**\n * Provides access to the SchemaService instance\n * for this Store instance.\n *\n * The SchemaService can be used to query for\n * information about the schema of a resource.\n *\n * @public\n */\n get schema(): ReturnType<this['createSchemaService']> {\n if (!this._schema) {\n this._schema = this.createSchemaService();\n }\n return this._schema as ReturnType<this['createSchemaService']>;\n }\n /** @internal */\n declare _schema: SchemaService;\n\n /**\n * Provides access to the CacheKeyManager\n * for this store.\n *\n * The CacheKeyManager can be used to generate or\n * retrieve a stable unique CacheKey for any resource\n * or request.\n *\n * @public\n */\n declare readonly cacheKeyManager: CacheKeyManager;\n /**\n * Provides access to the {@link RequestManager} instance associated\n * with this Store instance.\n *\n * See also:\n * - {@link Fetch}\n * - {@link CacheHandlerInterface | CacheHandler (Interface)}\n * - {@link CacheHandler | CacheHandler (Class)}\n *\n * ```ts\n * import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core';\n *\n * class AppStore extends Store {\n * requestManager = new RequestManager()\n * .use([Fetch])\n * .useCache(CacheHandler);\n * }\n * ```\n *\n * @public\n */\n declare requestManager: RequestManager;\n\n /**\n * A Property which an App may set to provide a CachePolicy\n * to control when a cached request becomes stale.\n *\n * Note, when defined, these methods will only be invoked if a\n * cache key exists for the request, either because the request\n * contains `cacheOptions.key` or because the {@link CacheKeyManager}\n * was able to generate a key for the request using the configured\n * {@link setIdentifierGenerationMethod | generation method}.\n *\n * `isSoftExpired` will only be invoked if `isHardExpired` returns `false`.\n *\n * ```ts\n * store.lifetimes = {\n * // make the request and ignore the current cache state\n * isHardExpired(key: RequestKey): boolean {\n * return false;\n * }\n *\n * // make the request in the background if true, return cache state\n * isSoftExpired(key: RequestKey): boolean {\n * return false;\n * }\n * }\n * ```\n *\n * @public\n */\n declare lifetimes?: CachePolicy;\n\n // Private\n /** @internal */\n declare _graph?: Graph;\n /** @internal */\n declare _requestCache: RequestStateService;\n /** @internal */\n declare _instanceCache: InstanceCache;\n /** @internal */\n declare _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;\n /** @internal */\n declare _forceShim: boolean;\n /**\n * Async flush buffers notifications until flushed\n * by finalization of a future configured by store.request\n *\n * This is useful for ensuring that notifications are delivered\n * prior to the promise resolving but without risk of promise\n * interleaving.\n *\n * @internal\n */\n declare _enableAsyncFlush: boolean | null;\n\n /**\n * Available in DEBUG Only\n * @internal\n */\n declare DISABLE_WAITER?: boolean;\n /** @internal */\n declare _isDestroying: boolean;\n /** @internal */\n declare _isDestroyed: boolean;\n\n /** @private */\n get isDestroying(): boolean {\n return this._isDestroying;\n }\n /** @internal */\n set isDestroying(value: boolean) {\n this._isDestroying = value;\n }\n /** @private */\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n /** @internal */\n set isDestroyed(value: boolean) {\n this._isDestroyed = value;\n }\n\n /** @deprecated use {@link Store.cacheKeyManager} */\n get identifierCache(): CacheKeyManager {\n return this.cacheKeyManager;\n }\n\n /**\n @private\n */\n constructor(createArgs?: unknown) {\n super(createArgs);\n Object.assign(this, createArgs);\n\n this.cacheKeyManager = new CacheKeyManager();\n\n this.notifications = new NotificationManager(this);\n\n // private but maybe useful to be here, somewhat intimate\n this.recordArrayManager = new RecordArrayManager({ store: this });\n\n // private\n this._requestCache = new RequestStateService(this);\n this._instanceCache = new InstanceCache(this);\n\n this.isDestroying = false;\n this.isDestroyed = false;\n }\n\n /** @internal */\n _run(cb: () => void): void {\n assert(`WarpDrive should never encounter a nested run`, !this._cbs);\n const _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } = (this._cbs = {});\n if (DEBUG) {\n try {\n cb();\n if (_cbs.coalesce) {\n _cbs.coalesce();\n }\n if (_cbs.sync) {\n _cbs.sync();\n }\n if (_cbs.notify) {\n _cbs.notify();\n }\n } finally {\n this._cbs = null;\n }\n } else {\n cb();\n if (_cbs.coalesce) {\n _cbs.coalesce();\n }\n if (_cbs.sync) {\n _cbs.sync();\n }\n if (_cbs.notify) {\n _cbs.notify();\n }\n this._cbs = null;\n }\n }\n\n /**\n * Executes the callback, ensurng that any work that calls\n * store._schedule is executed after in the right order.\n *\n * When queues already exist, scheduled callbacks will\n * join the existing queue.\n *\n * @internal\n */\n _join(cb: () => void): void {\n if (this._cbs) {\n cb();\n } else {\n this._run(cb);\n }\n }\n\n /** @internal */\n _schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void {\n assert(`WarpDrive expects to schedule only when there is an active run`, !!this._cbs);\n assert(`WarpDrive expects only one flush per queue name, cannot schedule ${name}`, !this._cbs[name]);\n\n this._cbs[name] = cb;\n }\n\n /**\n * Retrieve the RequestStateService instance\n * associated with this Store.\n *\n * This can be used to query the status of requests\n * that have been initiated for a given identifier.\n *\n * @return {RequestStateService}\n * @public\n */\n getRequestStateService(): RequestStateService {\n return this._requestCache;\n }\n\n /** @internal */\n _getAllPending(): (Promise<unknown[]> & { length: number }) | void {\n if (TESTING) {\n const all: Promise<unknown>[] = [];\n const pending = this._requestCache._pending;\n\n pending.forEach((requests) => {\n all.push(...requests.map((v) => v[RequestPromise]!));\n });\n this.requestManager._pending.forEach((v) => all.push(v));\n const promise: Promise<unknown[]> & { length: number } = Promise.allSettled(all) as Promise<unknown[]> & {\n length: number;\n };\n promise.length = all.length;\n return promise;\n }\n }\n\n /**\n * ::: tip 💡 For a more complete overview see the [Request Guide](/guides/2-requests/1-overview)\n * :::\n *\n * Issue a request via the configured {@link RequestManager},\n * inserting the response into the {@link Store.cache | cache} and handing\n * back a {@link Future} which resolves to a {@link ReactiveDocument | ReactiveDocument}\n *\n * #### Request Cache Keys\n *\n * Only {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/GET | GET} requests with a url or requests with an explicit\n * {@link CacheOptions.key | cache key} will have the request result\n * and document cached.\n *\n * The cache key used is {@link RequestInfo.cacheOptions.key | RequestInfo.cacheOptions.key}\n * if present, falling back to {@link RequestInfo.url}.\n *\n * Params are not serialized as part of the cache-key, so\n * either ensure they are already in the url or utilize\n * `requestConfig.cacheOptions.key`. For queries issued\n * via the {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/POST | POST} method `requestConfig.cacheOptions.key`\n * MUST be supplied for the document to be cached.\n *\n * #### Requesting Without a Cache Key\n *\n * Resource data within the request is always updated in the cache,\n * regardless of whether a cache key is present for the request.\n *\n * #### Fulfilling From Cache\n *\n * When a cache-key is determined, the request may fulfill\n * from cache provided the cache is not stale.\n *\n * Cache staleness is determined by the configured {@link CachePolicy}\n * with priority given to the {@link CacheOptions.reload} and\n * {@link CacheOptions.backgroundReload} on the request if present.\n *\n * If the cache data has soft expired or the request asks for a background\n * reload, the request will fulfill from cache if possible and\n * make a non-blocking request in the background to update the cache.\n *\n * If the cache data has hard expired or the request asks for a reload,\n * the request will not fulfill from cache and will make a blocking\n * request to update the cache.\n *\n * #### The Response\n *\n * The primary difference between {@link RequestManager.request} and `store.request`\n * is that `store.request` will convert the response into a {@link ReactiveDocument}\n * containing {@link Store.instantiateRecord | ReactiveResources}.\n *\n * @public\n */\n request<RT>(requestConfig: StoreRequestInput<RT>): Future<RT> {\n // we lazily set the cache handler when we issue the first request\n // because constructor doesn't allow for this to run after\n // the user has had the chance to set the prop.\n const opts: {\n store: Store;\n disableTestWaiter?: boolean;\n [EnableHydration]: boolean;\n records?: ResourceKey[];\n } = {\n store: this,\n [EnableHydration]: requestConfig[EnableHydration] ?? true,\n };\n\n if (requestConfig.records) {\n const cacheKeyManager = this.cacheKeyManager;\n opts.records = requestConfig.records.map((r) => cacheKeyManager.getOrCreateRecordIdentifier(r));\n }\n\n if (TESTING) {\n if (this.DISABLE_WAITER) {\n opts.disableTestWaiter =\n typeof requestConfig.disableTestWaiter === 'boolean' ? requestConfig.disableTestWaiter : true;\n }\n }\n\n if (LOG_REQUESTS) {\n let options: unknown;\n try {\n options = JSON.parse(JSON.stringify(requestConfig));\n } catch {\n options = requestConfig;\n }\n // oxlint-disable-next-line no-console\n console.log(\n `request: [[START]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${\n requestConfig.op || '<unknown operation>'\n } ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`,\n options\n );\n }\n\n const request = Object.assign({}, requestConfig, opts);\n const future = this.requestManager.request(request);\n\n future.onFinalize(() => {\n if (LOG_REQUESTS) {\n // oxlint-disable-next-line no-console\n console.log(\n `request: [[FINALIZE]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${\n requestConfig.op || '<unknown operation>'\n } ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`\n );\n }\n // skip flush for legacy belongsTo\n if (requestConfig.op === 'findBelongsTo' && !requestConfig.url) {\n return;\n }\n this.notifications._flush();\n });\n\n return future;\n }\n\n /**\n Creates a new record in the current store.\n\n > [!CAUTION]\n > This should not be used to mock records or to create\n > a record representing data that could be fetched from\n > the API.\n\n The properties passed to this method are set on\n the newly created record.\n\n For instance: to create a new `post`:\n\n ```js\n store.createRecord('post', {\n title: 'WarpDrive is Stellar!'\n });\n ```\n\n Relationships can be set during create. For instance,\n to create a new `post` that has an existing user as\n it's author:\n\n ```js\n const user = store.peekRecord('user', '1');\n\n store.createRecord('post', {\n title: 'WarpDrive is Stellar!',\n user: user\n });\n ```\n\n ### lid handling\n\n All new records are assigned an `lid` that can be used to handle\n transactional saves of multiple records, or to link the data to\n other data in scenarios involving eventual-consistency or remote\n syncing.\n\n ```ts\n const post = store.createRecord('post', {\n title: 'WarpDrive is Stellar!'\n });\n const { lid } = recordIdentifierFor(post);\n ```\n\n The `lid` defaults to a uuidv4 string.\n\n In order to support receiving knowledge about unpersisted creates\n from other sources (say a different tab in the same web-browser),\n createRecord allows for the `lid` to be provided as part of an\n optional third argument. **If this lid already exists in the store\n an error will be thrown.**\n\n ```ts\n const post = store.createRecord(\n 'post',\n { title: 'WarpDrive is Stellar!' },\n { lid: '4d47bb88-931f-496e-986d-c4888cef7373' }\n );\n ```\n\n @public\n @param type the name of the resource\n @param inputProperties a hash of properties to set on the\n newly created record.\n @return a record in the \"isNew\" state\n */\n createRecord<T>(type: TypeFromInstance<T>, inputProperties: CreateRecordProperties<T>, context?: CreateContext): T;\n createRecord(type: string, inputProperties: CreateRecordProperties, context?: CreateContext): OpaqueRecordInstance;\n createRecord(type: string, inputProperties: CreateRecordProperties, context?: CreateContext): OpaqueRecordInstance {\n if (DEBUG) {\n assertDestroyingStore(this, 'createRecord');\n }\n assert(`You need to pass a model name to the store's createRecord method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n // This is wrapped in a `run.join` so that in test environments users do not need to manually wrap\n // calls to `createRecord`. The run loop usage here is because we batch the joining and updating\n // of record-arrays via ember's run loop, not our own.\n //\n // to remove this, we would need to move to a new `async` API.\n let record!: OpaqueRecordInstance;\n this._join(() => {\n const normalizedModelName = normalizeModelName(type);\n const properties = { ...inputProperties };\n\n // If the passed properties do not include a primary key,\n // give the adapter an opportunity to generate one. Typically,\n // client-side ID generators will use something like uuid.js\n // to avoid conflicts.\n let id: string | null;\n\n if (properties.id === null || properties.id === undefined) {\n upgradeStore(this);\n const adapter = this.adapterFor?.(normalizedModelName, true);\n\n if (adapter && adapter.generateIdForRecord) {\n id = properties.id = coerceId(adapter.generateIdForRecord(this, normalizedModelName, properties));\n } else {\n id = properties.id = null;\n }\n } else {\n id = properties.id = coerceId(properties.id);\n }\n\n const resource: { type: string; id: string | null; lid?: string } = { type: normalizedModelName, id };\n\n if (resource.id) {\n const identifier = this.cacheKeyManager.peekResourceKey(resource as ResourceIdentifierObject);\n\n assert(\n `The id ${String(properties.id)} has already been used with another '${normalizedModelName}' record.`,\n !identifier\n );\n }\n\n if (context?.lid) {\n const identifier = this.cacheKeyManager.peekResourceKey({ lid: context?.lid });\n resource.lid = context.lid;\n assert(`The lid ${context.lid} has already been used with another '${identifier?.type}' record.`, !identifier);\n }\n\n const identifier = this.cacheKeyManager.createIdentifierForNewRecord(resource);\n const cache = this.cache;\n\n const createOptions = normalizeProperties(this, identifier, properties);\n const resultProps = cache.clientDidCreate(identifier, createOptions);\n\n record = getNewRecord(this._instanceCache, identifier, resultProps);\n });\n return record;\n }\n\n /**\n For symmetry, a record can be deleted via the store.\n\n Example\n\n ```javascript\n let post = store.createRecord('post', {\n title: 'Ember is awesome!'\n });\n\n store.deleteRecord(post);\n ```\n\n @public\n @param {unknown} record\n */\n deleteRecord<T>(record: T): void {\n if (DEBUG) {\n assertDestroyingStore(this, 'deleteRecord');\n }\n\n const identifier = peekResourceKey(record);\n const cache = this.cache;\n assert(`expected the record to be connected to a cache`, identifier);\n this._join(() => {\n cache.setIsDeleted(identifier, true);\n\n if (cache.isNew(identifier)) {\n this._instanceCache.unloadRecord(identifier);\n }\n });\n }\n\n /**\n For symmetry, a record can be unloaded via the store.\n This will cause the record to be destroyed and freed up for garbage collection.\n\n Example\n\n ```javascript\n const { content: { data: post } } = await store.request(findRecord({ type: 'post', id: '1' }));\n store.unloadRecord(post);\n ```\n\n @public\n @param {Model} record\n */\n unloadRecord<T>(record: T): void {\n if (DEBUG) {\n assertDestroyingStore(this, 'unloadRecord');\n }\n const identifier = peekResourceKey(record);\n if (identifier) {\n this._instanceCache.unloadRecord(identifier);\n }\n }\n\n /**\n Get a record by a given type and ID without triggering a fetch.\n\n This method will synchronously return the record if it is available in the store,\n otherwise it will return `null`. A record is available if it has been fetched earlier, or\n pushed manually into the store.\n\n **Example 1**\n\n ```ts\n const post = store.peekRecord('post', '1');\n\n post.id; // '1'\n ```\n\n `peekRecord` can be called with a single identifier argument instead of the combination\n of `type` (modelName) and `id` as separate arguments. You may recognize this combo as\n the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)\n\n **Example 2**\n\n ```ts\n const post = store.peekRecord({ type: 'post', id: '1' });\n post.id; // '1'\n ```\n\n If you have previously received an lid from an Identifier for this record, you can lookup the record again using\n just the lid.\n\n **Example 3**\n\n ```js\n let post = store.peekRecord({ lid });\n post.id; // '1'\n ```\n\n @since 1.13.0\n @public\n @param type - either a string representing the modelName or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record\n @param id - optional only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved.\n */\n peekRecord<T>(type: TypeFromInstance<T>, id: string | number): T | null;\n peekRecord(type: string, id: string | number): unknown | null;\n peekRecord<T>(identifier: ResourceIdentifierObject<TypeFromInstance<T>>): T | null;\n peekRecord(identifier: ResourceIdentifierObject): unknown | null;\n peekRecord<T = OpaqueRecordInstance>(identifier: ResourceIdentifierObject | string, id?: string | number): T | null {\n if (arguments.length === 1 && isMaybeIdentifier(identifier)) {\n const stableIdentifier = this.cacheKeyManager.peekResourceKey(identifier);\n const isLoaded = stableIdentifier && this._instanceCache.recordIsLoaded(stableIdentifier);\n // TODO come up with a better mechanism for determining if we have data and could peek.\n // this is basically an \"are we not empty\" query.\n return isLoaded ? (this._instanceCache.getRecord(stableIdentifier) as T) : null;\n }\n\n if (DEBUG) {\n assertDestroyingStore(this, 'peekRecord');\n }\n\n assert(`You need to pass a model name to the store's peekRecord method`, identifier);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${String(\n identifier\n )}`,\n typeof identifier === 'string'\n );\n\n const type = normalizeModelName(identifier);\n const normalizedId = ensureStringId(id);\n const resource = { type, id: normalizedId };\n const stableIdentifier = this.cacheKeyManager.peekResourceKey(resource);\n const isLoaded = stableIdentifier && this._instanceCache.recordIsLoaded(stableIdentifier);\n\n return isLoaded ? (this._instanceCache.getRecord(stableIdentifier) as T) : null;\n }\n\n /**\n This method returns the {@link LegacyLiveArray} that contains all of the\n known records for a given type in the store. Each ResourceType has only\n one LiveArray instance, so multiple calls to `peekAll` with the same type\n will always return the same instance.\n\n Note that because it's a LiveArray, the result will contain any\n locally created records of the type, however, it will not make a\n request to the backend to retrieve additional records.\n\n Example\n\n ```ts\n const allPosts = store.peekAll('post');\n ```\n\n @since 1.13.0\n @public\n @param type the name of the resource\n */\n peekAll<T>(type: TypeFromInstance<T>): LegacyLiveArray<T>;\n peekAll(type: string): LegacyLiveArray;\n peekAll(type: string): LegacyLiveArray {\n if (DEBUG) {\n assertDestroyingStore(this, 'peekAll');\n }\n assert(`You need to pass a model name to the store's peekAll method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n return this.recordArrayManager.liveArrayFor(normalizeModelName(type));\n }\n\n /**\n This method unloads all records in the store.\n It schedules unloading to happen during the next run loop.\n\n Optionally you can pass a type which unload all records for a given type.\n\n ```javascript\n store.unloadAll();\n store.unloadAll('post');\n ```\n\n @param {String} type the name of the resource\n @public\n */\n unloadAll<T>(type: TypeFromInstance<T>): void;\n unloadAll(type?: string): void;\n unloadAll(type?: string) {\n if (DEBUG) {\n assertDestroyedStoreOnly(this, 'unloadAll');\n }\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${String(type)}`,\n !type || typeof type === 'string'\n );\n assertPrivateStore(this);\n\n this._join(() => {\n this._enableAsyncFlush = true;\n if (type === undefined) {\n this.recordArrayManager.pause();\n // destroy the graph before unloadAll\n // since then we avoid churning relationships\n // during unload\n this._graph?.identifiers.clear();\n\n this.recordArrayManager.clear();\n this._instanceCache.clear();\n } else {\n this._instanceCache.clear(normalizeModelName(type));\n }\n this._enableAsyncFlush = null;\n this.notifications._flush();\n if (type === undefined) {\n this.recordArrayManager.resume();\n }\n });\n }\n\n /**\n Push some data for a given type into the store.\n\n This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments:\n - record's `type` should always be in singular, dasherized form\n - members (properties) should be camelCased\n\n [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level):\n\n ```js\n store.push({\n data: {\n // primary data for single record of type `Person`\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Daniel',\n lastName: 'Kmak'\n }\n }\n });\n ```\n\n [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7)\n\n `data` property can also hold an array (of records):\n\n ```js\n store.push({\n data: [\n // an array of records\n {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Daniel',\n lastName: 'Kmak'\n }\n },\n {\n id: '2',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n }\n }\n ]\n });\n ```\n\n [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355)\n\n There are some typical properties for `JSONAPI` payload:\n * `id` - mandatory, unique record's key\n * `type` - mandatory string which matches `model`'s dasherized name in singular form\n * `attributes` - object which holds data for record attributes - `attr`'s declared in model\n * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`):\n - [`links`](http://jsonapi.org/format/#document-links)\n - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data\n - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship\n\n For this model:\n\n ```js [app/models/person.js]\n import Model, { attr, hasMany } from '@warp-drive/legacy/model';\n\n export default class PersonRoute extends Route {\n @attr('string') firstName;\n @attr('string') lastName;\n\n @hasMany('person') children;\n }\n ```\n\n To represent the children as IDs:\n\n ```js\n {\n data: {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n },\n relationships: {\n children: {\n data: [\n {\n id: '2',\n type: 'person'\n },\n {\n id: '3',\n type: 'person'\n },\n {\n id: '4',\n type: 'person'\n }\n ]\n }\n }\n }\n }\n ```\n\n [Demo.](http://ember-twiddle.com/343e1735e034091f5bde)\n\n To represent the children relationship as a URL:\n\n ```js\n {\n data: {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n },\n relationships: {\n children: {\n links: {\n related: '/people/1/children'\n }\n }\n }\n }\n }\n ```\n\n If you're streaming data, or implementing response handling, make sure\n that you have converted the incoming data into this form.\n\n This method can be used both to push in brand new\n records, as well as to update existing records.\n\n See also {@link Cache.patch}\n\n @public\n @param data\n @return the primary record(s) that created or updated.\n */\n push(data: EmptyResourceDocument): null;\n push<T>(data: SingleResourceDocument<TypeFromInstance<T>>): T;\n push(data: SingleResourceDocument): OpaqueRecordInstance;\n push<T>(data: CollectionResourceDocument<TypeFromInstance<T>>): T[];\n push(data: CollectionResourceDocument): OpaqueRecordInstance[];\n push(data: JsonApiDocument): OpaqueRecordInstance | OpaqueRecordInstance[] | null {\n if (DEBUG) {\n assertDestroyingStore(this, 'push');\n }\n const pushed = this._push(data, false);\n\n if (Array.isArray(pushed)) {\n return pushed.map((identifier) => this._instanceCache.getRecord(identifier));\n }\n\n if (pushed === null) {\n return null;\n }\n\n return this._instanceCache.getRecord(pushed);\n }\n\n /**\n Push some data in the form of a json-api document into the store,\n without creating materialized records.\n\n @private\n @return identifiers for the primary records that had data loaded\n */\n _push(jsonApiDoc: JsonApiDocument, asyncFlush?: boolean): PersistedResourceKey | PersistedResourceKey[] | null {\n if (DEBUG) {\n assertDestroyingStore(this, '_push');\n }\n if (asyncFlush) {\n this._enableAsyncFlush = true;\n }\n\n let ret!: ResourceDocument;\n this._join(() => {\n ret = this.cache.put({ content: jsonApiDoc });\n });\n\n this._enableAsyncFlush = null;\n\n return 'data' in ret ? ret.data : null;\n }\n\n /**\n * Returns the cache instance associated to this Store, instantiates the Cache\n * if necessary via `Store.createCache`\n *\n * @public\n */\n get cache(): ReturnType<this['createCache']> {\n let { cache } = this._instanceCache;\n if (!cache) {\n cache = this._instanceCache.cache = this.createCache(this._instanceCache._storeWrapper);\n if (DEBUG) {\n cache = this._instanceCache.cache = new CacheManager(cache);\n }\n }\n\n return cache as ReturnType<this['createCache']>;\n }\n\n /** @private */\n destroy(): void {\n if (this.isDestroyed) {\n // @ember/test-helpers will call destroy multiple times\n return;\n }\n this.isDestroying = true;\n\n this._graph?.destroy();\n this._graph = undefined;\n\n this.notifications.destroy();\n this.recordArrayManager.destroy();\n this.cacheKeyManager.destroy();\n this._instanceCache.clear();\n this.isDestroyed = true;\n }\n\n /**\n * This method\n *\n * @private\n */\n static create(args?: Record<string, unknown>): Store {\n return new this(args);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateStore extends Store {\n readonly recordArrayManager: PrivateRecordArrayManager;\n notifications: PrivateNotificationManager;\n requestManager: PrivateRequestManager;\n cacheKeyManager: PrivateCacheKeyManager;\n _schema: SchemaService;\n _graph?: Graph;\n _requestCache: PrivateRequestStateService;\n getRequestStateService(): PrivateRequestStateService;\n _instanceCache: InstanceCache;\n _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;\n _forceShim: boolean;\n /**\n * Async flush buffers notifications until flushed\n * by finalization of a future configured by store.request\n *\n * This is useful for ensuring that notifications are delivered\n * prior to the promise resolving but without risk of promise\n * interleaving.\n */\n _enableAsyncFlush: boolean | null;\n\n /**\n * Available in DEBUG Only\n */\n DISABLE_WAITER?: boolean;\n _isDestroying: boolean;\n _isDestroyed: boolean;\n isDestroying: boolean;\n isDestroyed: boolean;\n _run(cb: () => void): void;\n /**\n * Executes the callback, ensurng that any work that calls\n * store._schedule is executed after in the right order.\n *\n * When queues already exist, scheduled callbacks will\n * join the existing queue.\n *\n */\n _join(cb: () => void): void;\n _schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void;\n _getAllPending(): (Promise<unknown[]> & { length: number }) | void;\n}\n\n/**\n * Upgrade the type for Store to PrivateStore, which will also\n * upgrade any associated types to their private equivalents.\n *\n * @private\n */\nexport function assertPrivateStore(store: unknown): asserts store is PrivateStore {}\n/**\n * Upgrade the type for Store to PrivateStore, which will also\n * upgrade any associated types to their private equivalents.\n *\n * @private\n */\nexport function isPrivateStore(store: unknown): PrivateStore {\n return store as PrivateStore;\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n Store.prototype.getSchemaDefinitionService = function (): SchemaService {\n assert(`You must registerSchemaDefinitionService with the store to use custom model classes`, this._schema);\n deprecate(`Use \\`store.schema\\` instead of \\`store.getSchemaDefinitionService()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n return this._schema;\n };\n Store.prototype.registerSchemaDefinitionService = function (schema: SchemaService) {\n deprecate(`Use \\`store.createSchemaService\\` instead of \\`store.registerSchemaDefinitionService()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n this._schema = schema;\n };\n Store.prototype.registerSchema = function (schema: SchemaService) {\n deprecate(`Use \\`store.createSchemaService\\` instead of \\`store.registerSchema()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n this._schema = schema;\n };\n}\n\nlet assertDestroyingStore: (store: Store, method: string) => void;\nlet assertDestroyedStoreOnly: (store: Store, method: string) => void;\n\nif (DEBUG) {\n // oxlint-disable-next-line no-shadow\n assertDestroyingStore = function assertDestroyingStore(store: Store, method: string) {\n assert(\n `Attempted to call store.${method}(), but the store instance has already been destroyed.`,\n !(store.isDestroying || store.isDestroyed)\n );\n };\n // oxlint-disable-next-line no-shadow\n assertDestroyedStoreOnly = function assertDestroyedStoreOnly(store: Store, method: string) {\n assert(\n `Attempted to call store.${method}(), but the store instance has already been destroyed.`,\n !store.isDestroyed\n );\n };\n}\n\nexport function isMaybeIdentifier(\n maybeIdentifier: string | ResourceIdentifierObject\n): maybeIdentifier is ResourceIdentifierObject {\n return Boolean(\n maybeIdentifier !== null &&\n typeof maybeIdentifier === 'object' &&\n (('id' in maybeIdentifier && 'type' in maybeIdentifier && maybeIdentifier.id && maybeIdentifier.type) ||\n maybeIdentifier.lid)\n );\n}\n\nfunction normalizeProperties(\n store: Store,\n identifier: ResourceKey,\n properties?: { [key: string]: unknown }\n): { [key: string]: unknown } | undefined {\n // assert here\n if (properties !== undefined) {\n if ('id' in properties) {\n assert(`expected id to be a string or null`, properties.id !== undefined);\n }\n assert(\n `You passed '${typeof properties}' as properties for record creation instead of an object.`,\n typeof properties === 'object' && properties !== null\n );\n\n const { type } = identifier;\n\n // convert relationship Records to RecordDatas before passing to RecordData\n const defs = store.schema.fields({ type });\n\n if (defs.size) {\n const keys = Object.keys(properties);\n\n for (let i = 0; i < keys.length; i++) {\n const prop = keys[i];\n const field = defs.get(prop);\n\n if (!field) continue;\n\n if (field.kind === 'hasMany') {\n if (DEBUG) {\n assertRecordsPassedToHasMany(properties[prop] as OpaqueRecordInstance[]);\n }\n properties[prop] = extractIdentifiersFromRecords(properties[prop] as OpaqueRecordInstance[]);\n } else if (field.kind === 'belongsTo') {\n properties[prop] = extractIdentifierFromRecord(properties[prop]);\n }\n }\n }\n }\n return properties;\n}\n\nfunction assertRecordsPassedToHasMany(records: OpaqueRecordInstance[]) {\n assert(`You must pass an array of records to set a hasMany relationship`, Array.isArray(records));\n assert(\n `All elements of a hasMany relationship must be instances of Model, you passed ${records\n .map((r) => `${typeof r}`)\n .join(', ')}`,\n (function () {\n return records.every((record) => {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n });\n })()\n );\n}\n\nfunction extractIdentifiersFromRecords(records: OpaqueRecordInstance[]): ResourceKey[] {\n return records.map((record) => extractIdentifierFromRecord(record)) as ResourceKey[];\n}\n\ntype PromiseProxyRecord = { then(): void; content: OpaqueRecordInstance | null | undefined };\n\nfunction extractIdentifierFromRecord(recordOrPromiseRecord: PromiseProxyRecord | OpaqueRecordInstance | null) {\n if (!recordOrPromiseRecord) {\n return null;\n }\n const extract = recordIdentifierFor;\n\n return extract(recordOrPromiseRecord);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ensureStringId, type InstanceCache, recordIdentifierFor } from '../-private';\nimport type { NotificationType } from '../-private/managers/notification-manager.ts';\nimport { defineSignal } from '../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport type { Cache } from '../../types/cache.ts';\nimport type { NewResourceKey, ResourceKey } from '../../types/identifier.ts';\nimport type { Value } from '../../types/json/raw';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../types/record.ts';\nimport type {\n LegacyAttributeField,\n LegacyRelationshipField,\n LegacyRelationshipField as RelationshipSchema,\n} from '../../types/schema/fields.ts';\nimport type {\n ExistingResourceIdentifierObject,\n ExistingResourceObject,\n InnerRelationshipDocument,\n SingleResourceDocument,\n} from '../../types/spec/json-api-raw';\nimport type { Store } from './store.ts';\n\n/*\n When a find request is triggered on the store, the user can optionally pass in\n attributes and relationships to be preloaded. These are meant to behave as if they\n came back from the server, except the user obtained them out of band and is informing\n the store of their existence. The most common use case is for supporting client side\n nested URLs, such as `/posts/1/comments/2` so the user can do\n `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post.\n\n Preloaded data can be attributes and relationships passed in either as IDs or as actual\n models.\n */\ntype PreloadRelationshipValue = OpaqueRecordInstance | string;\nexport function preloadData(store: Store, identifier: NewResourceKey, preload: Record<string, Value>): void {\n const jsonPayload: Partial<ExistingResourceObject> = {};\n //TODO(Igor) consider the polymorphic case\n const schemas = store.schema;\n const fields = schemas.fields(identifier);\n Object.keys(preload).forEach((key) => {\n const preloadValue = preload[key];\n\n const field = fields.get(key);\n if (field && (field.kind === 'hasMany' || field.kind === 'belongsTo')) {\n if (!jsonPayload.relationships) {\n jsonPayload.relationships = {};\n }\n jsonPayload.relationships[key] = preloadRelationship(field, preloadValue);\n } else {\n if (!jsonPayload.attributes) {\n jsonPayload.attributes = {};\n }\n jsonPayload.attributes[key] = preloadValue;\n }\n });\n const cache = store.cache;\n const hasRecord = Boolean(store._instanceCache.peek(identifier));\n cache.upsert(identifier, jsonPayload, hasRecord);\n}\n\nfunction preloadRelationship(\n schema: RelationshipSchema,\n preloadValue: PreloadRelationshipValue | null | Array<PreloadRelationshipValue>\n): InnerRelationshipDocument<ExistingResourceIdentifierObject> {\n const relatedType = schema.type;\n\n if (schema.kind === 'hasMany') {\n assert('You need to pass in an array to set a hasMany property on a record', Array.isArray(preloadValue));\n return { data: preloadValue.map((value) => _convertPreloadRelationshipToJSON(value, relatedType)) };\n }\n\n assert('You should not pass in an array to set a belongsTo property on a record', !Array.isArray(preloadValue));\n return { data: preloadValue ? _convertPreloadRelationshipToJSON(preloadValue, relatedType) : null };\n}\n\n/*\n findRecord('user', '1', { preload: { friends: ['1'] }});\n findRecord('user', '1', { preload: { friends: [record] }});\n*/\nfunction _convertPreloadRelationshipToJSON(\n value: OpaqueRecordInstance | string,\n type: string\n): ExistingResourceIdentifierObject {\n if (typeof value === 'string' || typeof value === 'number') {\n return { type, id: ensureStringId(value) };\n }\n // TODO if not a record instance assert it's an identifier\n // and allow identifiers to be used\n return recordIdentifierFor(value) as ExistingResourceIdentifierObject;\n}\n\nexport interface BaseFinderOptions {\n reload?: boolean;\n backgroundReload?: boolean;\n include?: string | string[];\n adapterOptions?: Record<string, unknown>;\n}\nexport interface FindRecordOptions extends BaseFinderOptions {\n /**\n * Data to preload into the store before the request is made.\n * This feature is *highly* discouraged and has no corresponding\n * feature when using builders and handlers.\n *\n * Excepting relationships: the data should be in the form of a\n * JSON object where the keys are fields on the record and the value\n * is the raw value to be added to the cache.\n *\n * Relationships can either be provided as string IDs from which\n * an identifier will be built base upon the relationship's expected\n * resource type, or be record instances from which the identifier\n * will be extracted.\n *\n */\n preload?: Record<string, Value>;\n}\n\nexport type QueryOptions = {\n [K in string | 'adapterOptions']?: K extends 'adapterOptions' ? Record<string, unknown> : unknown;\n};\n\nexport type FindAllOptions = BaseFinderOptions;\nexport type LegacyResourceQuery = {\n include?: string | string[];\n [key: string]: Value | undefined;\n};\n\nexport type KeyOrString<T> = keyof T & string extends never ? string : keyof T & string;\n\n/**\n * Minimum subset of static schema methods and properties on the\n * \"model\" class.\n *\n * Only used when using the legacy schema-service implementation\n * for @warp-drive/legacy/model or when wrapping schema for legacy\n * Adapters/Serializers.\n *\n */\nexport interface ModelSchema<T = unknown> {\n /**\n * The resource type (model name) that this schema describes.\n */\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n\n /**\n * A map of every field defined on this resource type to its kind\n * (`'attribute'`, `'belongsTo'`, or `'hasMany'`).\n */\n fields: Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'>;\n\n /**\n * A map of every attribute field defined on this resource type, keyed by\n * attribute name.\n */\n attributes: Map<KeyOrString<T>, LegacyAttributeField>;\n\n /**\n * A map of every relationship (`belongsTo`/`hasMany`) field defined on this\n * resource type, keyed by relationship name.\n */\n relationshipsByName: Map<KeyOrString<T>, LegacyRelationshipField>;\n\n /**\n * Invokes `callback` once for each attribute field defined on this resource\n * type, passing the attribute's key and schema.\n */\n eachAttribute<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, attribute: LegacyAttributeField) => void,\n binding?: T\n ): void;\n\n /**\n * Invokes `callback` once for each relationship field defined on this\n * resource type, passing the relationship's key and schema.\n */\n eachRelationship<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, relationship: LegacyRelationshipField) => void,\n binding?: T\n ): void;\n\n /**\n * Invokes `callback` once for each attribute field defined on this resource\n * type that has a transform (a `type`), passing the attribute's key and the\n * name of the transform to apply.\n */\n eachTransformedAttribute<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, type: string | null) => void,\n binding?: T\n ): void;\n}\n\nfunction _resourceIsFullDeleted(identifier: ResourceKey, cache: Cache): boolean {\n return cache.isDeletionCommitted(identifier) || (cache.isNew(identifier) && cache.isDeleted(identifier));\n}\n\nexport function resourceIsFullyDeleted(instanceCache: InstanceCache, identifier: ResourceKey): boolean {\n const cache = instanceCache.cache;\n return !cache || _resourceIsFullDeleted(identifier, cache);\n}\n\n/**\n A `RecordReference` is a low-level API that allows users and\n addon authors to perform meta-operations on a record.\n\n @hideconstructor\n @public\n*/\nexport class RecordReference {\n /** @internal */\n declare private store: Store;\n // unsubscribe token given to us by the notification manager\n /** @internal */\n private ___token!: object;\n /** @internal */\n private ___identifier: ResourceKey;\n /** @internal */\n declare private _ref: number;\n\n constructor(store: Store, identifier: ResourceKey) {\n this.store = store;\n this.___identifier = identifier;\n this.___token = store.notifications.subscribe(\n identifier,\n (_: ResourceKey, bucket: NotificationType, notifiedKey?: string) => {\n if (bucket === 'identity' || (bucket === 'attributes' && notifiedKey === 'id')) {\n this._ref++;\n }\n }\n );\n }\n\n /** @internal */\n destroy(): void {\n this.store.notifications.unsubscribe(this.___token);\n }\n\n get type(): string {\n return this.identifier().type;\n }\n\n /**\n The `id` of the record that this reference refers to.\n\n Together, the `type` and `id` properties form a composite key for\n the identity map.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.id(); // '1'\n ```\n\n @public\n @return The id of the record.\n */\n id(): string | null {\n // oxlint-disable-next-line no-unused-expressions\n this._ref; // consume the tracked prop\n return this.___identifier.id;\n }\n\n /**\n The `identifier` of the record that this reference refers to.\n\n Together, the `type` and `id` properties form a composite key for\n the identity map.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.identifier(); // '1'\n ```\n\n @public\n @return The identifier of the record.\n */\n identifier(): ResourceKey {\n return this.___identifier;\n }\n\n /**\n How the reference will be looked up when it is loaded. Currently\n this always returns `identity` to signify that a record will be\n loaded by its `type` and `id`.\n\n Example\n\n ```javascript\n const userRef = store.getReference('user', 1);\n\n userRef.remoteType(); // 'identity'\n ```\n\n @public\n */\n remoteType(): 'identity' {\n return 'identity';\n }\n\n /**\n This API allows you to provide a reference with new data. The\n simplest usage of this API is similar to `store.push`: you provide a\n normalized hash of data and the object represented by the reference\n will update.\n\n If you pass a promise to `push`, WarpDrive will not ask the adapter\n for the data if another attempt to fetch it is made in the\n interim. When the promise resolves, the underlying object is updated\n with the new data, and the promise returned by *this function* is resolved\n with that object.\n\n For example, `recordReference.push(promise)` will be resolved with a\n record.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // provide data for reference\n userRef.push({\n data: {\n id: \"1\",\n type: \"user\",\n attributes: {\n username: \"@user\"\n }\n }\n }).then(function(user) {\n userRef.value() === user;\n });\n ```\n\n @public\n @param objectOrPromise a JSON:API ResourceDocument or a promise resolving to one\n @return a promise for the value (record or relationship)\n */\n push(objectOrPromise: SingleResourceDocument | Promise<SingleResourceDocument>): Promise<OpaqueRecordInstance> {\n // TODO @deprecate pushing unresolved payloads\n return Promise.resolve(objectOrPromise).then((data) => {\n return this.store.push(data);\n });\n }\n\n /**\n If the entity referred to by the reference is already loaded, it is\n present as `reference.value`. Otherwise the value returned by this function\n is `null`.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.value(); // user\n ```\n\n @public\n @return the record for this RecordReference\n */\n value(): OpaqueRecordInstance | null {\n return this.store.peekRecord(this.___identifier);\n }\n\n /**\n Triggers a fetch for the backing entity based on its `remoteType`\n (see `remoteType` definitions per reference type).\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // load user (via store.find)\n userRef.load().then(...)\n ```\n\n @public\n @return the record for this RecordReference\n */\n load(): Promise<unknown> {\n const id = this.id();\n if (id !== null) {\n return this.store.findRecord(this.type, id);\n }\n assert(`Unable to fetch record of type ${this.type} without an id`);\n }\n\n /**\n Reloads the record if it is already loaded. If the record is not\n loaded it will load the record via `store.findRecord`\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // or trigger a reload\n userRef.reload().then(...)\n ```\n\n @public\n @return the record for this RecordReference\n */\n reload(): Promise<unknown> {\n const id = this.id();\n if (id !== null) {\n return this.store.findRecord(this.type, id, { reload: true });\n }\n assert(`Unable to fetch record of type ${this.type} without an id`);\n }\n}\n\ndefineSignal(RecordReference.prototype, '_ref');\n\n// if modelFor turns out to be a bottleneck we should replace with a Map\n// and clear it during store teardown.\nconst AvailableShims = getOrSetGlobal('AvailableShims', new WeakMap<Store, Record<string, ShimModelClass>>());\n\nexport function getShimClass<T>(\n store: Store,\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string\n): ShimModelClass<T> {\n let shims = AvailableShims.get(store);\n\n if (!shims) {\n shims = Object.create(null) as Record<string, ShimModelClass>;\n AvailableShims.set(store, shims);\n }\n\n let shim = shims[modelName];\n if (shim === undefined) {\n shim = shims[modelName] = new ShimModelClass<unknown>(store, modelName);\n }\n\n return shim;\n}\n\n// Mimics the static apis of @warp-drive/legacy/model\nexport class ShimModelClass<T = unknown> implements ModelSchema<T> {\n declare __store: Store;\n declare modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n constructor(store: Store, modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string) {\n this.__store = store;\n this.modelName = modelName;\n }\n\n get fields(): Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'> {\n const fields = new Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'>();\n const fieldSchemas = this.__store.schema.fields({ type: this.modelName });\n\n fieldSchemas.forEach((schema, key) => {\n if (schema.kind === 'attribute' || schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n fields.set(key as KeyOrString<T>, schema.kind);\n }\n });\n\n return fields;\n }\n\n get attributes(): Map<KeyOrString<T>, LegacyAttributeField> {\n const attrs = new Map<KeyOrString<T>, LegacyAttributeField>();\n const fields = this.__store.schema.fields({ type: this.modelName });\n\n fields.forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n attrs.set(key as KeyOrString<T>, schema);\n }\n });\n\n return attrs;\n }\n\n get relationshipsByName(): Map<KeyOrString<T>, LegacyRelationshipField> {\n const rels = new Map<KeyOrString<T>, LegacyRelationshipField>();\n const fields = this.__store.schema.fields({ type: this.modelName });\n\n fields.forEach((schema, key) => {\n if (schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n rels.set(key as KeyOrString<T>, schema);\n }\n });\n\n return rels;\n }\n\n eachAttribute<K extends KeyOrString<T>>(\n callback: (key: K, attribute: LegacyAttributeField) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n callback.call(binding, key as K, schema);\n }\n });\n }\n\n eachRelationship<K extends KeyOrString<T>>(\n callback: (key: K, relationship: LegacyRelationshipField) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n callback.call(binding, key as K, schema);\n }\n });\n }\n\n eachTransformedAttribute<K extends KeyOrString<T>>(\n callback: (key: K, type: string | null) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n const type = schema.type;\n if (type) callback.call(binding, key as K, type);\n }\n });\n }\n}\n","import { deprecate } from '@ember/debug';\n\nimport { ENABLE_LEGACY_REQUEST_METHODS } from '@warp-drive/build-config/deprecations';\nimport { assert } from '@warp-drive/build-config/macros';\n\nimport type { LegacyLiveArray, LegacyQueryArray } from '../-private';\nimport { constructResource, ensureStringId, recordIdentifierFor, storeFor } from '../-private';\nimport type { Caches } from '../-private/caches/instance-cache';\nimport { isMaybeIdentifier, Store } from '../-private/store-service';\nimport { normalizeModelName } from '../-private/utils/normalize-model-name';\nimport type { ResourceKey } from '../../types/identifier';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../types/record';\nimport { SkipCache } from '../../types/request';\nimport type { ResourceIdentifierObject } from '../../types/spec/json-api-raw';\nimport type { FindAllOptions, FindRecordOptions, LegacyResourceQuery, ModelSchema, QueryOptions } from './-private';\nimport { getShimClass, preloadData, RecordReference, resourceIsFullyDeleted } from './-private';\n\nif (ENABLE_LEGACY_REQUEST_METHODS) {\n Store.prototype.findRecord = function (\n resource: string | ResourceIdentifierObject,\n id?: string | number | FindRecordOptions,\n options?: FindRecordOptions\n ): Promise<unknown> {\n deprecate(`store.findRecord is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.findRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n\n assert(\n `You need to pass a modelName or resource identifier as the first argument to the store's findRecord method`,\n resource\n );\n if (isMaybeIdentifier(resource)) {\n options = id as FindRecordOptions | undefined;\n } else {\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${resource}`,\n typeof resource === 'string'\n );\n const type = normalizeModelName(resource);\n const normalizedId = ensureStringId(id as string | number);\n resource = constructResource(type, normalizedId);\n }\n\n const identifier = this.cacheKeyManager.getOrCreateRecordIdentifier(resource);\n options = options || {};\n\n if (options.preload) {\n // force reload if we preload to ensure we don't resolve the promise\n // until we are complete, else we will end up background-reloading\n // even for initial load.\n if (!this._instanceCache.recordIsLoaded(identifier)) {\n options.reload = true;\n }\n this._join(() => {\n preloadData(this, identifier, options.preload!);\n });\n }\n\n const promise = this.request<OpaqueRecordInstance>({\n op: 'findRecord',\n data: {\n record: identifier,\n options,\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => {\n return document.content;\n });\n };\n\n Store.prototype.findAll = function <T>(\n type: TypeFromInstance<T> | string,\n options: FindAllOptions = {}\n ): Promise<LegacyLiveArray<T>> {\n deprecate(`store.findAll is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.findAll(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's findAll method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<LegacyLiveArray<T>>({\n op: 'findAll',\n data: {\n type: normalizeModelName(type),\n options: options || {},\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.query = function (\n type: string,\n query: LegacyResourceQuery,\n options: QueryOptions = {}\n ): Promise<LegacyQueryArray> {\n deprecate(`store.query is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.query(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's query method`, type);\n assert(`You need to pass a query hash to the store's query method`, query);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<LegacyQueryArray>({\n op: 'query',\n data: {\n type: normalizeModelName(type),\n query,\n options: options,\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.queryRecord = function (\n type: string,\n query: Record<string, unknown>,\n options?: QueryOptions\n ): Promise<OpaqueRecordInstance | null> {\n deprecate(`store.queryRecord is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.queryRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's queryRecord method`, type);\n assert(`You need to pass a query hash to the store's queryRecord method`, query);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<OpaqueRecordInstance | null>({\n op: 'queryRecord',\n data: {\n type: normalizeModelName(type),\n query,\n options: options || {},\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.getReference = function (\n resource: string | ResourceIdentifierObject,\n id: string | number\n ): RecordReference {\n deprecate(\n `store.getReference is deprecated. There is no direct replacement. For working with the cache and relationships, use the cache with the appropriate identifiers. To load, use store.request.`,\n false,\n {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n }\n );\n assert(\n `Attempted to call store.getReference(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n\n let resourceIdentifier: ResourceIdentifierObject;\n if (arguments.length === 1 && isMaybeIdentifier(resource)) {\n resourceIdentifier = resource;\n } else {\n const type = normalizeModelName(resource as string);\n const normalizedId = ensureStringId(id);\n resourceIdentifier = constructResource(type, normalizedId);\n }\n\n assert(\n 'getReference expected to receive either a resource identifier or type and id as arguments',\n isMaybeIdentifier(resourceIdentifier)\n );\n\n const identifier: ResourceKey = this.cacheKeyManager.getOrCreateRecordIdentifier(resourceIdentifier);\n\n const cache = upgradeInstanceCaches(this._instanceCache.__instances).reference;\n let reference = cache.get(identifier);\n\n if (!reference) {\n reference = new RecordReference(this, identifier);\n cache.set(identifier, reference);\n }\n return reference;\n };\n\n Store.prototype.modelFor = function <T>(\n type: T extends TypedRecordInstance ? TypeFromInstance<T> : string\n ): ModelSchema<T> {\n deprecate(\n `store.modelFor is deprecated, please use store.schema.fields({ type: '${type}' }) to access schema information instead.`,\n false,\n {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n }\n );\n assert(`Attempted to call store.modelFor(), but the store instance has already been destroyed.`, !this.isDestroyed);\n assert(`You need to pass <type> to the store's modelFor method`, typeof type === 'string' && type.length);\n assert(`No model was found for '${type}' and no schema handles the type`, this.schema.hasResource({ type }));\n\n return getShimClass<T>(this, type);\n };\n\n Store.prototype.saveRecord = function <T>(record: T, options: Record<string, unknown> = {}): Promise<T> {\n deprecate(`store.saveRecord is deprecated, please use store.request to initiate a save request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.saveRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`Unable to initiate save for a record in a disconnected state`, storeFor(record, true));\n const identifier = recordIdentifierFor(record);\n const cache = this.cache;\n\n if (!identifier) {\n // this commonly means we're disconnected\n // but just in case we reject here to prevent bad things.\n return Promise.reject(new Error(`Record Is Disconnected`));\n }\n assert(\n `Cannot initiate a save request for an unloaded record: ${identifier.lid}`,\n this._instanceCache.recordIsLoaded(identifier)\n );\n if (resourceIsFullyDeleted(this._instanceCache, identifier)) {\n return Promise.resolve(record);\n }\n\n if (!options) {\n options = {};\n }\n let operation: 'createRecord' | 'deleteRecord' | 'updateRecord' = 'updateRecord';\n\n if (cache.isNew(identifier)) {\n operation = 'createRecord';\n } else if (cache.isDeleted(identifier)) {\n operation = 'deleteRecord';\n }\n\n const request = {\n op: operation,\n data: {\n options,\n record: identifier,\n },\n records: [identifier],\n cacheOptions: { [SkipCache]: true },\n };\n\n return this.request<T>(request).then((document) => document.content);\n };\n}\n\nexport { Store };\n\nfunction upgradeInstanceCaches(cache: Caches): Caches & { reference: WeakMap<ResourceKey, RecordReference> } {\n const withReferences = cache as Caches & { reference: WeakMap<ResourceKey, RecordReference> };\n if (!withReferences.reference) {\n withReferences.reference = new WeakMap();\n }\n\n return withReferences;\n}\n","import type { RequestKey } from '../../../types/identifier.ts';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '../../../types/request.ts';\nimport type { ResourceDataDocument, ResourceErrorDocument } from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { Store } from '../store-service.ts';\n\nexport const MUTATION_OPS: Set<string> = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n !hasCachedValue ||\n (store.lifetimes && identifier ? store.lifetimes.isHardExpired(identifier, store) : false)\n );\n}\n\nexport function calcShouldBackgroundFetch(\n store: Store,\n request: ImmutableRequestInfo,\n willFetch: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n !willFetch &&\n (cacheOptions?.backgroundReload ||\n (store.lifetimes && identifier ? store.lifetimes.isSoftExpired(identifier, store) : false))\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nexport function isAggregateError(\n error: Error & { errors?: ApiError[] }\n): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\nexport type RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError): RobustError {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n\nexport function isErrorDocument(\n document: ResourceDataDocument | ResourceErrorDocument\n): document is ResourceErrorDocument {\n return 'errors' in document;\n}\n\nexport function getPriority(\n identifier: RequestKey | null,\n deduped: Map<RequestKey, { priority: { blocking: boolean } }>,\n priority: { blocking: boolean }\n): { blocking: boolean } {\n if (identifier) {\n const existing = deduped.get(identifier);\n if (existing) {\n return existing.priority;\n }\n }\n return priority;\n}\n","import { LOG_REQUESTS } from '@warp-drive/build-config/debugging';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { createReactiveDocument, type ReactiveDocument } from '../../../reactive/-private/document.ts';\nimport type { CacheHandler as CacheHandlerType, Future, ManagedRequestPriority, NextFn } from '../../../request.ts';\nimport type { RequestKey } from '../../../types/identifier.ts';\nimport type {\n ImmutableRequestInfo,\n RequestContext,\n StructuredDataDocument,\n StructuredErrorDocument,\n} from '../../../types/request.ts';\nimport { EnableHydration, SkipCache } from '../../../types/request.ts';\nimport type {\n CollectionResourceDataDocument,\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n SingleResourceDataDocument,\n} from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { ResourceIdentifierObject } from '../../../types/spec/json-api-raw.ts';\nimport type { RequestSignature } from '../../../types/symbols.ts';\nimport { log } from '../debug/utils.ts';\nimport type { Store } from '../store-service.ts';\nimport {\n calcShouldBackgroundFetch,\n calcShouldFetch,\n cloneError,\n getPriority,\n isCacheAffecting,\n isMutation,\n} from './utils.ts';\n\nexport type LooseStoreRequestInfo<RT = unknown> = Omit<\n ImmutableRequestInfo<RT>,\n 'records' | 'headers' | typeof RequestSignature\n> & {\n records?: ResourceIdentifierObject[];\n headers?: Headers;\n};\n\n/**\n * The request shape accepted by {@link Store.request}, either a fully-formed\n * {@link ImmutableRequestInfo} or the looser {@link LooseStoreRequestInfo}.\n */\nexport type StoreRequestInput<RT = unknown> = ImmutableRequestInfo<RT> | LooseStoreRequestInfo<RT>;\n\nexport interface StoreRequestContext extends RequestContext {\n request: ImmutableRequestInfo & {\n /** the store instance the request was issued through, used to enable store-aware cache handling. */\n store: Store;\n };\n}\n\n/**\n * A CacheHandler that adds support for using an WarpDrive Cache with a RequestManager.\n *\n * This handler will only run when a request has supplied a `store` instance. Requests\n * issued by the store via `store.request()` will automatically have the `store` instance\n * attached to the request.\n *\n * ```ts\n * requestManager.request({\n * store: store,\n * url: '/api/posts',\n * method: 'GET'\n * });\n * ```\n *\n * When this handler elects to handle a request, it will return the raw `StructuredDocument`\n * unless the request has `[EnableHydration]` set to `true`. In this case, the handler will\n * return a `Document` instance that will automatically update the UI when the cache is updated\n * in the future and will hydrate any identifiers in the StructuredDocument into Record instances.\n *\n * When issuing a request via the store, [EnableHydration] is automatically set to `true`. This\n * means that if desired you can issue requests that utilize the cache without needing to also\n * utilize Record instances if desired.\n *\n * Said differently, you could elect to issue all requests via a RequestManager, without ever using\n * the store directly, by setting [EnableHydration] to `true` and providing a store instance. Not\n * necessarily the most useful thing, but the decoupled nature of the RequestManager and incremental-feature\n * approach of WarpDrive allows for this flexibility.\n *\n * ```ts\n * import { EnableHydration } from '@warp-drive/core/types/request';\n *\n * requestManager.request({\n * store: store,\n * url: '/api/posts',\n * method: 'GET',\n * [EnableHydration]: true\n * });\n *\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(\n context: StoreRequestContext & { setIdentifier(identifier: RequestKey): void },\n next: NextFn<T>\n ): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(context.request);\n\n if (identifier) {\n context.setIdentifier(identifier);\n }\n\n // used to dedupe existing requests that match\n const DEDUPE = store.requestManager._deduped;\n const activeRequest = identifier && DEDUPE.get(identifier);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n // determine if we should skip cache\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n if (activeRequest) {\n activeRequest.priority = { blocking: true };\n if (LOG_REQUESTS) {\n log('request', '', 'DEDUPED', identifier.lid, 'blocking', '');\n }\n return activeRequest.promise as Promise<T>;\n }\n if (LOG_REQUESTS) {\n log(\n 'request',\n '',\n 'ISSUED',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'blocking',\n ''\n );\n }\n let promise = fetchContentAndHydrate(next, context, identifier, { blocking: true });\n if (identifier) {\n promise = promise.finally(() => {\n DEDUPE.delete(identifier);\n store.notifications.notify(identifier, 'state', null);\n });\n DEDUPE.set(identifier, { priority: { blocking: true }, promise });\n queueMicrotask(() => {\n store.notifications.notify(identifier, 'state', null);\n });\n }\n store.requestManager._pending.set(context.id, promise);\n return promise;\n }\n\n // if we have not skipped cache, determine if we should update behind the scenes\n if (calcShouldBackgroundFetch(store, context.request, false, identifier)) {\n let promise = activeRequest?.promise || fetchContentAndHydrate(next, context, identifier, { blocking: false });\n if (identifier && !activeRequest) {\n promise = promise.finally(() => {\n DEDUPE.delete(identifier);\n store.notifications.notify(identifier, 'state', null);\n });\n DEDUPE.set(identifier, { priority: { blocking: false }, promise });\n queueMicrotask(() => {\n store.notifications.notify(identifier, 'state', null);\n });\n }\n if (LOG_REQUESTS) {\n if (activeRequest && identifier) {\n log(\n 'request',\n '',\n 'DEDUPED',\n identifier.lid,\n activeRequest.priority.blocking ? 'blocking' : 'non-blocking',\n ''\n );\n } else {\n log(\n 'request',\n '',\n 'ISSUED',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'non-blocking',\n ''\n );\n }\n }\n store.requestManager._pending.set(context.id, promise);\n }\n\n if (LOG_REQUESTS) {\n log(\n 'request',\n '',\n 'CACHE-HIT',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'cached',\n ''\n );\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n\n const shouldHydrate: boolean = context.request[EnableHydration] || false;\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n const content = shouldHydrate\n ? maybeUpdateUiObjects<T>(store, context.request, { shouldHydrate, identifier }, peeked.content)\n : peeked.content;\n const newError = cloneError(peeked);\n newError.content = content;\n throw newError;\n }\n\n const result = shouldHydrate\n ? (maybeUpdateUiObjects<T>(store, context.request, { shouldHydrate, identifier }, peeked.content) as T)\n : (peeked.content as T);\n\n return result;\n },\n};\n\ntype HydrationOptions = {\n shouldHydrate?: boolean;\n identifier: RequestKey | null;\n};\n\ntype UpdateOptions = HydrationOptions & {\n priority: ManagedRequestPriority;\n};\n\nfunction maybeUpdateUiObjects<T>(\n store: Store,\n request: ImmutableRequestInfo,\n options: HydrationOptions,\n document: ResourceDocument | null | undefined\n): ReactiveDocument<T> | ResourceDocument | null {\n const { identifier } = options;\n\n if (!document || !options.shouldHydrate) {\n assert(`The CacheHandler expected response content but none was found`, !options.shouldHydrate);\n return document ?? null;\n }\n\n if (identifier) {\n return store._instanceCache.getDocument<T>(identifier);\n }\n\n // if we don't have an identifier, we give the document\n // its own local cache\n return createReactiveDocument<T>(store, null, {\n request,\n document,\n });\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n options: HydrationOptions,\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n if (Array.isArray(request.records)) {\n response = store.cache.didCommit(\n request.records,\n document as StructuredDataDocument<CollectionResourceDataDocument>\n );\n } else if (request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n response = store.cache.didCommit(\n request.data.record,\n document as StructuredDataDocument<SingleResourceDataDocument>\n );\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n }\n return maybeUpdateUiObjects(store, request, options, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n context: StoreRequestContext,\n options: UpdateOptions,\n document: StructuredDataDocument<T>\n): ResourceDataDocument | void {\n const { request } = context;\n store.requestManager._pending.delete(context.id);\n store._enableAsyncFlush = true;\n let response: ResourceDataDocument;\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, options, document) as ResourceDataDocument;\n });\n store._enableAsyncFlush = null;\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(context.request, document.response, options.identifier, store);\n }\n\n const finalPriority = getPriority(options.identifier, store.requestManager._deduped, options.priority);\n if (finalPriority.blocking) {\n return response!;\n } else {\n store.notifications._flush();\n }\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n context: StoreRequestContext,\n options: HydrationOptions,\n error: StructuredErrorDocument<T>\n) {\n let response: ResourceErrorDocument | undefined;\n if (isMutation(context.request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n if (Array.isArray(context.request.records)) {\n store.cache.commitWasRejected(context.request.records, errors);\n } else if (context.request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n store.cache.commitWasRejected(context.request.data.record, errors);\n } else {\n store.cache.put(error) as ResourceErrorDocument;\n }\n } else {\n response = store.cache.put(error) as ResourceErrorDocument;\n return maybeUpdateUiObjects(store, context.request, options, response);\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n context: StoreRequestContext,\n options: UpdateOptions,\n error: StructuredErrorDocument<T>\n): ResourceErrorDocument | void {\n store.requestManager._pending.delete(context.id);\n if (context.request.signal?.aborted) {\n throw error;\n }\n store._enableAsyncFlush = true;\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, context, options, error) as ResourceErrorDocument;\n });\n store._enableAsyncFlush = null;\n\n if (options.identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(context.request, error.response, options.identifier, store);\n }\n\n if (isMutation(context.request)) {\n throw error;\n }\n\n const finalPriority = getPriority(options.identifier, store.requestManager._deduped, options.priority);\n if (finalPriority.blocking) {\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n } else {\n store.notifications._flush();\n }\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: RequestKey | null,\n priority: { blocking: boolean }\n): Promise<T> {\n const { store } = context.request;\n const shouldHydrate: boolean = context.request[EnableHydration] || false;\n const options = { shouldHydrate, identifier, priority };\n\n let isMut = false;\n if (isMutation(context.request)) {\n isMut = true;\n\n if (Array.isArray(context.request.records)) {\n context.request.records.forEach((record) => {\n store.cache.willCommit(record, context);\n });\n } else if (context.request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n store.cache.willCommit(context.request.data.record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(context.request, identifier, store);\n }\n\n const promise = next(context.request).then(\n (document) => {\n return handleFetchSuccess(store, context, options, document);\n },\n (error: StructuredErrorDocument<T>) => {\n return handleFetchError(store, context, options, error);\n }\n ) as Promise<T>;\n\n if (!isMut) {\n return promise;\n }\n assert(`Expected a mutation`, isMutation(context.request));\n\n // for mutations we need to enqueue the promise with the requestStateService\n // TODO should we enque a request per record in records?\n const record = context.request.data?.record || context.request.records?.[0];\n\n return store._requestCache._enqueue(promise, {\n data: [{ op: 'saveRecord', recordIdentifier: record, options: undefined }],\n });\n}\n","export function isNonEmptyString(str: unknown): str is string {\n return Boolean(str && typeof str === 'string');\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { ExistingResourceIdentifierObject, ResourceIdentifierObject } from '../../../types/spec/json-api-raw.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport { coerceId } from './coerce-id.ts';\nimport { isNonEmptyString } from './is-non-empty-string.ts';\n\n/**\n * Given an existing resource identifier object (or a {@link ResourceKey}),\n * returns it unchanged aside from coercing its `id`, if present, to a string.\n *\n * @private\n */\nexport function constructResource(type: ResourceIdentifierObject): ResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type`, `id`, and `lid`, all of which\n * are known to be present, producing an {@link ExistingResourceIdentifierObject}.\n *\n * @private\n */\nexport function constructResource(type: string, id: string, lid: string): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `lid` alone, for the case where `type`\n * and `id` are not (yet) known.\n *\n * @private\n */\nexport function constructResource(\n type: string | undefined,\n id: null | undefined,\n lid: string\n): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type` and `id`, with an optional `lid`,\n * producing an {@link ExistingResourceIdentifierObject}.\n *\n * @private\n */\nexport function constructResource(type: string, id: string, lid?: string | null): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type` and an optional `id`/`lid`. If no\n * usable `id` is provided, falls back to constructing a `lid`-only identifier.\n *\n * @private\n */\nexport function constructResource(\n type: string,\n id?: string | number | null,\n lid?: string | null\n): ResourceIdentifierObject;\n/**\n * Implementation for {@link constructResource}. Normalizes the supplied\n * `type`/`id`/`lid` (or existing resource identifier object) into a valid\n * {@link ResourceIdentifierObject}, coercing the id and asserting that enough\n * information was provided to identify the resource.\n *\n * @private\n */\nexport function constructResource(\n type: string | ResourceIdentifierObject | undefined,\n id?: string | number | null,\n lid?: string | null\n): ResourceIdentifierObject | ExistingResourceIdentifierObject {\n if (typeof type === 'object' && type !== null) {\n const resource = type;\n if (isResourceKey(resource)) {\n return resource;\n }\n if ('id' in resource) {\n resource.id = coerceId(resource.id);\n }\n\n assert(\n 'Expected either id or lid to be a valid string',\n ('id' in resource && isNonEmptyString(resource.id)) || isNonEmptyString(resource.lid)\n );\n assert('if id is present, the type must be a string', !('id' in resource) || typeof resource.type === 'string');\n\n return resource;\n } else {\n const trueId = coerceId(id);\n if (!isNonEmptyString(trueId)) {\n if (isNonEmptyString(lid)) {\n return { lid };\n }\n throw new Error('Expected either id or lid to be a valid string');\n }\n\n assert('type must be a string', typeof type === 'string');\n\n if (isNonEmptyString(lid)) {\n return { type, id: trueId, lid };\n }\n\n return { type, id: trueId };\n }\n}\n","// every `target[prop]` extraction below is immediately invoked via `Reflect.apply(fn, receiver, args)`,\n// which is the correct way to call an unbound method with an explicit `this` — the rule can't see that\n/* oxlint-disable typescript/unbound-method */\nimport { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_MANY_ARRAY_DUPLICATES } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport { notifyInternalSignal, type WarpDriveSignal } from '../../../signals/-private.ts';\nimport type { BaseFinderOptions, ResourceKey } from '../../../types.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { ObjectValue } from '../../../types/json/raw.ts';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../../types/record.ts';\nimport type { LegacyHasManyField, LinksModeHasManyField } from '../../../types/schema/fields.ts';\nimport type { Links, Meta, PaginationLinks } from '../../../types/spec/json-api-raw.ts';\nimport { recordIdentifierFor } from '../caches/instance-cache.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport type { CreateRecordProperties } from '../store-service.ts';\nimport { save } from './-utils.ts';\nimport type { LegacyLiveArrayCreateOptions } from './legacy-live-array.ts';\nimport type { NativeProxy } from './native-proxy-type-fix.ts';\nimport { createReactiveResourceArray, destroy, type ReactiveResourceArray } from './resource-array.ts';\n\n/**\n A `ManyArray` is a `MutableArray` that represents the contents of a has-many\n relationship.\n\n The `ManyArray` is instantiated lazily the first time the relationship is\n requested.\n\n This class is not intended to be directly instantiated by consuming applications.\n\n ### Inverses\n\n Often, the relationships in WarpDrive applications will have\n an inverse. For example, imagine the following models are\n defined:\n\n ```js [app/models/post.js]\n import Model, { hasMany } from '@ember-data/model';\n\n export default class PostModel extends Model {\n @hasMany('comment') comments;\n }\n ```\n\n ```js [app/models/comment.js]\n import { Model, belongsTo } from '@warp-drive/legacy/model';\n\n export default class CommentModel extends Model {\n @belongsTo('post') post;\n }\n ```\n\n If you created a new instance of `Post` and added\n a `Comment` record to its `comments` has-many\n relationship, you would expect the comment's `post`\n property to be set to the post that contained\n the has-many.\n\n We call the record to which a relationship belongs-to the\n relationship's _owner_.\n\n @public\n*/\nexport interface LegacyManyArray<T = unknown> extends ReactiveResourceArray<T> {\n /**\n The meta data for the has-many relationship, as returned in the\n relationship's payload from the server.\n\n @public\n */\n meta: Meta | null;\n\n /**\n The links for the has-many relationship, as returned in the\n relationship's payload from the server. Used to refetch the\n relationship when reloading.\n\n @public\n */\n links: Links | PaginationLinks | null;\n\n /** @internal */\n isPolymorphic: boolean;\n /** @internal */\n isAsync: boolean;\n\n /** @private */\n key: string;\n /** @private */\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n\n /**\n The loading state of this array\n @public\n */\n isLoaded: boolean;\n\n /** @internal */\n notify(): void;\n\n /**\n Reloads all of the records in the manyArray. If the manyArray\n holds a relationship that was originally fetched using a links url\n WarpDrive will revisit the original links url to repopulate the\n relationship.\n\n If the ManyArray holds the result of a `store.query()` reload will\n re-run the original query.\n\n Example\n\n ```javascript\n let user = store.peekRecord('user', '1')\n await login(user);\n\n let permissions = await user.permissions;\n await permissions.reload();\n ```\n\n @public\n */\n reload(options?: BaseFinderOptions): Promise<LegacyManyArray<T>>;\n\n /**\n Create a child record and associated it to the collection\n\n @public\n */\n createRecord(hash: CreateRecordProperties<T>): T;\n\n /**\n Saves all of the records in the `ManyArray`.\n\n Note: this API can only be used in legacy mode with a configured Adapter.\n\n Example\n\n ```js\n const { content: { data: inbox } } = await store.request(findRecord({ type: 'inbox', id: '1' }));\n\n let messages = await inbox.messages;\n messages.forEach((message) => {\n message.isRead = true;\n });\n messages.save();\n ```\n\n @public\n */\n save: () => Promise<LegacyManyArray<T>>;\n\n /** @private */\n destroy: () => void;\n}\n\n/**\n * The options for {@link createLegacyManyArray}\n *\n * @private\n */\nexport interface LegacyManyArrayCreateOptions extends LegacyLiveArrayCreateOptions {\n isLoaded: boolean;\n editable: boolean;\n isAsync: boolean;\n isPolymorphic: boolean;\n field: LegacyHasManyField | LinksModeHasManyField;\n identifier: ResourceKey;\n links: Links | PaginationLinks | null;\n meta: Meta | null;\n}\n/**\n * Creates a {@link LegacyManyArray}\n *\n * @private\n */\nexport function createLegacyManyArray<T>(options: LegacyManyArrayCreateOptions): LegacyManyArray<T> {\n const extensions = options.store.schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions\n ? options.store.schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions(options.field)\n : null;\n\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: options.editable,\n source: options.source,\n data: {\n links: options.links,\n meta: options.meta,\n } as ObjectValue,\n features: {\n modelName: options.type,\n save,\n DEPRECATED_CLASS_NAME: 'ManyArray',\n isLoaded: options.isLoaded,\n isAsync: options.isAsync,\n isPolymorphic: options.isPolymorphic,\n identifier: options.identifier,\n key: options.field.name,\n reload,\n createRecord,\n notify,\n },\n extensions,\n options: null,\n destroy: destroyLegacyManyArray,\n mutate: _MUTATE,\n }) as LegacyManyArray<T>;\n}\n\nfunction _MUTATE<T>(\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], T[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n): unknown {\n const collection = receiver as unknown as LegacyManyArray<T>;\n switch (prop) {\n case 'length 0': {\n Reflect.set(target, 'length', 0);\n mutateReplaceRelatedRecords(collection, [], _SIGNAL);\n return true;\n }\n case 'replace cell': {\n const [index, prior, value] = args as [number, ResourceKey, ResourceKey];\n target[index] = value;\n mutateReplaceRelatedRecord(collection, { value, prior, index }, _SIGNAL);\n return true;\n }\n case 'push': {\n const newValues = extractIdentifiersFromRecords(args);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.push(...newValues),\n `Cannot push duplicates to a hasMany's state.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const seen = new Set(target);\n const unique = new Set<OpaqueRecordInstance>();\n\n args.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.add(item);\n }\n });\n\n const newArgs = Array.from(unique);\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n if (newArgs.length) {\n mutateAddToRelatedRecords(collection, { value: extractIdentifiersFromRecords(newArgs) }, _SIGNAL);\n }\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (newValues.length) {\n mutateAddToRelatedRecords(collection, { value: newValues }, _SIGNAL);\n }\n return result;\n }\n\n case 'pop': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n if (result) {\n mutateRemoveFromRelatedRecords(\n collection,\n { value: recordIdentifierFor(result as OpaqueRecordInstance) },\n _SIGNAL\n );\n }\n return result;\n }\n\n case 'unshift': {\n const newValues = extractIdentifiersFromRecords(args);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.unshift(...newValues),\n `Cannot unshift duplicates to a hasMany's state.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const seen = new Set(target);\n const unique = new Set<OpaqueRecordInstance>();\n\n args.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.add(item);\n }\n });\n\n const newArgs = Array.from(unique);\n const result: unknown = Reflect.apply(target[prop], receiver, newArgs);\n\n if (newArgs.length) {\n mutateAddToRelatedRecords(collection, { value: extractIdentifiersFromRecords(newArgs), index: 0 }, _SIGNAL);\n }\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (newValues.length) {\n mutateAddToRelatedRecords(collection, { value: newValues, index: 0 }, _SIGNAL);\n }\n return result;\n }\n\n case 'shift': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n\n if (result) {\n mutateRemoveFromRelatedRecords(\n collection,\n { value: recordIdentifierFor(result as OpaqueRecordInstance), index: 0 },\n _SIGNAL\n );\n }\n return result;\n }\n\n case 'sort': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n mutateSortRelatedRecords(collection, (result as OpaqueRecordInstance[]).map(recordIdentifierFor), _SIGNAL);\n return result;\n }\n\n case 'splice': {\n const [start, _deleteCount, ...adds] = args as [number, number | undefined, ...OpaqueRecordInstance[]];\n\n // Don't know if I like this approach, is there not a way where we can just use splice, see what it deleted and go from there?\n let deleteCount;\n if (args.length === 1) {\n // Omitting deleteCount: remove ALL elements (a.k.a. Infinity)\n deleteCount = Infinity;\n } else {\n // deleteCount is undefined, not a valid number, a negative number...\n if (typeof _deleteCount !== 'number' || _deleteCount < 0) {\n // do not remove any elements\n deleteCount = 0;\n } else {\n deleteCount = _deleteCount;\n }\n }\n\n // sanitize deleteCount to not exceed length / amount of items from index to end\n deleteCount = Math.min(collection[Context].source.length - start, deleteCount);\n\n // detect a full replace\n if (start === 0 && deleteCount === collection[Context].source.length) {\n const newValues = extractIdentifiersFromRecords(adds);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.splice(start, deleteCount, ...newValues),\n `Cannot replace a hasMany's state with a new state that contains duplicates.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const current = new Set(adds);\n const unique = Array.from(current);\n const newArgs = ([start, deleteCount] as unknown[]).concat(unique);\n\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n mutateReplaceRelatedRecords(collection, extractIdentifiersFromRecords(unique), _SIGNAL);\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n mutateReplaceRelatedRecords(collection, newValues, _SIGNAL);\n return result;\n }\n\n const newValues = extractIdentifiersFromRecords(adds);\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.splice(start, deleteCount, ...newValues),\n `Cannot splice a hasMany's state with a new state that contains duplicates.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const currentState = target.slice();\n currentState.splice(start, deleteCount);\n\n const seen = new Set(currentState);\n const unique: OpaqueRecordInstance[] = [];\n adds.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.push(item);\n }\n });\n\n const newArgs = [start, deleteCount, ...unique];\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n if (deleteCount > 0) {\n mutateRemoveFromRelatedRecords(collection, { value: result.map(recordIdentifierFor), index: start }, _SIGNAL);\n }\n\n if (unique.length > 0) {\n mutateAddToRelatedRecords(\n collection,\n { value: extractIdentifiersFromRecords(unique), index: start },\n _SIGNAL\n );\n }\n\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (deleteCount > 0) {\n mutateRemoveFromRelatedRecords(collection, { value: result.map(recordIdentifierFor), index: start }, _SIGNAL);\n }\n if (newValues.length > 0) {\n mutateAddToRelatedRecords(collection, { value: newValues, index: start }, _SIGNAL);\n }\n return result;\n }\n default:\n assert(`unable to convert ${prop} into a transaction that updates the cache state for this record array`);\n }\n}\n\nfunction notify(this: LegacyManyArray): void {\n notifyInternalSignal(this[Context].signal);\n}\n\nfunction reload<T>(this: LegacyManyArray<T>, options?: BaseFinderOptions): Promise<LegacyManyArray<T>> {\n const { manager } = this[Context];\n assert(`Expected the manager for ManyArray to implement reloadHasMany`, typeof manager.reloadHasMany === 'function');\n // TODO this is odd, we don't ask the store for anything else like this?\n return manager.reloadHasMany<T>(this.key, options) as Promise<LegacyManyArray<T>>;\n}\n\nfunction createRecord<T>(this: LegacyManyArray<T>, hash: CreateRecordProperties<T>): T {\n const { store } = this[Context];\n assert(`Expected modelName to be set`, this.modelName);\n const record = store.createRecord<T>(this.modelName as TypeFromInstance<T>, hash);\n this.push(record);\n\n return record;\n}\n\nfunction destroyLegacyManyArray(this: ReactiveResourceArray): void {\n destroy.call(this, false);\n}\n\ntype PromiseProxyRecord = { then(): void; content: OpaqueRecordInstance | null | undefined };\n\nfunction assertRecordPassedToHasMany(record: OpaqueRecordInstance | PromiseProxyRecord) {\n assert(\n `All elements of a hasMany relationship must be instances of Model, you passed ${typeof record}`,\n (function () {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n })()\n );\n}\n\nfunction extractIdentifiersFromRecords(records: OpaqueRecordInstance[]): ResourceKey[] {\n return records.map(extractIdentifierFromRecord);\n}\n\nfunction extractIdentifierFromRecord(recordOrPromiseRecord: PromiseProxyRecord | OpaqueRecordInstance) {\n assertRecordPassedToHasMany(recordOrPromiseRecord);\n return recordIdentifierFor(recordOrPromiseRecord);\n}\n\nfunction assertNoDuplicates<T>(\n collection: LegacyManyArray<T>,\n target: ResourceKey[],\n callback: (currentState: ResourceKey[]) => void,\n reason: string\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n const state = target.slice();\n callback(state);\n\n if (state.length !== new Set(state).size) {\n const duplicates = state.filter((currentValue, currentIndex) => state.indexOf(currentValue) !== currentIndex);\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n deprecate(\n `${reason} This behavior is deprecated. Found duplicates for the following records within the new state provided to \\`<${\n identifier.type\n }:${identifier.id || identifier.lid}>.${collection.key}\\`\\n\\t- ${Array.from(new Set(duplicates))\n .map((r) => (isResourceKey(r) ? r.lid : recordIdentifierFor(r).lid))\n .sort((a, b) => a.localeCompare(b))\n .join('\\n\\t- ')}`,\n false,\n {\n id: 'ember-data:deprecate-many-array-duplicates',\n for: 'ember-data',\n until: '6.0',\n since: {\n enabled: '5.3',\n available: '4.13',\n },\n }\n );\n } else {\n throw new Error(\n `${reason} Found duplicates for the following records within the new state provided to \\`<${\n identifier.type\n }:${identifier.id || identifier.lid}>.${collection.key}\\`\\n\\t- ${Array.from(new Set(duplicates))\n .map((r) => (isResourceKey(r) ? r.lid : recordIdentifierFor(r).lid))\n .sort((a, b) => a.localeCompare(b))\n .join('\\n\\t- ')}`\n );\n }\n }\n}\n\nfunction mutateAddToRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n operationInfo: { value: ResourceKey | ResourceKey[]; index?: number },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'add',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateRemoveFromRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n operationInfo: { value: ResourceKey | ResourceKey[]; index?: number },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'remove',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateReplaceRelatedRecord<T>(\n collection: LegacyManyArray<T>,\n operationInfo: {\n value: ResourceKey;\n prior: ResourceKey;\n index: number;\n },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'replaceRelatedRecord',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateReplaceRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n value: ResourceKey[],\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'replaceRelatedRecords',\n record: identifier,\n field: collection.key,\n value,\n },\n _SIGNAL\n );\n}\n\nfunction mutateSortRelatedRecords<T>(collection: LegacyManyArray<T>, value: ResourceKey[], _SIGNAL: WarpDriveSignal) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'sortRelatedRecords',\n record: identifier,\n field: collection.key,\n value,\n },\n _SIGNAL\n );\n}\n\nfunction mutate<T>(collection: LegacyManyArray<T>, mutation: LocalRelationshipOperation, _SIGNAL: WarpDriveSignal) {\n const { manager } = collection[Context];\n\n assert(`Expected the manager for ManyArray to implement mutate`, typeof manager.mutate === 'function');\n manager.mutate(mutation);\n notifyInternalSignal(_SIGNAL);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { LegacyAliasField, ObjectAliasField, PolarisAliasField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getAliasField(context: KindContext<LegacyAliasField | ObjectAliasField | PolarisAliasField>): unknown {\n assert(`Alias field access is not implemented`);\n}\n\nexport function setAliasField(context: KindContext<LegacyAliasField | ObjectAliasField | PolarisAliasField>): boolean {\n assert(`Alias field setting is not implemented`);\n return false;\n}\n","import { DEPRECATE_COMPUTED_CHAINS } from '@warp-drive/build-config/deprecations';\nimport { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../../index.ts';\nimport type { WarpDriveSignal } from '../../../signals/-private.ts';\nimport { ARRAY_SIGNAL, consumeInternalSignal, entangleSignal, withSignalStore } from '../../../signals/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { ArrayValue, ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { OpaqueRecordInstance } from '../../../types/record.ts';\nimport type { ArrayField, HashField, SchemaArrayField } from '../../../types/schema/fields.ts';\nimport type { KindContext, ObjectContext } from '../default-mode.ts';\nimport { ReactiveResource } from '../record.ts';\nimport type { SchemaService } from '../schema.ts';\nimport { Context, Destroy, SOURCE } from '../symbols.ts';\nimport type { ProxiedMethod } from './extension.ts';\nimport { isExtensionProp, performArrayExtensionGet, performExtensionSet } from './extension.ts';\n\ntype KeyType = string | symbol | number;\nconst ARRAY_GETTER_METHODS = new Set<KeyType>([\n Symbol.iterator,\n 'concat',\n 'entries',\n 'every',\n 'fill',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'forEach',\n 'includes',\n 'indexOf',\n 'join',\n 'keys',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'values',\n]);\n// const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\nconst SYNC_PROPS = new Set<KeyType>(['[]', 'length']);\nfunction isArrayGetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_GETTER_METHODS.has(prop);\n}\nconst ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\n\nfunction isArraySetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_SETTER_METHODS.has(prop);\n}\n\n// function isSelfProp<T extends object>(self: T, prop: KeyType): prop is keyof T {\n// return prop in self;\n// }\n\nfunction convertToInt(prop: KeyType): number | null {\n if (typeof prop === 'symbol') return null;\n\n const num = Number(prop);\n\n if (isNaN(num)) return null;\n\n return num % 1 === 0 ? num : null;\n}\n\ntype ForEachCB = (record: OpaqueRecordInstance, index: number, context: typeof Proxy<unknown[]>) => void;\nfunction safeForEach(\n instance: typeof Proxy<unknown[]>,\n arr: unknown[],\n store: Store,\n callback: ForEachCB,\n target: unknown\n) {\n if (target === undefined) {\n target = null;\n }\n // clone to prevent mutation\n arr = arr.slice();\n assert('`forEach` expects a function as first argument.', typeof callback === 'function');\n\n // because we retrieveLatest above we need not worry if array is mutated during iteration\n // by unloadRecord/rollbackAttributes\n // push/add/removeObject may still be problematic\n // but this is a more traditionally expected forEach bug.\n const length = arr.length; // we need to access length to ensure we are consumed\n\n for (let index = 0; index < length; index++) {\n callback.call(target, arr[index], index, instance);\n }\n\n return instance;\n}\n\ntype MemoizedSchemaObject = {\n type: string;\n identity: number | string | object;\n index: number;\n context: ObjectContext;\n value: WeakRef<ReactiveResource>;\n};\n\nexport interface ManagedArray extends Omit<Array<unknown>, '[]'> {\n [SOURCE]: unknown[];\n identifier: ResourceKey;\n path: string | string[];\n owner: ReactiveResource;\n [ARRAY_SIGNAL]: WarpDriveSignal;\n [Context]: KindContext<SchemaArrayField | ArrayField>;\n}\n\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ManagedArray {\n constructor(context: KindContext<SchemaArrayField | ArrayField>, owner: ReactiveResource, data: unknown[]) {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n this[SOURCE] = data?.slice();\n const IS_EDITABLE = context.editable ?? false;\n this[Context] = context;\n const schema = context.store.schema as SchemaService;\n const cache = context.store.cache;\n const { field } = context;\n\n const signals = withSignalStore(this);\n let _SIGNAL: WarpDriveSignal = null as unknown as WarpDriveSignal;\n const boundFns = new Map<KeyType, ProxiedMethod>();\n this.identifier = context.resourceKey;\n this.path = context.path;\n this.owner = owner;\n let transaction = false;\n type StorageKlass = typeof WeakMap<object, MemoizedSchemaObject>;\n const KeyMode = (field as SchemaArrayField).options?.key ?? '@identity';\n // listener.\n const RefStorage: StorageKlass =\n KeyMode === '@identity'\n ? WeakMap\n : // CAUTION CAUTION CAUTION\n // this is a pile of lies\n // the Map is Map<string, WeakRef<ReactiveResource>>\n // but TS does not understand how to juggle modes like this\n // internal to a method like ours without us duplicating the code\n // into two separate methods.\n Map<object, MemoizedSchemaObject>;\n const ManagedRecordRefs = field.kind === 'schema-array' ? new RefStorage() : null;\n const extensions = context.legacy ? schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions(field) : null;\n const proxy = new Proxy(this[SOURCE], {\n get<R extends typeof Proxy<unknown[]>>(target: unknown[], prop: keyof R, receiver: R) {\n if (prop === ARRAY_SIGNAL) {\n return _SIGNAL;\n }\n if (prop === 'identifier') {\n return self.identifier;\n }\n if (prop === 'owner') {\n return self.owner;\n }\n if (prop === Context) {\n return self[Context];\n }\n\n const index = convertToInt(prop);\n if (_SIGNAL.isStale && (index !== null || SYNC_PROPS.has(prop) || isArrayGetter(prop))) {\n _SIGNAL.isStale = false;\n const newData = cache.getAttr(context.resourceKey, context.path);\n if (newData && newData !== self[SOURCE]) {\n self[SOURCE].length = 0;\n self[SOURCE].push(...(newData as ArrayValue));\n }\n }\n\n if (prop === 'length') {\n return (consumeInternalSignal(_SIGNAL), target.length);\n }\n if (prop === '[]') return (consumeInternalSignal(_SIGNAL), receiver);\n\n if (index !== null) {\n if (!transaction) {\n consumeInternalSignal(_SIGNAL);\n }\n const rawValue = target[index];\n\n if (field.kind === 'array') {\n if (field.type) {\n const transform = schema.transformation(field);\n return transform.hydrate(rawValue as Value, field.options ?? null, self.owner);\n }\n return rawValue;\n }\n\n /**\n * When the array is polymorphic, we need to determine the real type\n * in order to apply the correct identity as schema-object identity\n * is only required to be unique by type\n */\n let objectType: string;\n if (field.options?.polymorphic) {\n const typePath = (field.options.type as string) ?? 'type';\n // if we are polymorphic, then context.field.options.type will\n // either specify a path on the rawValue to use as the type, defaulting to \"type\" or\n // the special string \"@hash\" which tells us to treat field.type as a hashFn name with which\n // to calc the type.\n if (typePath === '@hash') {\n assert(`Expected the field to define a hashFn as its type`, field.type);\n const hashFn = schema.hashFn({ type: field.type });\n // TODO consider if there are better options and name args we could provide.\n objectType = hashFn(rawValue as object, null, null);\n } else {\n objectType = (rawValue as ObjectValue)[typePath] as string;\n assert(\n `Expected the type path for the field to be a value on the raw object`,\n typePath && objectType && typeof objectType === 'string'\n );\n }\n } else {\n assert(`A non-polymorphic SchemaArrayField must provide a SchemaObject type in its definition`, field.type);\n objectType = field.type;\n }\n\n /**\n * When KeyMode=@hash the ReactiveResource is keyed into\n * ManagedRecordRefs by the return value of @hash on the rawValue.\n *\n * This means that we could find a way to only recompute the identity\n * when ARRAY_SIGNAL is dirty if hash performance becomes a bottleneck.\n */\n let schemaObjectKeyValue: string | number | object;\n if (KeyMode === '@hash') {\n const hashField = schema.resource({ type: objectType! }).identity as HashField;\n const hashFn = schema.hashFn(hashField);\n schemaObjectKeyValue = hashFn(rawValue as object, hashField.options ?? null, hashField.name);\n } else {\n // if mode is not @identity or @index, then access the key path.\n // we should assert that `mode` is a string\n // it should read directly from the cache value for that field (e.g. no derivation, no transformation)\n // and, we likely should lookup the associated field and throw an error IF\n // the given field does not exist OR\n // the field is anything other than a GenericField or LegacyAttributeField.\n if (DEBUG) {\n const isPathKeyMode = KeyMode !== '@identity' && KeyMode !== '@index';\n if (isPathKeyMode) {\n assert('mode must be a string', typeof KeyMode === 'string' && KeyMode !== '');\n const modeField = schema.fields({ type: objectType! }).get(KeyMode);\n assert('field must exist in schema', modeField);\n assert(\n 'field must be a GenericField or LegacyAttributeField',\n modeField.kind === 'field' || modeField.kind === 'attribute'\n );\n }\n }\n schemaObjectKeyValue =\n KeyMode === '@identity'\n ? (rawValue as object)\n : KeyMode === '@index'\n ? index\n : ((rawValue as ObjectValue)[KeyMode] as string | number | object);\n }\n\n if (!schemaObjectKeyValue && schemaObjectKeyValue !== 0) {\n assert(`Unexpected out of bounds access on SchemaArray`);\n return undefined;\n }\n\n const recordRef = ManagedRecordRefs!.get(schemaObjectKeyValue as object);\n const record = recordRef?.value.deref();\n\n // confirm the type and key still match\n if (record && recordRef!.type === objectType && recordRef!.identity === schemaObjectKeyValue) {\n if (recordRef!.index !== index) {\n recordRef!.index = index;\n recordRef!.context.path[recordRef!.context.path.length - 1] = index as unknown as string;\n }\n return record;\n } else if (record) {\n // TODO schedule idle once we can\n void Promise.resolve().then(() => {\n record[Destroy]();\n });\n }\n\n const recordPath = context.path.slice();\n // this is a dirty lie since path is string[] but really we\n // should change the types for paths to `Array<string | number>`\n recordPath.push(index as unknown as string);\n\n const objectContext = {\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: recordPath,\n field: field,\n value: objectType,\n };\n const schemaObject = new ReactiveResource(objectContext);\n\n ManagedRecordRefs!.set(schemaObjectKeyValue as object, {\n type: objectType,\n identity: schemaObjectKeyValue,\n index,\n context: objectContext,\n value: new WeakRef(schemaObject),\n });\n\n return schemaObject;\n }\n\n if (isArrayGetter(prop)) {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n if (prop === 'forEach') {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n transaction = true;\n const result = safeForEach(receiver, target, context.store, arguments[0] as ForEachCB, arguments[1]);\n transaction = false;\n return result;\n };\n } else {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n transaction = false;\n return result;\n };\n }\n boundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (isArraySetter(prop)) {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n if (!IS_EDITABLE) {\n throw new Error(\n `Mutating this array via ${String(prop)} is not allowed because the ReactiveResource is not editable`\n );\n }\n consumeInternalSignal(_SIGNAL);\n transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n transaction = false;\n return result;\n };\n boundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performArrayExtensionGet(\n receiver,\n extensions!,\n signals,\n prop,\n _SIGNAL,\n boundFns,\n (v: boolean) => void (transaction = v)\n );\n }\n\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop: KeyType, value: unknown, receiver: object) {\n if (!IS_EDITABLE) {\n let errorPath = context.resourceKey.type;\n if (context.path) {\n errorPath = context.path[context.path.length - 1];\n }\n assert(`Cannot set ${String(prop)} on ${errorPath} because the ReactiveResource is not editable`);\n return false;\n }\n if (prop === 'identifier') {\n self.identifier = value as ResourceKey;\n return true;\n }\n if (prop === 'owner') {\n self.owner = value as ReactiveResource;\n return true;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n const reflect = Reflect.set(target, prop, value, receiver);\n\n if (reflect) {\n if (!field.type) {\n cache.setAttr(context.resourceKey, context.path, self[SOURCE] as Value);\n _SIGNAL.isStale = true;\n return true;\n }\n\n let rawValue = self[SOURCE] as ArrayValue;\n if (field.kind !== 'schema-array') {\n const transform = schema.transformation(field);\n if (!transform) {\n throw new Error(\n `No '${field.type}' transform defined for use by ${context.resourceKey.type}.${String(prop)}`\n );\n }\n rawValue = (self[SOURCE] as ArrayValue).map((item) =>\n transform.serialize(item, field.options ?? null, self.owner)\n );\n }\n cache.setAttr(context.resourceKey, context.path, rawValue);\n _SIGNAL.isStale = true;\n }\n return reflect;\n },\n has(target, prop) {\n if (prop === 'identifier' || prop === 'owner' || prop === ARRAY_SIGNAL) {\n return true;\n }\n return Reflect.has(target, prop);\n },\n }) as ManagedArray;\n\n // we entangle the signal on the returned proxy since that is\n // the object that other code will be interfacing with.\n _SIGNAL = entangleSignal(signals, proxy, ARRAY_SIGNAL, undefined);\n\n return proxy;\n }\n}\n\n// this will error if someone tries to call\n// A(identifierArray) since it is not configurable\n// which is preferable to the `meta` override we used\n// before which required importing all of Ember\nconst desc = {\n enumerable: true,\n configurable: false,\n get: function () {\n // here to support computed chains\n // and {{#each}}\n if (DEPRECATE_COMPUTED_CHAINS) {\n return this;\n }\n },\n};\n// compat(desc);\nObject.defineProperty(ManagedArray.prototype, '[]', desc);\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ARRAY_SIGNAL, entangleSignal, peekInternalSignal } from '../../../signals/-private';\nimport type { ArrayValue, ObjectValue } from '../../../types/json/raw';\nimport type { ArrayField, SchemaArrayField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedArray } from '../fields/managed-array';\n\nexport function getArrayField(context: KindContext<ArrayField | SchemaArrayField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n // the thing we hand out needs to know its owner and path in a private manner\n // its \"address\" is the parent identifier (identifier) + field name (field.name)\n // in the nested object case field name here is the full dot path from root resource to this value\n // its \"key\" is the field on the parent record\n // its \"owner\" is the parent record\n const { record } = context;\n let managedArray = signal.value as ManagedArray | null;\n\n if (managedArray) {\n // if the signal is stale, we need to check the rawValue has not become\n // `null`.\n if (signal.isStale) {\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n const rawValue = cache.getAttr(resourceKey, path);\n // if the rawValue is null or the rawValue is undefined and the field has no defaultValue\n // we need to reset the managedArray to null\n if (rawValue === null || (!rawValue && typeof rawValue === 'undefined' && !field.options?.defaultValue)) {\n signal.value = null;\n // TODO once we fix schema-object GC we should run Destroy here on the managed array\n return null;\n }\n }\n return managedArray;\n } else {\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as unknown[];\n\n // we only apply the defaultValue if the rawValue is undefined, this allows\n // use of explicit null for the field.\n if (!rawValue && typeof rawValue === 'undefined' && field.options?.defaultValue) {\n rawValue = [];\n }\n\n if (!rawValue) {\n return null;\n }\n managedArray = new ManagedArray(context, record, rawValue);\n signal.value = managedArray;\n }\n return managedArray;\n}\n\nexport function setArrayField(context: KindContext<ArrayField>): boolean {\n const { field, record, value } = context;\n const { cache, schema } = context.store;\n const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1)!);\n const peeked = fieldSignal?.value as ManagedArray | undefined;\n\n const transform = field.type ? schema.transformation(field) : null;\n // prettier-ignore\n const rawValue = value === null ? null\n : field.type ? (value as ArrayValue).map((item) => transform!.serialize(item, (field.options as ObjectValue) ?? null, record))\n : (value as ArrayValue)?.slice();\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n if (peeked) {\n assert(`Expected the peekManagedArray for ${field.kind} to return a ManagedArray`, ARRAY_SIGNAL in peeked);\n const arrSignal = peeked[ARRAY_SIGNAL];\n arrSignal.isStale = true;\n // TODO run array destroy?\n }\n\n if (!Array.isArray(rawValue) && fieldSignal) {\n fieldSignal.value = null;\n }\n\n return true;\n}\n","import { entangleInitiallyStaleSignal } from '../../../signals/-private';\nimport type { Value } from '../../../types/json/raw';\nimport type { LegacyAttributeField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getAttributeField(context: KindContext<LegacyAttributeField>): unknown {\n entangleInitiallyStaleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { cache } = context.store;\n return context.editable\n ? cache.getAttr(context.resourceKey, context.path)\n : cache.getRemoteAttr(context.resourceKey, context.path);\n}\n\nexport function setAttributeField(context: KindContext<LegacyAttributeField>): boolean {\n context.store.cache.setAttr(context.resourceKey, context.path, context.value as Value);\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { CacheableFieldSchema, FieldSchema, HashField, IdentityField } from '../../../types/schema/fields.ts';\n\nconst InvalidKinds = ['alias', 'derived', '@local'] as const;\ntype InvalidKind = 'alias' | 'derived' | '@local';\n\nexport function isInvalidKind(kind: string): kind is InvalidKind {\n return InvalidKinds.includes(kind as InvalidKind);\n}\n\nexport function isNonIdentityCacheableField(\n field: FieldSchema | IdentityField | HashField\n): field is Exclude<CacheableFieldSchema, IdentityField> {\n return !isInvalidKind(field.kind) && field.kind !== '@id' && field.kind !== '@hash';\n}\n\nexport function getFieldCacheKeyStrict(field: CacheableFieldSchema): string {\n return field.sourceKey || field.name;\n}\n\nexport function getFieldCacheKey(field: FieldSchema | IdentityField | HashField): string | null {\n return 'sourceKey' in field && field.sourceKey ? field.sourceKey : field.name;\n}\n\nexport function assertIsCacheField(field: FieldSchema | IdentityField): asserts field is CacheableFieldSchema {\n assert(\n `The FieldSchema ${field.kind} is not a CacheField and cannot be used to retrieve cache data`,\n !isInvalidKind(field.kind)\n );\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { cacheKeyFor } from '../../..';\nimport { entangleSignal } from '../../../signals/-private';\nimport type { ResourceKey } from '../../../types';\nimport type { LegacyBelongsToField } from '../../../types/schema/fields';\nimport type { SingleResourceRelationship } from '../../../types/spec/json-api-raw';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key';\nimport type { ReactiveResource } from '../record';\nimport type { SchemaService } from '../schema';\n\nexport function getBelongsToField(context: KindContext<LegacyBelongsToField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { field, resourceKey, store } = context;\n const { schema, cache } = store;\n if (field.options.linksMode) {\n const rawValue = context.editable\n ? (cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field)) as SingleResourceRelationship)\n : (cache.getRemoteRelationship(resourceKey, getFieldCacheKeyStrict(field)) as SingleResourceRelationship);\n\n return rawValue.data ? store.peekRecord(rawValue.data) : null;\n }\n\n // FIXME move this to a \"LegacyMode\" make this part of \"PolarisMode\"\n assert(`Can only use belongsTo fields when the resource is in legacy mode`, context.legacy);\n return (schema as SchemaService)._kind('@legacy', 'belongsTo').get(store, context.record, resourceKey, field);\n}\n\nexport function setBelongsToField(context: KindContext<LegacyBelongsToField>): boolean {\n const { field, resourceKey, store } = context;\n const { schema, cache } = store;\n\n /**\n * We currently only allow editing sync belongsTo relationships\n * in PolarisMode\n */\n const isValidPolarisConfig = field.options.linksMode && !field.options.async;\n if (!context.legacy && isValidPolarisConfig) {\n const name = context.path.at(-1)!;\n cache.mutate(\n {\n op: 'replaceRelatedRecord',\n record: resourceKey,\n field: name,\n value: getResourceKey(context.value as ReactiveResource | null),\n },\n // @ts-expect-error\n true\n );\n return true;\n }\n\n assert(`Can only mutate belongsTo fields when the resource is in legacy mode`, context.legacy);\n (schema as SchemaService)\n ._kind('@legacy', 'belongsTo')\n .set(store, context.record, context.resourceKey, context.field, context.value);\n return true;\n}\n\nexport function getResourceKey(record: ReactiveResource | null): ResourceKey | null {\n if (!record) {\n return null;\n }\n\n return cacheKeyFor(record);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private';\nimport type { CollectionField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getCollectionField(context: KindContext<CollectionField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n assert(`Accessing collection fields is not yet implemented`);\n}\n\nexport function setCollectionField(context: KindContext<CollectionField>): boolean {\n assert(`Setting collection fields is not yet implemented`);\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { DerivedField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getDerivedField(context: KindContext<DerivedField>): unknown {\n const { schema } = context.store;\n return schema.derivation(context.field)(context.record, context.field.options ?? null, context.field.name);\n}\n\nexport function setDerivedField(context: KindContext<DerivedField>): boolean {\n assert(\n `ILLEGAL SET: Cannot set '${context.path.join('.')}' on '${context.resourceKey.type}' as ${context.field.kind} fields are not mutable`\n );\n return false;\n}\n","import { entangleInitiallyStaleSignal } from '../../../signals/-private';\nimport type { Value } from '../../../types/json/raw';\nimport type { GenericField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getGenericField(context: KindContext<GenericField>): unknown {\n const signal = entangleInitiallyStaleSignal(context.signals, context.record, context.path.at(-1)!, null);\n // FIXME we should be able to cache the computation here, but some tests fail.\n // if (!signal.isStale) {\n // return signal.value;\n // }\n signal.isStale = false;\n const { cache, schema } = context.store;\n const rawValue = context.editable\n ? cache.getAttr(context.resourceKey, context.path)\n : cache.getRemoteAttr(context.resourceKey, context.path);\n\n const { field } = context;\n if (!field.type) {\n // signal.value = rawValue;\n return rawValue;\n }\n\n const transform = schema.transformation(field);\n // signal.value = transform.hydrate(rawValue, field.options ?? null, context.record);\n // return signal.value;\n return transform.hydrate(rawValue, field.options ?? null, context.record);\n}\n\nexport function setGenericField(context: KindContext<GenericField>): boolean {\n const { cache, schema } = context.store;\n const { field } = context;\n\n if (!field.type) {\n cache.setAttr(context.resourceKey, context.path, context.value as Value);\n return true;\n }\n\n const transform = schema.transformation(field);\n const rawValue = transform.serialize(context.value, field.options ?? null, context.record);\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n return true;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../../index.ts';\nimport type { RelatedCollection as ManyArray } from '../../../store/-private.ts';\nimport { fastPush } from '../../../store/-private.ts';\nimport type { CollectionRelationship } from '../../../types/cache/relationship.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { CacheOptions } from '../../../types/request.ts';\nimport { EnableHydration } from '../../../types/request.ts';\nimport type { CollectionResourceRelationship } from '../../../types/spec/json-api-raw.ts';\nimport type { ReactiveResource } from '../record.ts';\nimport { Context } from '../symbols.ts';\n\nexport interface FindHasManyOptions {\n reload?: boolean;\n backgroundReload?: boolean;\n}\n\nexport class ManyArrayManager {\n declare record: ReactiveResource;\n declare store: Store;\n declare identifier: ResourceKey;\n declare editable: boolean;\n\n constructor(record: ReactiveResource, editable: boolean) {\n const context = record[Context];\n this.record = record;\n this.store = context.store;\n this.identifier = context.resourceKey;\n this.editable = editable;\n }\n\n _syncArray(array: ManyArray): void {\n const method = this.editable ? 'getRelationship' : 'getRemoteRelationship';\n // FIXME field needs to use sourceKey\n const rawValue = this.store.cache[method](this.identifier, array.key) as CollectionRelationship;\n\n if (rawValue.meta) {\n array.meta = rawValue.meta;\n }\n\n if (rawValue.links) {\n array.links = rawValue.links;\n }\n\n const currentState = array[Context].source;\n\n // rawValue.data is undefined when the relationship has never received membership\n // data (e.g. a links-only payload) - there is nothing to sync in that case, and the\n // array must already be empty since it could only ever have been populated from data\n if (rawValue.data !== undefined && currentState !== rawValue.data) {\n // unlike in the normal RecordArray case, we don't need to divorce the reference\n // because we don't need to worry about associate/disassociate since the graph\n // takes care of that for us\n currentState.length = 0;\n fastPush(currentState, rawValue.data);\n }\n }\n\n reloadHasMany<T>(key: string, options?: FindHasManyOptions): Promise<ManyArray<T>> {\n // FIXME field needs to use sourceKey\n const field = this.store.schema.fields(this.identifier).get(key);\n assert(`Expected a hasMany field for ${key}`, field?.kind === 'hasMany');\n\n const cacheOptions = options ? extractCacheOptions(options) : { reload: true };\n cacheOptions.types = [field.type];\n\n const rawValue = this.store.cache.getRelationship(this.identifier, key) as CollectionRelationship;\n\n const req = {\n url: getRelatedLink(rawValue),\n op: 'findHasMany',\n method: 'GET' as const,\n records: rawValue.data as ResourceKey[],\n cacheOptions,\n options: {\n field,\n identifier: this.identifier,\n links: rawValue.links,\n meta: rawValue.meta,\n },\n [EnableHydration]: false,\n };\n\n return this.store.request(req) as unknown as Promise<ManyArray<T>>;\n }\n\n mutate(mutation: LocalRelationshipOperation): void {\n this.store.cache.mutate(mutation);\n }\n}\n\nfunction getRelatedLink(resource: CollectionResourceRelationship): string {\n const related = resource.links?.related;\n assert(`Expected a related link`, related);\n\n return typeof related === 'object' ? related.href : related;\n}\n\nfunction extractCacheOptions(options: FindHasManyOptions) {\n const cacheOptions: CacheOptions = {};\n if ('reload' in options) {\n cacheOptions.reload = options.reload;\n }\n if ('backgroundReload' in options) {\n cacheOptions.backgroundReload = options.backgroundReload;\n }\n return cacheOptions;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private.ts';\nimport type { RelatedCollection as ManyArray } from '../../../store/-private.ts';\nimport { createLegacyManyArray } from '../../../store/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { LegacyHasManyField } from '../../../types/schema/fields.ts';\nimport type { CollectionResourceRelationship } from '../../../types/spec/json-api-raw.ts';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key.ts';\nimport { ManyArrayManager } from '../fields/many-array-manager.ts';\nimport type { SchemaService } from '../schema.ts';\n\nexport function getHasManyField(context: KindContext<LegacyHasManyField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { store, field } = context;\n if (field.options.linksMode) {\n const { record } = context;\n // the thing we hand out needs to know its owner and path in a private manner\n // its \"address\" is the parent identifier (identifier) + field name (field.name)\n // in the nested object case field name here is the full dot path from root resource to this value\n // its \"key\" is the field on the parent record\n // its \"owner\" is the parent record\n\n const cached = signal.value as ManyArray | undefined;\n if (cached) {\n return cached;\n }\n const { editable, resourceKey } = context;\n const { cache } = store;\n // the editable copy renders reconciled local state; the readonly copy\n // renders remote state (and re-pulls remote state when notified on the\n // 'remote' channel), mirroring ManyArrayManager._syncArray and\n // getBelongsToField.\n const rawValue = (\n editable\n ? cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field))\n : cache.getRemoteRelationship(resourceKey, getFieldCacheKeyStrict(field))\n ) as CollectionResourceRelationship;\n if (!rawValue) {\n return null;\n }\n const managedArray = createLegacyManyArray({\n store,\n manager: new ManyArrayManager(record, editable),\n source: (rawValue.data?.slice() ?? []) as ResourceKey[],\n type: field.type,\n isLoaded: true,\n editable,\n isAsync: field.options.async ?? false,\n isPolymorphic: field.options.polymorphic ?? false,\n field,\n identifier: resourceKey,\n links: rawValue.links || null,\n meta: rawValue.meta || null,\n });\n signal.value = managedArray;\n return managedArray;\n }\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n return (store.schema as SchemaService)\n ._kind('@legacy', 'hasMany')\n .get(store, context.record, context.resourceKey, field);\n}\n\nexport function setHasManyField(context: KindContext<LegacyHasManyField>): boolean {\n const { store } = context;\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n assert(`You must pass an array of records to set a hasMany relationship`, Array.isArray(context.value));\n (store.schema as SchemaService)\n ._kind('@legacy', 'hasMany')\n .set(store, context.record, context.resourceKey, context.field, context.value);\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { HashField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getHashField(context: KindContext<HashField>): unknown {\n const { field, path, resourceKey } = context;\n const { schema, cache } = context.store;\n assert(`Cannot use a ${field.kind} directly on a resource.`, Array.isArray(path) && path.length > 1);\n const realPath = path.slice(0, -1);\n const rawData = context.editable ? cache.getAttr(resourceKey, realPath) : cache.getRemoteAttr(resourceKey, realPath);\n return schema.hashFn(field)(rawData as object, field.options ?? null, field.name ?? null);\n}\n\nexport function setHashField(context: KindContext<HashField>): boolean {\n assert(\n `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`\n );\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private.ts';\nimport type { IdentityField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getIdentityField(context: KindContext<IdentityField>): unknown {\n entangleSignal(context.signals, context.record, '@identity', null);\n return context.resourceKey.id;\n}\n\nexport function setIdentityField(context: KindContext<IdentityField>): boolean {\n const { value, resourceKey, store } = context;\n assert(`Expected to receive a string id`, typeof value === 'string' && value.length);\n const normalizedId = String(value);\n const didChange = normalizedId !== resourceKey.id;\n assert(\n `Cannot set ${resourceKey.type} record's id to ${normalizedId}, because id is already ${resourceKey.id}`,\n !didChange || resourceKey.id === null\n );\n\n if (normalizedId !== null && didChange) {\n store._instanceCache.setRecordId(resourceKey, normalizedId);\n store.notifications.notify(resourceKey, 'identity', null);\n }\n return true;\n}\n","import { consumeInternalSignal, getOrCreateInternalSignal, notifyInternalSignal } from '../../../signals/-private';\nimport type { LocalField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getLocalField(context: KindContext<LocalField>): unknown {\n const { field } = context;\n const signal = getOrCreateInternalSignal(\n context.signals,\n context.record,\n field.name,\n field.options?.defaultValue ?? null\n );\n consumeInternalSignal(signal);\n return signal.value;\n}\n\nexport function setLocalField(context: KindContext<LocalField>): boolean {\n const { value } = context;\n const signal = getOrCreateInternalSignal(context.signals, context.record, context.field.name, value);\n if (signal.value !== value) {\n signal.value = value;\n notifyInternalSignal(signal);\n }\n return true;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport {\n consumeInternalSignal,\n entangleSignal,\n notifyInternalSignal,\n OBJECT_SIGNAL,\n type WarpDriveSignal,\n withSignalStore,\n} from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { ObjectField, SchemaObjectField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\nimport type { ReactiveResource } from '../record.ts';\nimport type { SchemaService } from '../schema.ts';\nimport { Context, SOURCE } from '../symbols.ts';\nimport { isExtensionProp, performExtensionSet, performObjectExtensionGet } from './extension.ts';\n\nexport function notifyObject(obj: ManagedObject): void {\n notifyInternalSignal(obj[OBJECT_SIGNAL]);\n}\n\ntype ObjectSymbol = typeof OBJECT_SIGNAL | typeof SOURCE | typeof Context;\nconst ObjectSymbols = new Set<ObjectSymbol>([OBJECT_SIGNAL, Context, SOURCE]);\n\ntype KeyType = string | symbol | number;\n// const ignoredGlobalFields = new Set<string>(['setInterval', 'nodeType', 'nodeName', 'length', 'document', STRUCTURED]);\nexport interface ManagedObject {\n [SOURCE]: object;\n [Context]: KindContext<ObjectField>;\n [OBJECT_SIGNAL]: WarpDriveSignal;\n}\n\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ManagedObject {\n constructor(context: KindContext<ObjectField>) {\n const { field, path } = context;\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n this[SOURCE] = Object.assign({}, context.value);\n const signals = withSignalStore(this);\n const _SIGNAL = (this[OBJECT_SIGNAL] = entangleSignal(signals, this, OBJECT_SIGNAL, undefined));\n this[Context] = context;\n const identifier = context.resourceKey;\n const { cache, schema } = context.store;\n\n // prettier-ignore\n const extensions =\n !context.legacy ? null : (schema as SchemaService).CAUTION_MEGA_DANGER_ZONE_objectExtensions(field, null);\n\n const proxy = new Proxy(this[SOURCE], {\n ownKeys() {\n return Object.keys(self[SOURCE]);\n },\n\n has(target: unknown, prop: string | number | symbol) {\n return prop in self[SOURCE];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return {\n writable: context.editable,\n enumerable: true,\n configurable: true,\n };\n },\n\n get<R extends typeof Proxy<object>>(target: object, prop: keyof R, receiver: R) {\n if (ObjectSymbols.has(prop as ObjectSymbol)) {\n return self[prop as keyof typeof target];\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => null;\n }\n if (prop === Symbol.toStringTag) {\n return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;\n }\n if (prop === 'constructor') {\n return Object;\n }\n if (prop === 'toString') {\n return function () {\n return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;\n };\n }\n if (prop === 'toHTML') {\n return function () {\n return '<span>ManagedObject</span>';\n };\n }\n\n if (_SIGNAL.isStale) {\n _SIGNAL.isStale = false;\n let newData = cache.getAttr(identifier, path);\n if (newData && newData !== self[SOURCE]) {\n if (field.type) {\n const transform = schema.transformation(field);\n newData = transform.hydrate(\n newData,\n (field.options as ObjectValue) ?? null,\n context.record\n ) as ObjectValue;\n }\n self[SOURCE] = Object.assign({}, newData) as ObjectValue; // Add type assertion for newData\n }\n }\n\n // toJSON and extensions need to come after we update data if stale\n if (prop === 'toJSON') {\n return function () {\n return structuredClone(self[SOURCE]);\n };\n }\n\n // we always defer to data before extensions\n if (prop in self[SOURCE]) {\n consumeInternalSignal(_SIGNAL);\n\n return (self[SOURCE] as R)[prop];\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performObjectExtensionGet(receiver, extensions!, signals, prop);\n }\n\n return Reflect.get(target, prop, receiver) as R;\n },\n\n set(target: object, prop: KeyType, value: unknown, receiver: object) {\n assert(`Cannot set read-only property '${String(prop)}' on ManagedObject`, context.editable);\n // `assert` is stripped in production, so without this the write below would silently\n // succeed against the underlying writable `target` instead of being rejected.\n if (!context.editable) {\n return false;\n }\n\n // since objects function as dictionaries, we can't defer to schema/data before extensions\n // unless the prop is in the existing data.\n if (!(prop in self[SOURCE]) && isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n const reflect = Reflect.set(target, prop, value, receiver);\n if (!reflect) {\n return false;\n }\n\n if (!field.type) {\n cache.setAttr(identifier, path, self[SOURCE] as Value);\n } else {\n const transform = schema.transformation(field);\n const val = transform.serialize(self[SOURCE], (field.options as ObjectValue) ?? null, context.record);\n cache.setAttr(identifier, path, val);\n }\n\n _SIGNAL.isStale = true;\n return true;\n },\n }) as ManagedObject;\n\n return proxy;\n }\n}\n\nexport const ManagedObjectMap: Map<ReactiveResource, Map<string, ManagedObject | ReactiveResource>> = getOrSetGlobal(\n 'ManagedObjectMap',\n new Map<ReactiveResource, Map<string, ManagedObject | ReactiveResource>>()\n);\n\nexport function peekManagedObject(record: ReactiveResource, field: ObjectField): ManagedObject | undefined;\nexport function peekManagedObject(record: ReactiveResource, field: SchemaObjectField): ReactiveResource | undefined;\nexport function peekManagedObject(\n record: ReactiveResource,\n field: ObjectField | SchemaObjectField\n): ManagedObject | ReactiveResource | undefined {\n const managedObjectMapForRecord = ManagedObjectMap.get(record);\n if (managedObjectMapForRecord) {\n return managedObjectMapForRecord.get(field.name);\n }\n}\n","import { entangleSignal, OBJECT_SIGNAL } from '../../../signals/-private';\nimport type { ObjectValue, Value } from '../../../types/json/raw';\nimport type { ObjectField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedObject, ManagedObjectMap, peekManagedObject } from '../fields/managed-object';\n\nexport function getObjectField(context: KindContext<ObjectField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { record, field } = context;\n const managedObjectMapForRecord = ManagedObjectMap.get(record);\n let managedObject;\n if (managedObjectMapForRecord) {\n managedObject = managedObjectMapForRecord.get(field.name);\n }\n if (managedObject) {\n return managedObject;\n } else {\n const { store, resourceKey, path } = context;\n const { cache, schema } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as object;\n if (!rawValue) {\n return null;\n }\n if (field.type) {\n const transform = schema.transformation(field);\n rawValue = transform.hydrate(rawValue as ObjectValue, (field.options as ObjectValue) ?? null, record) as object;\n }\n\n managedObject = new ManagedObject({\n store,\n resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path,\n field,\n record,\n signals: context.signals,\n value: rawValue,\n });\n\n if (!managedObjectMapForRecord) {\n ManagedObjectMap.set(record, new Map([[field.name, managedObject]]));\n } else {\n managedObjectMapForRecord.set(field.name, managedObject);\n }\n }\n return managedObject;\n}\n\nexport function setObjectField(context: KindContext<ObjectField>): boolean {\n const { field, value, record } = context;\n const { cache, schema } = context.store;\n\n if (!field.type) {\n let newValue = value as Value;\n if (value !== null) {\n newValue = { ...(value as ObjectValue) };\n } else {\n ManagedObjectMap.delete(record);\n }\n\n cache.setAttr(context.resourceKey, context.path, newValue);\n\n const peeked = peekManagedObject(record, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n objSignal.isStale = true;\n }\n return true;\n }\n\n const transform = schema.transformation(field);\n const rawValue = transform.serialize({ ...(value as ObjectValue) }, (field.options as ObjectValue) ?? null, record);\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n const peeked = peekManagedObject(record, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n objSignal.isStale = true;\n }\n return true;\n}\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/build-config/macros';\n\nimport type { Future } from '../../../request';\nimport { defineSignal, entangleSignal } from '../../../signals/-private';\nimport type { StoreRequestInput } from '../../../store/-private';\nimport type { ResourceField } from '../../../types/schema/fields';\nimport type { Link, Links, SingleResourceRelationship } from '../../../types/spec/json-api-raw';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key';\nimport type { ReactiveResource } from '../record';\nimport { Context } from '../symbols';\n\ninterface ResourceRelationship<T extends ReactiveResource = ReactiveResource> {\n lid: string;\n name: string;\n [Context]: KindContext<ResourceField>;\n\n data: T | null;\n links: Links;\n meta: Record<string, unknown>;\n}\n\n// TODO probably this should just be a Document\n// but its separate until we work out the lid situation\nclass ResourceRelationship<T extends ReactiveResource = ReactiveResource> {\n constructor(context: KindContext<ResourceField>) {\n const { store, resourceKey } = context;\n const { cache } = store;\n const name = getFieldCacheKeyStrict(context.field);\n const rawValue = (\n context.editable ? cache.getRelationship(resourceKey, name) : cache.getRemoteRelationship(resourceKey, name)\n ) as SingleResourceRelationship;\n\n // TODO setup true lids for relationship documents\n // @ts-expect-error we need to give relationship documents a lid\n // oxlint-disable-next-line typescript/no-unsafe-assignment\n this.lid = rawValue.lid ?? rawValue.links?.self ?? `relationship:${resourceKey.lid}.${name}`;\n this.data = rawValue.data ? (store.peekRecord(rawValue.data) as T) : null;\n this.name = name;\n\n if (DEBUG) {\n this.links = Object.freeze(Object.assign({}, rawValue.links));\n this.meta = Object.freeze(Object.assign({}, rawValue.meta));\n } else {\n this.links = rawValue.links ?? {};\n this.meta = rawValue.meta ?? {};\n }\n\n this[Context] = context;\n }\n\n fetch(options?: StoreRequestInput<T>): Future<T> {\n const url = options?.url ?? getHref(this.links.related) ?? getHref(this.links.self) ?? null;\n\n if (!url) {\n throw new Error(\n `Cannot ${options?.method ?? 'fetch'} ${this[Context].resourceKey.type}.${String(\n this.name\n )} because it has no related link`\n );\n }\n const request = Object.assign(\n {\n url,\n method: 'GET',\n },\n options\n );\n\n return this[Context].store.request<T>(request);\n }\n}\n\ndefineSignal(ResourceRelationship.prototype, 'data', null);\ndefineSignal(ResourceRelationship.prototype, 'links', null);\ndefineSignal(ResourceRelationship.prototype, 'meta', null);\n\nfunction getHref(link?: Link | null): string | null {\n if (!link) {\n return null;\n }\n if (typeof link === 'string') {\n return link;\n }\n return link.href;\n}\n\nexport function getResourceField(context: KindContext<ResourceField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n return new ResourceRelationship(context);\n}\n\nexport function setResourceField(context: KindContext<ResourceField>): boolean {\n assert(`setting resource relationships is not yet supported`);\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ARRAY_SIGNAL, peekInternalSignal } from '../../../signals/-private';\nimport type { ArrayValue } from '../../../types/json/raw';\nimport type { SchemaArrayField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport type { ManagedArray } from '../fields/managed-array.ts';\n\nexport { getArrayField as getSchemaArrayField } from './array-field';\n\nexport function setSchemaArrayField(context: KindContext<SchemaArrayField>): boolean {\n const arrayValue = context.value === null ? null : (context.value as ArrayValue)?.slice();\n const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1)!);\n const peeked = fieldSignal?.value as ManagedArray | undefined | null;\n\n context.store.cache.setAttr(context.resourceKey, context.path, arrayValue);\n if (peeked) {\n assert(`Expected the peekManagedArray for ${context.field.kind} to return a ManagedArray`, ARRAY_SIGNAL in peeked);\n const arrSignal = peeked[ARRAY_SIGNAL];\n arrSignal.isStale = true;\n\n if (!Array.isArray(arrayValue)) {\n fieldSignal!.value = null;\n }\n }\n\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private';\nimport type { ObjectValue, Value } from '../../../types/json/raw';\nimport type { ObjectSchema, SchemaObjectField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedObjectMap } from '../fields/managed-object';\nimport { ReactiveResource } from '../record';\nimport { Destroy } from '../symbols';\n\ntype MemoizedSchemaObject = {\n type: string;\n identity: string | object;\n value: ReactiveResource;\n};\n\nexport function getSchemaObjectField(context: KindContext<SchemaObjectField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as object;\n\n if (!rawValue && !field.options?.polymorphic && field.options?.defaultValue) {\n rawValue = {};\n }\n\n if (!rawValue) {\n if (signal.value) {\n const value = signal.value as MemoizedSchemaObject;\n // TODO if we had idle scheduling this should be done there.\n void Promise.resolve().then(() => {\n value.value[Destroy]();\n });\n signal.value = null;\n }\n return null;\n }\n\n const { schema } = store;\n let objectType: string;\n\n if (field.options?.polymorphic) {\n const typePath = field.options.type ?? 'type';\n // if we are polymorphic, then context.field.options.type will\n // either specify a path on the rawValue to use as the type, defaulting to \"type\" or\n // the special string \"@hash\" which tells us to treat field.type as a hashFn name with which\n // to calc the type.\n if (typePath === '@hash') {\n assert(`Expected the field to define a hashFn as its type`, field.type);\n const hashFn = schema.hashFn({ type: field.type });\n // TODO consider if there are better options and name args we could provide.\n objectType = hashFn(rawValue, null, null);\n } else {\n objectType = (rawValue as ObjectValue)[typePath] as string;\n assert(\n `Expected the type path for the field to be a value on the raw object`,\n typePath && objectType && typeof objectType === 'string'\n );\n }\n } else {\n assert(`A non-polymorphic SchemaObjectField must provide a SchemaObject type in its definition`, field.type);\n objectType = field.type;\n }\n\n const hashField = (schema.resource({ type: objectType }) as ObjectSchema).identity;\n const identity = hashField\n ? schema.hashFn(hashField)(rawValue, hashField.options ?? null, hashField.name)\n : field.name;\n\n const cachedSchemaObject = signal.value as MemoizedSchemaObject | null;\n if (cachedSchemaObject) {\n if (cachedSchemaObject.type === objectType && cachedSchemaObject.identity === identity) {\n return cachedSchemaObject.value;\n } else {\n // TODO if we had idle scheduling this should be done there.\n void Promise.resolve().then(() => {\n cachedSchemaObject.value[Destroy]();\n });\n }\n }\n\n const schemaObject = new ReactiveResource({\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: context.path,\n field: context.field,\n value: objectType,\n });\n\n signal.value = {\n type: objectType,\n identity: identity,\n value: schemaObject,\n };\n return schemaObject;\n}\n\nexport function setSchemaObjectField(context: KindContext<SchemaObjectField>): boolean {\n const { store, value } = context;\n let newValue = value as Value;\n if (value !== null) {\n assert(`Expected value to be an object`, typeof value === 'object');\n newValue = { ...(value as ObjectValue) };\n // FIXME the case of field.type to string here is likely incorrect\n const schemaFields = store.schema.fields({ type: context.field.type as string });\n for (const key of Object.keys(newValue)) {\n if (!schemaFields.has(key)) {\n assert(`Field ${key} does not exist on schema object ${context.field.type}`);\n return false;\n }\n }\n } else {\n ManagedObjectMap.delete(context.record);\n }\n store.cache.setAttr(context.resourceKey, context.path, newValue);\n // const peeked = peekManagedObject(self, field);\n // if (peeked) {\n // const objSignal = peeked[OBJECT_SIGNAL];\n // objSignal.isStale = true;\n // }\n return true;\n}\n","import type { SignalStore } from '../../signals/-private.ts';\nimport type { Store } from '../../store/-private.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport type {\n FieldSchema,\n HashField,\n IdentityField,\n SchemaArrayField,\n SchemaObjectField,\n} from '../../types/schema/fields.ts';\nimport { getAliasField, setAliasField } from './kind/alias-field.ts';\nimport { getArrayField, setArrayField } from './kind/array-field.ts';\nimport { getAttributeField, setAttributeField } from './kind/attribute-field.ts';\nimport { getBelongsToField, setBelongsToField } from './kind/belongs-to-field.ts';\nimport { getCollectionField, setCollectionField } from './kind/collection-field.ts';\nimport { getDerivedField, setDerivedField } from './kind/derived-field.ts';\nimport { getGenericField, setGenericField } from './kind/generic-field.ts';\nimport { getHasManyField, setHasManyField } from './kind/has-many-field.ts';\nimport { getHashField, setHashField } from './kind/hash-field.ts';\nimport { getIdentityField, setIdentityField } from './kind/identity-field.ts';\nimport { getLocalField, setLocalField } from './kind/local-field.ts';\nimport { getObjectField, setObjectField } from './kind/object-field.ts';\nimport { getResourceField, setResourceField } from './kind/resource-field.ts';\nimport { getSchemaArrayField, setSchemaArrayField } from './kind/schema-array-field.ts';\nimport { getSchemaObjectField, setSchemaObjectField } from './kind/schema-object-field.ts';\nimport type { ReactiveResource } from './record.ts';\n\nexport type PathLike = string | symbol | Array<string | symbol>;\n\nexport type ModeName = 'polaris' | 'legacy';\nexport interface ModeInfo {\n name: ModeName;\n legacy: boolean;\n editable: boolean;\n}\n\nexport interface BaseContext {\n /**\n * The {@link Store} instance that owns\n * the reactive context we are within.\n */\n store: Store;\n /**\n * The {@link ResourceKey} of the resource that\n * the reactive context we are within is for.\n */\n resourceKey: ResourceKey;\n /**\n * The name of the {@link ModeName | mode} that the\n * reactive context we are within is operating in.\n */\n modeName: ModeName;\n /**\n * Whether we are in legacy {@link ModeName | mode}\n * or not.\n */\n legacy: boolean;\n /**\n * Whether the ReactiveResource instance we are operating\n * in is currently editable or not. This should be true if the\n * record is currently checked out for editing or is in legacy mode\n * and false if the record is currently in a read-only state.\n */\n editable: boolean;\n}\n\nexport interface ResourceContext extends BaseContext {\n path: null;\n field: null;\n value: null;\n}\nexport interface ObjectContext extends BaseContext {\n path: string[];\n field: SchemaObjectField | SchemaArrayField;\n value: string;\n}\n\n/**\n * A ReactiveResource context object passed to\n * the get/set functions of a field kind implementation.\n *\n * This provides all the necessary information for\n * the field kind to perform its operations.\n */\nexport interface KindContext<T extends FieldSchema | IdentityField | HashField> extends BaseContext {\n /**\n * The \"cache\" path to the field within the resource.\n *\n * This is the path that should be used to access the\n * field's value in the cache.\n *\n * It differs from the \"ui path\" in that it will be\n * both unaliased and account for source keys.\n */\n path: string[];\n /**\n * The raw schema field definition\n */\n field: T;\n /**\n * The value being set in a set operation. This will be null in a get operation.\n */\n value: unknown;\n /**\n * The object (a ReactiveResource) that the field is being directly accessed on.\n * This is not necessarily the same as the instance that {@link BaseContext.resourceKey | resourceKey}\n * points to, as the field being accessed may be on an embedded schema-object\n * or similar.\n */\n record: ReactiveResource;\n /**\n * The signals object for the record, used to entangle signals for reactivity.\n */\n signals: SignalStore;\n}\n\nexport interface KindImpl<T extends FieldSchema | IdentityField | HashField> {\n /**\n * A function which produces the value for the field when invoked.\n */\n get: (context: KindContext<T>) => unknown;\n /**\n * A function which updates the value for the field when invoked.\n *\n * This will never be invoked when the record is in a non-editable mode.\n *\n * This should assert in dev and return false if mutation is not allowed.\n */\n set: (context: KindContext<T>) => boolean;\n /**\n * Whether this field is ever mutable (writable). This should be\n * if there is ever a scenario in which the field can be written\n * and false only if the field can never be written to.\n */\n mutable: boolean;\n /**\n * Whether this field's of this kind should be included in the\n * enumerated (iterable) keys of the record/object instance.\n *\n * This should generally be true except for fields that are not\n * producing a value backed by the cache. For instance, locals\n * should not be enumerable, as their value is not tied to the\n * cache at all.\n */\n enumerable: boolean;\n /**\n *\n */\n serializable: boolean;\n}\n\ntype Mode = {\n [Field in FieldSchema | IdentityField | HashField as Field['kind']]: KindImpl<Field>;\n};\n\nexport const DefaultMode: Mode = {\n '@hash': {\n get: getHashField,\n set: setHashField,\n mutable: false,\n enumerable: false,\n serializable: false,\n },\n '@id': {\n get: getIdentityField,\n set: setIdentityField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n '@local': {\n get: getLocalField,\n set: setLocalField,\n mutable: true,\n enumerable: false,\n serializable: false,\n },\n alias: {\n get: getAliasField,\n set: setAliasField,\n mutable: true,\n enumerable: true,\n serializable: false,\n },\n array: {\n get: getArrayField,\n set: setArrayField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n attribute: {\n get: getAttributeField,\n set: setAttributeField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n belongsTo: {\n get: getBelongsToField,\n set: setBelongsToField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n collection: {\n get: getCollectionField,\n set: setCollectionField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n derived: {\n get: getDerivedField,\n set: setDerivedField,\n mutable: true,\n enumerable: true,\n serializable: false,\n },\n field: {\n get: getGenericField,\n set: setGenericField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n hasMany: {\n get: getHasManyField,\n set: setHasManyField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n object: {\n get: getObjectField,\n set: setObjectField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n resource: {\n get: getResourceField,\n set: setResourceField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n 'schema-array': {\n get: getSchemaArrayField,\n set: setSchemaArrayField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n 'schema-object': {\n get: getSchemaObjectField,\n set: setSchemaObjectField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n};\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { NotificationType } from '../../index.ts';\nimport {\n ARRAY_SIGNAL,\n entangleSignal,\n notifyInternalSignal,\n OBJECT_SIGNAL,\n Signals,\n withSignalStore,\n} from '../../signals/-private.ts';\nimport type { LegacyManyArray, Store } from '../../store/-private.ts';\nimport { recordIdentifierFor, setRecordIdentifier } from '../../store/-private.ts';\nimport { removeRecordIdentifier } from '../../store/-private/caches/instance-cache.ts';\nimport type { ResourceKey } from '../../types/identifier.ts';\nimport { STRUCTURED } from '../../types/request.ts';\nimport type { FieldSchema, GenericField, IdentityField } from '../../types/schema/fields.ts';\nimport { RecordStore } from '../../types/symbols.ts';\nimport type { ObjectContext, ResourceContext } from './default-mode.ts';\nimport { DefaultMode } from './default-mode.ts';\nimport type { ProxiedMethod } from './fields/extension.ts';\nimport { isExtensionProp, performExtensionSet, performObjectExtensionGet } from './fields/extension.ts';\nimport { getFieldCacheKey } from './fields/get-field-key.ts';\nimport type { ManagedArray } from './fields/managed-array.ts';\nimport { peekManagedObject } from './fields/managed-object.ts';\nimport type { SchemaService } from './schema.ts';\nimport { Checkout, Commit, Context, Destroy } from './symbols.ts';\n\nconst IgnoredGlobalFields = new Set<string>(['length', 'nodeType', 'then', 'setInterval', 'document', STRUCTURED]);\nconst symbolList = [Context, Destroy, RecordStore, Checkout, Commit];\nconst RecordSymbols = new Set(symbolList);\n\ntype RecordSymbol = (typeof symbolList)[number];\n\nfunction isPathMatch(a: string[], b: string[]) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction isNonEnumerableProp(prop: string | number | symbol) {\n return (\n prop === 'constructor' ||\n prop === 'prototype' ||\n prop === '__proto__' ||\n prop === 'toString' ||\n prop === 'toJSON' ||\n prop === 'toHTML' ||\n typeof prop === 'symbol'\n );\n}\n\nconst Editables = new Map<ReactiveResource, ReactiveResource>();\n\nexport interface ReactiveResource {\n /** @internal */\n [Symbol.toStringTag]: `ReactiveResource<${string}>`;\n\n /** @internal */\n [Context]: ObjectContext | ResourceContext;\n\n /** @internal */\n [RecordStore]: Store;\n\n /** @internal */\n ___notifications: object;\n\n /** @internal */\n [Destroy](): void;\n\n /** @internal */\n [Commit](): Promise<void>;\n\n /**\n * Create an editable copy of the record\n *\n * ReactiveResource instances are not editable by default. This method creates an editable copy of the record. To use,\n * import the `Checkout` symbol from `@warp-drive/core/reactive` and call it on the record.\n *\n * ```ts\n * import { Checkout } from '@warp-drive/core/reactive';\n *\n * const record = store.peekRecord('user', '1');\n * const editableRecord = await record[Checkout]();\n * ```\n *\n * @returns a promise that resolves to the editable record\n * @throws if the record is already editable or if the record is embedded\n * @private\n */\n [Checkout]<T>(): Promise<T>;\n}\n\n/**\n * @private\n */\nexport interface PrivateReactiveResource extends ReactiveResource {\n /**\n * @private\n */\n [Context]: ObjectContext | ResourceContext;\n}\n\n/**\n * A class that uses a the ResourceSchema for a ResourceType\n * and a ResourceKey to transform data from the cache into a rich, reactive\n * object.\n *\n * This class is not directly instantiable. To use it, you should\n * configure the store's `instantiateRecord` and `teardownRecord` hooks\n * with the matching hooks provided by this package.\n *\n * @hideconstructor\n * @public\n */\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ReactiveResource {\n constructor(context: ResourceContext | ObjectContext) {\n const resourceKey = context.resourceKey;\n const isEmbedded = context.path !== null;\n const schema = context.store.schema as unknown as SchemaService;\n const objectType = isEmbedded ? context.value : resourceKey.type;\n const ResourceSchema = schema.resource(isEmbedded ? { type: objectType } : resourceKey);\n const identityField = ResourceSchema.identity;\n const BoundFns = new Map<string | symbol, ProxiedMethod>();\n\n // prettier-ignore\n const extensions =\n !context.legacy ? null\n : isEmbedded ? schema.CAUTION_MEGA_DANGER_ZONE_objectExtensions(context.field, objectType)\n : schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(resourceKey);\n\n this[Context] = context;\n this[RecordStore] = context.store;\n\n const fields = isEmbedded ? schema.fields({ type: objectType }) : schema.fields(resourceKey);\n const method = typeof schema.cacheFields === 'function' ? 'cacheFields' : 'fields';\n const cacheFields = isEmbedded ? schema[method]({ type: objectType }) : schema[method](resourceKey);\n\n const signals = withSignalStore(this);\n this.___notifications = context.store.notifications.subscribe(\n resourceKey,\n (_: ResourceKey, type: NotificationType, key?: string | string[]) => {\n switch (type) {\n case 'identity': {\n if (isEmbedded || !identityField) return; // base paths never apply to embedded records\n\n if (identityField.name && identityField.kind === '@id') {\n const signal = signals.get('@identity');\n if (signal) {\n notifyInternalSignal(signal);\n }\n }\n break;\n }\n case 'attributes':\n if (key) {\n if (Array.isArray(key)) {\n if (context.path === null) return; // deep paths will be handled by embedded records\n // TODO we should have the notification manager\n // ensure it is safe for each callback to mutate this array\n if (isPathMatch(context.path, key)) {\n // handle the notification\n // TODO we should likely handle this notification here\n // also we should add a LOGGING flag\n // oxlint-disable-next-line no-console\n console.warn(`Notification unhandled for ${key.join(',')} on ${resourceKey.type}`, proxy);\n return;\n }\n\n // TODO we should add a LOGGING flag\n // console.log(`Deep notification skipped for ${key.join('.')} on ${identifier.type}`, proxy);\n // deep notify the key path\n } else {\n if (isEmbedded) return; // base paths never apply to embedded records\n\n // TODO determine what LOGGING flag to wrap this in if any\n // console.log(`Notification for ${key} on ${identifier.type}`, proxy);\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n const field = cacheFields.get(key);\n if (field?.kind === 'array' || field?.kind === 'schema-array') {\n const peeked = signal?.value as ManagedArray | undefined;\n if (peeked) {\n assert(\n `Expected the peekManagedArray for ${field.kind} to return a ManagedArray`,\n ARRAY_SIGNAL in peeked\n );\n const arrSignal = peeked[ARRAY_SIGNAL];\n notifyInternalSignal(arrSignal);\n }\n }\n if (field?.kind === 'object') {\n const peeked = peekManagedObject(proxy, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n notifyInternalSignal(objSignal);\n }\n }\n }\n }\n break;\n case 'relationships':\n if (key) {\n if (Array.isArray(key)) {\n // FIXME\n } else {\n if (isEmbedded) return; // base paths never apply to embedded records\n\n const field = cacheFields.get(key);\n assert(`Expected relationship ${key} to be the name of a field`, field);\n if (field.kind === 'belongsTo') {\n // TODO determine what LOGGING flag to wrap this in if any\n // console.log(`Notification for ${key} on ${identifier.type}`, proxy);\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n // FIXME\n } else if (field.kind === 'resource') {\n // FIXME\n } else if (field.kind === 'hasMany') {\n if (field.options.linksMode) {\n const signal = signals.get(key);\n if (signal) {\n const peeked = signal.value as LegacyManyArray | undefined;\n if (peeked) {\n notifyInternalSignal(peeked[Context].signal);\n }\n }\n return;\n }\n\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n\n if (schema._kind('@legacy', 'hasMany').notify(context.store, proxy, resourceKey, field)) {\n assert(`Expected options to exist on relationship meta`, field.options);\n assert(`Expected async to exist on relationship meta options`, 'async' in field.options);\n if (field.options.async) {\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n }\n }\n } else if (field.kind === 'collection') {\n // FIXME\n }\n }\n }\n\n break;\n }\n },\n // Each copy subscribes to the channel of the projection it renders and\n // re-pulls that projection when notified. PolarisMode's default immutable\n // instance shows only remote state, so it subscribes 'remote' and is not\n // woken for purely-local changes it can't see. Legacy-mode schemas and any\n // editable instance (including a checked-out PolarisMode copy) show a\n // reconciled local view and so subscribe 'local' (the same as omitting the\n // channel) and are not woken for purely-remote changes (e.g. a push that\n // merely confirms a committed local mutation) that leave their view as-is.\n context.legacy || context.editable ? 'local' : 'remote'\n );\n\n const proxy = new Proxy(this, {\n ownKeys() {\n const identityKey = identityField?.name;\n const keys = Array.from(fields.keys());\n if (identityKey) {\n keys.unshift(identityKey);\n }\n return keys;\n },\n\n has(target: ReactiveResource, prop: string | number | symbol) {\n if (prop === Destroy || prop === Checkout) {\n return true;\n }\n if (prop === identityField?.name) {\n return true;\n }\n return fields.has(prop as string);\n },\n\n getOwnPropertyDescriptor(target, prop) {\n const schemaForField = prop === identityField?.name ? identityField : fields.get(prop as string)!;\n assert(`No field named ${String(prop)} on ${resourceKey.type}`, schemaForField);\n\n if (isNonEnumerableProp(prop)) {\n return {\n writable: false,\n enumerable: false,\n configurable: true,\n };\n }\n\n switch (schemaForField.kind) {\n case 'derived':\n return {\n writable: false,\n enumerable: true,\n configurable: true,\n };\n case '@id':\n return {\n writable: resourceKey.id === null,\n enumerable: true,\n configurable: true,\n };\n case '@hash':\n return schemaForField.name\n ? {\n writable: false,\n enumerable: true,\n configurable: true,\n }\n : {\n writable: false,\n enumerable: false,\n configurable: false,\n };\n case '@local':\n case 'field':\n case 'attribute':\n case 'resource':\n case 'alias':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n case 'schema-array':\n case 'array':\n case 'schema-object':\n case 'object':\n return {\n writable: context.editable,\n enumerable: true,\n configurable: true,\n };\n default:\n return {\n writable: false,\n enumerable: false,\n configurable: false,\n };\n }\n },\n\n get(target: ReactiveResource, prop: string | number | symbol, receiver: typeof Proxy<ReactiveResource>) {\n if (RecordSymbols.has(prop as RecordSymbol)) {\n if (prop === Destroy) {\n return () => _DESTROY(receiver as unknown as ReactiveResource);\n }\n if (prop === Checkout) {\n return () => Promise.resolve(_CHECKOUT(receiver as unknown as ReactiveResource));\n }\n if (prop === Commit) {\n return () => Promise.resolve(_COMMIT(receiver as unknown as ReactiveResource));\n }\n // this Proxy get trap must return raw property values, including methods, unbound\n // oxlint-disable-next-line typescript/unbound-method\n return target[prop as keyof ReactiveResource];\n }\n if (prop === Signals) {\n return signals;\n }\n\n // TODO make this a symbol\n if (prop === '___notifications') {\n return target.___notifications;\n }\n\n // ReactiveResource reserves use of keys that begin with these characters\n // for its own usage.\n // _, @, $, *\n\n const maybeField = prop === identityField?.name ? identityField : fields.get(prop as string);\n if (!maybeField) {\n if (IgnoredGlobalFields.has(prop as string)) {\n return undefined;\n }\n\n /////////////////////////////////////////////////////////////\n //// Note these bound function behaviors are essentially ////\n //// built-in but overrideable derivations. ////\n //// ////\n //// The bar for this has to be \"basic expectations of ////\n /// an object\" – very, very high ////\n /////////////////////////////////////////////////////////////\n\n if (prop === Symbol.toStringTag || prop === 'toString') {\n let fn = BoundFns.get('toString');\n if (!fn) {\n fn = function () {\n entangleSignal(signals, receiver, '@identity', null);\n return `Record<${resourceKey.type}:${resourceKey.id} (${resourceKey.lid})>`;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === 'toHTML') {\n let fn = BoundFns.get('toHTML');\n if (!fn) {\n fn = function () {\n entangleSignal(signals, receiver, '@identity', null);\n return `<span>Record<${resourceKey.type}:${resourceKey.id} (${resourceKey.lid})></span>`;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === 'toJSON') {\n let fn = BoundFns.get('toJSON');\n if (!fn) {\n fn = function () {\n const json: Record<string, unknown> = {};\n for (const key in receiver) {\n // serializing arbitrary property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n json[key] = receiver[key as keyof typeof receiver];\n }\n\n return json;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === Symbol.toPrimitive) return () => null;\n\n if (prop === Symbol.iterator) {\n let fn = BoundFns.get(Symbol.iterator);\n if (!fn) {\n fn = function* () {\n for (const key in receiver) {\n // yielding arbitrary property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n yield [key, receiver[key as keyof typeof receiver]];\n }\n };\n BoundFns.set(Symbol.iterator, fn);\n }\n return fn;\n }\n\n if (prop === 'constructor') {\n return ReactiveResource;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performObjectExtensionGet(receiver, extensions!, signals, prop);\n }\n\n // too many things check for random symbols\n if (typeof prop === 'symbol') return undefined;\n\n assert(`No field named ${String(prop)} on ${context.path ? context.value : resourceKey.type}`);\n return undefined;\n }\n\n const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;\n assert(\n `Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`,\n maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)\n );\n /**\n * Prop Array is the path from a resource to the field including\n * intermediate \"links\" on arrays,objects,schema-arrays and schema-objects.\n *\n * E.g. in the following\n *\n * ```\n * const user = {\n * addresses: [{\n * street: 'Sunset Blvd',\n * zip: 90210\n * }]\n * }\n * ```\n *\n * The propArray for \"street\" is ['addresses', 0, 'street']\n *\n * Prop Array follows the `cache` path to the value, not the ui path.\n * Thus, if `addresses` has a sourceKey of `user_addresses` and\n * `zip` has a sourceKey of `zip_code` then the propArray for \"zip\" is\n * ['user_addresses', 0, 'zip_code']\n */\n const propArray = context.path?.slice() ?? [];\n // we use the field.name instead of prop here because we want to use the cache-path not\n // the record path.\n // SAFETY: we lie as string here because if we were to get null\n // we would be in a field kind that won't use the propArray below.\n const fieldCacheKey = getFieldCacheKey(field) as string;\n propArray.push(fieldCacheKey);\n\n switch (field.kind) {\n case '@id':\n case '@hash':\n case '@local':\n case 'derived':\n case 'field':\n case 'attribute':\n case 'schema-array':\n case 'array':\n case 'schema-object':\n case 'object':\n case 'resource':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n return DefaultMode[field.kind as 'field'].get({\n store: context.store,\n resourceKey: resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: propArray,\n field: field as GenericField,\n record: receiver as unknown as ReactiveResource,\n signals,\n value: null,\n });\n\n default:\n assertNeverField(resourceKey, field, propArray);\n }\n },\n\n set(\n target: ReactiveResource,\n prop: string | number | symbol,\n value: unknown,\n receiver: typeof Proxy<ReactiveResource>\n ) {\n // the only \"editable\" prop as it is currently a proxy for \"isDestroyed\"\n if (prop === '___notifications') {\n target[prop] = value as object;\n return true;\n }\n\n if (!context.editable) {\n assert(\n `Cannot set ${String(prop)} on ${context.path !== null ? context.value : resourceKey.type} because the ReactiveResource is not editable`\n );\n return false;\n }\n\n const maybeField = prop === identityField?.name ? identityField : fields.get(prop as string);\n if (!maybeField) {\n const type = context.path !== null ? context.value : resourceKey.type;\n\n if (isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n assert(`There is no settable field named ${String(prop)} on ${type}`);\n return false;\n }\n const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;\n assert(\n `Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`,\n maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)\n );\n /**\n * Prop Array is the path from a resource to the field including\n * intermediate \"links\" on arrays,objects,schema-arrays and schema-objects.\n *\n * E.g. in the following\n *\n * ```\n * const user = {\n * addresses: [{\n * street: 'Sunset Blvd',\n * zip: 90210\n * }]\n * }\n * ```\n *\n * The propArray for \"street\" is ['addresses', 0, 'street']\n *\n * Prop Array follows the `cache` path to the value, not the ui path.\n * Thus, if `addresses` has a sourceKey of `user_addresses` and\n * `zip` has a sourceKey of `zip_code` then the propArray for \"zip\" is\n * ['user_addresses', 0, 'zip_code']\n */\n const propArray = context.path?.slice() ?? [];\n // we use the field.name instead of prop here because we want to use the cache-path not\n // the record path.\n // SAFETY: we lie as string here because if we were to get null\n // we would be in a field kind that won't use the propArray below.\n const fieldCacheKey = getFieldCacheKey(field) as string;\n propArray.push(fieldCacheKey);\n\n switch (field.kind) {\n case '@id':\n case '@hash':\n case '@local':\n case 'field':\n case 'attribute':\n case 'derived':\n case 'array':\n case 'schema-array':\n case 'schema-object':\n case 'object':\n case 'resource':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n return DefaultMode[field.kind as '@id'].set({\n store: context.store,\n resourceKey: resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: propArray,\n field: field as IdentityField,\n record: receiver as unknown as ReactiveResource,\n signals,\n value,\n });\n\n default:\n return assertNeverField(resourceKey, field, propArray);\n }\n },\n });\n\n if (DEBUG) {\n Object.defineProperty(this, '__SHOW_ME_THE_DATA_(debug mode only)__', {\n enumerable: false,\n configurable: true,\n get() {\n const data: Record<string, unknown> = {};\n for (const key of fields.keys()) {\n // building a debug-only snapshot of raw property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n data[key] = proxy[key as keyof ReactiveResource];\n }\n\n return data;\n },\n });\n }\n\n return proxy;\n }\n}\n\nasync function _COMMIT(record: ReactiveResource): Promise<void> {\n await Promise.resolve();\n const context = record[Context];\n context.store.cache.willCommit(context.resourceKey, null);\n context.store.cache.didCommit(context.resourceKey, null);\n}\n\nexport function _CHECKOUT(record: ReactiveResource): ReactiveResource {\n const context = record[Context];\n\n // IF we are already the editable record, throw an error\n if (context.editable) {\n throw new Error(`Cannot checkout an already editable record`);\n }\n\n const editable = Editables.get(record);\n if (editable) {\n return editable;\n }\n\n if (context.path !== null) {\n throw new Error(`Cannot checkout an embedded record`);\n }\n\n const editableRecord = new ReactiveResource({\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.legacy ? 'legacy' : 'polaris',\n legacy: context.legacy,\n editable: true,\n path: null,\n field: null,\n value: null,\n });\n setRecordIdentifier(editableRecord, recordIdentifierFor(record));\n Editables.set(record, editableRecord);\n return editableRecord;\n}\n\nfunction _DESTROY(record: ReactiveResource): void {\n if (record[Context].legacy) {\n // @ts-expect-error\n record.isDestroying = true;\n // @ts-expect-error\n record.isDestroyed = true;\n } else if (!record[Context].editable) {\n const editable = Editables.get(record);\n if (editable) {\n _DESTROY(editable);\n removeRecordIdentifier(editable);\n }\n }\n\n record[Context].store.notifications.unsubscribe(record.___notifications);\n record.___notifications = null as unknown as object;\n\n // FIXME we need a way to also unsubscribe all SchemaObjects when the primary\n // resource is destroyed.\n}\n\nfunction assertNeverField(identifier: ResourceKey, field: never, path: string | string[]): false {\n assert(\n `Cannot use unknown field kind ${(field as FieldSchema).kind} on <${identifier.type}>.${Array.isArray(path) ? path.join('.') : path}`\n );\n return false;\n}\n\n/**\n * Checkout an immutable resource for editing.\n *\n * {@link ReactiveResource | ReactiveResources} are not editable by default. This method\n * creates an editable copy of the resource.\n *\n * This returns a promise which resolves with the editable\n * version of the resource.\n *\n * ```ts\n * import { checkout } from '@warp-drive/core/reactive';\n *\n * const immutable = store.peekRecord('user', '1');\n * const editable = await checkout(immutable);\n * ```\n *\n * Edits to editable resources will be automatically committed if a new\n * payload from the cache matches their existing value.\n *\n * @public\n *\n * @returns a promise that resolves to the editable resource\n * @throws if the resource is already editable or if resource is an embedded object\n */\nexport function checkout<T>(resource: unknown): Promise<T & ReactiveResource> {\n return (resource as ReactiveResource)[Checkout]();\n}\n\n/**\n * Forcibly commit all local changes on an editable resource to\n * the remote (immutable) version.\n *\n * This API should only be used cautiously. Typically a better\n * approach is for either the API or a Handler to reflect saved\n * changes back to update the cache.\n *\n * @public\n */\nexport function commit(record: ReactiveResource): Promise<void> {\n return record[Commit]();\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../index.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport { isResourceSchema } from '../../types/schema/fields.ts';\nimport { ReactiveResource } from './record.ts';\nimport type { SchemaService } from './schema.ts';\nimport { Destroy } from './symbols.ts';\n\n/**\n * The store's default `instantiateRecord` hook implementation, which\n * produces a {@link ReactiveResource} for `identifier` using the resource\n * schema registered for its type.\n *\n * `createArgs` are only applied (via `Object.assign`) when the resource's\n * schema is `legacy`, matching the historical behavior of assigning initial\n * properties when creating a new legacy record.\n *\n * @public\n */\nexport function instantiateRecord(\n store: Store,\n identifier: ResourceKey,\n createArgs?: Record<string, unknown>\n): ReactiveResource {\n const schema = store.schema as unknown as SchemaService;\n const resourceSchema = schema.resource(identifier);\n assert(`Expected a resource schema`, isResourceSchema(resourceSchema));\n const legacy = resourceSchema?.legacy ?? false;\n const editable = legacy;\n const record = new ReactiveResource({\n store,\n resourceKey: identifier,\n modeName: legacy ? 'legacy' : 'polaris',\n legacy: legacy,\n editable: editable,\n path: null,\n field: null,\n value: null,\n });\n\n if (createArgs && editable) {\n Object.assign(record, createArgs);\n }\n\n return record;\n}\n\nfunction assertReactiveResource(record: unknown): asserts record is ReactiveResource {\n assert('Expected a ReactiveResource', record && typeof record === 'object' && Destroy in record);\n}\n\n/**\n * The store's default `teardownRecord` hook implementation, which asserts\n * that `record` is a {@link ReactiveResource} and invokes its `Destroy`\n * behavior.\n *\n * @public\n */\nexport function teardownRecord(record: unknown): void {\n assertReactiveResource(record);\n record[Destroy]();\n}\n","import { deprecate, warn } from '@ember/debug';\n\nimport { ENFORCE_STRICT_RESOURCE_FINALIZATION } from '@warp-drive/build-config/canary-features';\nimport { DEBUG } from '@warp-drive/build-config/env';\nimport { ENABLE_LEGACY_SCHEMA_SERVICE } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { recordIdentifierFor } from '../../index.ts';\nimport { createInternalMemo, type WarpDriveSignal, withSignalStore } from '../../signals/-private.ts';\nimport type { Store } from '../../store/-private.ts';\nimport type { SchemaService as SchemaServiceInterface } from '../../types.ts';\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport type { ResourceKey } from '../../types/identifier.ts';\nimport type { ObjectValue, Value } from '../../types/json/raw.ts';\nimport type { Derivation, HashFn } from '../../types/schema/concepts.ts';\nimport {\n type ArrayField,\n type CacheableFieldSchema,\n type DerivedField,\n type FieldSchema,\n type GenericField,\n type HashField,\n type IdentityField,\n isResourceSchema,\n type LegacyAttributeField,\n type LegacyBelongsToField,\n type LegacyHasManyField,\n type LegacyRelationshipField,\n type LegacyResourceSchema,\n type LinksModeBelongsToField,\n type LinksModeHasManyField,\n type ObjectField,\n type ObjectSchema,\n type PolarisResourceSchema,\n type ResourceSchema,\n type SchemaArrayField,\n type SchemaObjectField,\n type Trait,\n} from '../../types/schema/fields.ts';\nimport { Type } from '../../types/symbols.ts';\nimport type { WithPartial } from '../../types/utils.ts';\nimport { getFieldCacheKeyStrict, isNonIdentityCacheableField } from './fields/get-field-key.ts';\nimport type { ReactiveResource } from './record.ts';\nimport { Context } from './symbols.ts';\n\nconst Support = getOrSetGlobal('Support', new WeakMap<WeakKey, Record<string, unknown>>());\n\nconst ConstructorField = {\n type: '@constructor',\n name: 'constructor',\n kind: 'derived',\n} satisfies DerivedField;\nconst TypeField = {\n type: '@identity',\n name: '$type',\n kind: 'derived',\n options: { key: 'type' },\n} satisfies DerivedField;\nconst IdentifierField = {\n type: '@identity',\n name: '$key',\n kind: 'derived',\n options: { key: '^' },\n} satisfies DerivedField;\nconst DefaultIdentityField = { name: 'id', kind: '@id' } satisfies IdentityField;\n\nfunction _constructor(record: ReactiveResource) {\n let state = Support.get(record);\n if (!state) {\n state = {};\n Support.set(record, state);\n }\n\n return (state._constructor = state._constructor || {\n name: `ReactiveResource<${recordIdentifierFor(record).type}>`,\n get modelName() {\n assert(`record.constructor.modelName is not available outside of legacy mode`, false);\n return undefined;\n },\n });\n}\n_constructor[Type] = '@constructor';\n\n/**\n * Extensions allow providing non-schema driven behaviors to\n * ReactiveResources, ReactiveArrays, and ReactiveObjects.\n *\n * This should only be used for temporary migration purposes\n * to the new schema system when migrating from either Model\n * or ModelFragments.\n */\nexport interface CAUTION_MEGA_DANGER_ZONE_Extension {\n /**\n * Whether this extension extends the behaviors of objects\n * (both ReactiveObjects and ReactiveResources) or of arrays.\n */\n kind: 'object' | 'array';\n /**\n * The name of the extension, to be used when specifying\n * either `objectExtensions` or `arrayExtensions` on the\n * field, ResourceSchema or ObjectSchema\n */\n name: string;\n /**\n * An object with iterable keys whose values are the getters\n * or methods to expose on the object or array.\n *\n * or\n *\n * A constructable such as a Function or Class whose prototype\n * will be iterated with getOwnPropertyNames.\n *\n * Examples:\n *\n * **An Object with methods**\n *\n * ```ts\n * store.schema.CAUTION_MEGA_DANGER_ZONE_registerExtension({\n * kind: 'object',\n * name: 'do-thing-1',\n * features: {\n * doThingOne(this: { street: string }) {\n * return `do-thing-1:${this.street}`;\n * },\n * doThingTwo(this: { street: string }) {\n * return `do-thing-1:${this.street}`;\n * },\n * },\n * });\n * ```\n *\n * **A class with getters, methods and decorated fields**\n *\n * ```ts\n * class Features {\n * sayHello() {\n * return 'hello!';\n * }\n *\n * @tracked trackedField = 'initial tracked value';\n *\n * get realName() {\n * const self = this as unknown as { name: string };\n * return self.name;\n * }\n * set realName(v: string) {\n * const self = this as unknown as { name: string };\n * self.name = v;\n * }\n *\n * get greeting() {\n * const self = this as unknown as { name: string };\n * return `hello ${self.name}!`;\n * }\n *\n * @computed('name')\n * get salutation() {\n * const self = this as unknown as { name: string };\n * return `salutations ${self.name}!`;\n * }\n *\n * @cached\n * get helloThere() {\n * const self = this as unknown as { name: string };\n * return `Well Hello There ${self.name}!`;\n * }\n * }\n *\n * // non-decorated fields dont appear on class prototypes as they are instance only\n * // @ts-expect-error\n * Features.prototype.untrackedField = 'initial untracked value';\n *\n * store.schema.CAUTION_MEGA_DANGER_ZONE_registerExtension({\n * kind: 'object',\n * name: 'my-ext',\n * features: Features,\n * });\n * ```\n *\n */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n features: Record<string | symbol, unknown> | Function;\n}\n\n/**\n * Describes one feature added to a resource by a schema extension, as\n * classified by {@link processExtension} from the property descriptor it\n * was declared with (a method, a plain value, or a getter/setter pair).\n */\nexport type ExtensionDef =\n | {\n /** A callable feature, installed as a method. */\n kind: 'method';\n /** The function to invoke when the feature is called. */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n fn: Function;\n }\n | {\n /** A plain, non-writable data feature. */\n kind: 'readonly-value';\n /** The value to expose for the feature. */\n value: unknown;\n }\n | {\n /** A plain, writable data feature. */\n kind: 'mutable-value';\n /** The value to expose for the feature. */\n value: unknown;\n }\n | {\n /** An accessor feature with only a getter. */\n kind: 'readonly-field';\n /** Computes the feature's value. */\n get: () => unknown;\n }\n | {\n /** An accessor feature with both a getter and a setter. */\n kind: 'mutable-field';\n /** Computes the feature's value. */\n get: () => unknown;\n /** Assigns the feature's value. */\n set: (value: unknown) => void;\n }\n | {\n /** An accessor feature with only a setter. */\n kind: 'writeonly-field';\n /** Assigns the feature's value. */\n set: (value: unknown) => void;\n };\n\n/**\n * The result of {@link processExtension} normalizing a\n * {@link CAUTION_MEGA_DANGER_ZONE_Extension} into a lookup of its features\n * by name.\n */\nexport interface ProcessedExtension {\n /** Whether this extension applies to objects/resources or to arrays. */\n kind: 'object' | 'array';\n /** The name the extension was registered under. */\n name: string;\n /** Each feature the extension exposes, keyed by its property name. */\n features: Map<string | symbol, ExtensionDef>;\n}\n\nconst BannedKeys = ['constructor', '__proto__'];\n\nfunction processExtension(extension: CAUTION_MEGA_DANGER_ZONE_Extension): ProcessedExtension {\n const { kind, name } = extension;\n const features = new Map<string | symbol, ExtensionDef>();\n const baseFeatures =\n typeof extension.features === 'function'\n ? (extension.features.prototype as Record<string | symbol, unknown>)\n : extension.features;\n for (const key of Object.getOwnPropertyNames(baseFeatures)) {\n if (BannedKeys.includes(key)) continue;\n\n const decl = Object.getOwnPropertyDescriptor(baseFeatures, key);\n assert(`Expected to find a declaration for ${key} on extension ${name}`, decl);\n if (decl.value) {\n const { value } = decl as { value: unknown };\n features.set(\n key,\n typeof value === 'function'\n ? {\n kind: 'method',\n fn: value,\n }\n : decl.writable\n ? {\n kind: 'mutable-value',\n value,\n }\n : {\n kind: 'readonly-value',\n value,\n }\n );\n continue;\n }\n\n if (decl.get || decl.set) {\n const { get, set } = decl as { get?: () => unknown; set?: (v: unknown) => void };\n features.set(\n key,\n // prettier-ignore\n get && set ? { kind: 'mutable-field', get, set }\n : get ? { kind: 'readonly-field', get }\n : { kind: 'writeonly-field', set: set! }\n );\n continue;\n }\n\n assert(`The feature ${key} on extension ${name} is of an unknown variety.`);\n }\n\n return {\n kind,\n name,\n features,\n };\n}\n/**\n * A field (or schema) capable of declaring `objectExtensions` and/or\n * `arrayExtensions` to mix registered {@link CAUTION_MEGA_DANGER_ZONE_Extension}\n * features onto it.\n */\nexport interface ExtensibleField {\n /** The kind of field, only some of which support extensions. */\n kind: 'schema-object' | 'schema-array' | 'array' | 'object' | 'hasMany';\n /** Configures which registered extensions to mix onto this field. */\n options?: {\n /** Names of registered object extensions to mix onto this field. */\n objectExtensions?: string[];\n /** Names of registered array extensions to mix onto this field. */\n arrayExtensions?: string[];\n };\n}\n\nfunction getExt(\n extCache: { object: Map<string | symbol, ProcessedExtension>; array: Map<string | symbol, ProcessedExtension> },\n type: 'array' | 'object',\n extName: string | symbol\n): null | ProcessedExtension['features'] {\n const ext = extCache[type].get(extName);\n assert(`expected to have an extension named ${String(extName)} available for ${type}s`, ext);\n return ext?.features ?? null;\n}\n\nfunction hasObjectSchema(\n field: ObjectSchema | ResourceSchema | SchemaArrayField | SchemaObjectField | ExtensibleField\n): field is SchemaArrayField | SchemaObjectField {\n return 'kind' in field && (field.kind === 'schema-array' || field.kind === 'schema-object');\n}\n\nfunction pretendIsResourceOrObjectSchema(\n field: ObjectSchema | ResourceSchema | ExtensibleField\n): asserts field is ObjectSchema | LegacyResourceSchema {}\n\nfunction processExtensions(\n schema: SchemaService,\n field: ExtensibleField | ObjectSchema | ResourceSchema,\n scenario: 'resource' | 'object' | 'array',\n resolvedType: string | null\n) {\n // if we're looking up extensions for a resource, there is no\n // merging required so if we have no objectExtensions\n // we are done.\n if (scenario === 'resource') {\n pretendIsResourceOrObjectSchema(field);\n if (!('objectExtensions' in field || !field.objectExtensions?.length)) {\n return null;\n }\n }\n\n const type = scenario === 'resource' ? 'object' : scenario;\n const extCache = schema._extensions;\n const fieldCache = schema._cachedFieldExtensionsByField;\n\n if (fieldCache[type].has(field)) {\n return fieldCache[type].get(field)!;\n }\n\n // prettier-ignore\n const extensions =\n (\n scenario === 'resource' ? (field as { objectExtensions?: string[] }).objectExtensions\n : scenario === 'object' ? (field as ExtensibleField).options?.objectExtensions\n : (field as ExtensibleField).options?.arrayExtensions\n ) || null;\n\n // if we are a resource scenario, we know from the first check we do have extensions\n // if we are an object scenario, we can now return the resource scenario.\n // if we are an array scenario, there is nothing more to process.\n if (!extensions) {\n if (scenario === 'array') return null;\n\n if (!hasObjectSchema(field)) {\n return null;\n }\n\n return schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resolvedType ? { type: resolvedType } : (field as { type: string })\n );\n }\n\n // if we have made it here, we have extensions, lets check if there's\n // a cached version we can use\n const baseExtensions =\n scenario === 'resource' && hasObjectSchema(field)\n ? schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(field as { type: string })\n : scenario === 'object' && hasObjectSchema(field)\n ? schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resolvedType ? { type: resolvedType } : (field as { type: string })\n )\n : null;\n\n if (!baseExtensions && extensions.length === 1) {\n const value = getExt(extCache, type, extensions[0]);\n fieldCache[type].set(field, value);\n return value;\n }\n\n const features = new Map<string | symbol, ExtensionDef>(baseExtensions);\n for (const extName of extensions) {\n const value = getExt(extCache, type, extName);\n if (value) {\n for (const [feature, desc] of value) {\n features.set(feature, desc);\n }\n }\n }\n\n const value = features.size ? features : null;\n fieldCache[type].set(field, value);\n\n return value;\n}\n\n/**\n * Utility for constructing a ResourceSchema with the recommended\n * fields for the PolarisMode experience.\n *\n * Using this requires registering the PolarisMode derivations\n *\n * ```ts\n * import { registerDerivations } from '@warp-drive/schema-record';\n *\n * registerDerivations(schema);\n * ```\n *\n * @public\n * @param schema\n * @return {PolarisResourceSchema}\n */\nexport function withDefaults(schema: WithPartial<PolarisResourceSchema, 'identity'>): PolarisResourceSchema {\n schema.identity = schema.identity || DefaultIdentityField;\n\n // because fields gets iterated in definition order,\n // we add TypeField to the beginning so that it will\n // appear right next to the identity field\n schema.fields.unshift(TypeField);\n schema.fields.unshift(IdentifierField);\n schema.fields.push(ConstructorField);\n return schema as PolarisResourceSchema;\n}\n\ninterface FromIdentityDerivation {\n (record: ReactiveResource, options: { key: 'lid' } | { key: 'type' }, key: string): string;\n (record: ReactiveResource, options: { key: 'id' }, key: string): string | null;\n (record: ReactiveResource, options: { key: '^' }, key: string): ResourceKey;\n (record: ReactiveResource, options: null, key: string): asserts options;\n (\n record: ReactiveResource,\n options: { key: 'id' | 'lid' | 'type' | '^' } | null,\n key: string\n ): ResourceKey | string | null;\n [Type]: '@identity';\n}\n\n/**\n * A derivation that computes its value from the\n * record's identity.\n *\n * It can be used via a derived field definition like:\n *\n * ```ts\n * {\n * kind: 'derived',\n * name: 'id',\n * type: '@identity',\n * options: { key: 'id' }\n * }\n * ```\n *\n * Valid keys are `'id'`, `'lid'`, `'type'`, and `'^'`.\n *\n * `^` returns the entire identifier object.\n *\n * @public\n */\nexport const fromIdentity = ((\n record: ReactiveResource,\n options: { key: 'id' | 'lid' | 'type' | '^' } | null,\n key: string\n): ResourceKey | string | null => {\n const context = record[Context];\n const identifier = context.resourceKey;\n assert(`Cannot compute @identity for a record without an identifier`, identifier);\n assert(\n `Expected to receive a key to compute @identity, but got ${String(options)}`,\n options?.key && ['lid', 'id', 'type', '^'].includes(options.key)\n );\n\n return options.key === '^' ? identifier : identifier[options.key];\n}) as unknown as FromIdentityDerivation;\nfromIdentity[Type] = '@identity';\n\n/**\n * Registers the default derivations for records that want\n * to use the PolarisMode defaults provided by\n *\n * ```ts\n * import { withDefaults } from '@warp-drive/schema-record';\n * ```\n *\n * @public\n */\nexport function registerDerivations(schema: SchemaServiceInterface): void {\n schema.registerDerivation(fromIdentity);\n schema.registerDerivation(_constructor);\n}\n\n/**\n * A relationship field capable of declaring `options.as`, marking it as a\n * concrete implementation of an abstract polymorphic type.\n */\ntype AbstractTypeImplementerField =\n | LegacyBelongsToField\n | LegacyHasManyField\n | LinksModeBelongsToField\n | LinksModeHasManyField;\n\n/**\n * A relationship field contributed to an abstract type's schema, along with\n * the name of the type that contributed it (either a concrete implementer,\n * via `options.as`, or the abstract type's own schema), for use in assertion\n * messages when two contributions disagree on shape.\n */\ninterface AbstractFieldContribution {\n field: AbstractTypeImplementerField;\n source: string;\n}\n\n/**\n * Reduces a field to a plain object with a fixed key order, covering every\n * option any relationship-implementer field can declare, so two fields can\n * be compared for exact equality via `JSON.stringify` regardless of the key\n * order the schema author happened to write them in.\n *\n * `options.as` is included and is *not* special-cased: every contributor to\n * a given field name on an abstract type - including the abstract type's\n * own schema, if it has one - is expected to declare `as` equal to that\n * abstract type's own name. This is redundant/self-referential for the\n * abstract type's own schema, but required for consistency: relationship\n * resolution elsewhere (e.g. `inverse` name-matching) does not itself\n * validate `as`, so a field with a missing or incorrect `as` can otherwise\n * be silently pulled into a relationship it never declared it implements.\n */\nfunction comparableAbstractFieldShape(field: FieldSchema): unknown {\n const { kind, name, type, sourceKey, options } = field as {\n kind: string;\n name: string;\n type?: string;\n sourceKey?: string;\n options?: {\n as?: string;\n async?: boolean;\n inverse?: string | null;\n polymorphic?: boolean;\n linksMode?: boolean;\n resetOnRemoteUpdate?: boolean;\n arrayExtensions?: string[];\n };\n };\n return {\n kind,\n name,\n type,\n sourceKey,\n options: {\n as: options?.as,\n async: options?.async,\n inverse: options?.inverse,\n polymorphic: options?.polymorphic,\n linksMode: options?.linksMode,\n resetOnRemoteUpdate: options?.resetOnRemoteUpdate,\n arrayExtensions: options?.arrayExtensions,\n },\n };\n}\n\n/**\n * Asserts that two contributions to the same field name on an abstract\n * polymorphic type - whether from two different concrete implementers, or\n * from an implementer and the abstract type's own schema - declare an\n * identical shape: `kind`, `type`, and every option, including `as` (which\n * every contributor, the abstract type's own schema included, must declare\n * equal to `abstractType`). A mismatch here (e.g. one implementer's field\n * being a `hasMany` while another's is a `belongsTo`, the two disagreeing on\n * `inverse`/`async`/`polymorphic`, or one omitting or misdeclaring `as`)\n * cannot be resolved by picking one side arbitrarily, since that would\n * silently leave whichever side lost the mismatch pointing at a relationship\n * whose true shape differs from what its own schema declared.\n */\nfunction assertConsistentAbstractFieldShape(\n abstractType: string,\n fieldName: string,\n existing: { field: FieldSchema; source: string },\n incoming: { field: FieldSchema; source: string }\n): void {\n // This function exists solely to support the `assert()` call below - there\n // is no other work here with an effect in production. Since `assert()`'s\n // own babel-macro stripping only removes the call expression itself, not\n // the (comparatively expensive, involving `JSON.stringify`) computation of\n // its arguments, guard the whole body so none of it survives in production\n // builds, matching how `assertPolymorphicType`/`assertInheritedSchema` and\n // their call sites are gated in `assert-polymorphic-type.ts`.\n if (DEBUG) {\n const existingShape = comparableAbstractFieldShape(existing.field);\n const incomingShape = comparableAbstractFieldShape(incoming.field);\n assert(\n `Expected the relationship '${fieldName}' on the abstract polymorphic type '${abstractType}' to be declared identically everywhere it is implemented (including 'options.as', which every contributor - the abstract type's own schema included - must declare equal to '${abstractType}'), but '${existing.source}' declares it as:\\n\\n${JSON.stringify(existingShape, null, 2)}\\n\\nwhile '${incoming.source}' declares it as:\\n\\n${JSON.stringify(incomingShape, null, 2)}\\n\\nAll concrete implementers of an abstract type - and the abstract type's own schema, if it has one - must declare an identical shape for any relationship field they share.`,\n JSON.stringify(existingShape) === JSON.stringify(incomingShape)\n );\n }\n}\n\ninterface InternalSchema {\n original: ResourceSchema | ObjectSchema;\n finalized: boolean;\n traits: Set<string>;\n fields: Map<string, FieldSchema>;\n cacheFields: Map<string, Exclude<CacheableFieldSchema, IdentityField>>;\n attributes: Record<string, LegacyAttributeField>;\n relationships: Record<string, LegacyRelationshipField>;\n}\n\n/**\n * Defines how to convert a `GenericField`, `ObjectField`, or `ArrayField`\n * between the raw value `T` stored in the cache and the presentation value\n * `PT` exposed on the record.\n */\nexport type Transformation<T extends Value = Value, PT = unknown> = {\n /** Converts the presentation value into the raw value to store in the cache. */\n serialize(value: PT, options: Record<string, unknown> | null, record: ReactiveResource): T;\n /** Converts the raw cache value into its presentation value. */\n hydrate(value: T | undefined, options: Record<string, unknown> | null, record: ReactiveResource): PT;\n /** Computes the value to use when the cache has no value for the field. */\n defaultValue?(options: Record<string, unknown> | null, identifier: ResourceKey): T;\n /** The name under which this transformation is registered and looked up. */\n [Type]: string;\n};\n\n/**\n * Wraps a derivation in a new function with Derivation signature but that looks\n * up the value in the cache before recomputing.\n *\n * @internal\n */\nfunction makeCachedDerivation<R, T, FM extends ObjectValue | null>(\n derivation: Derivation<R, T, FM>\n): Derivation<R, T, FM> {\n const memoizedDerivation = (record: R, options: FM, prop: string): T => {\n const signals = withSignalStore(record as object);\n let signal = signals.get(prop);\n if (!signal) {\n signal = createInternalMemo(signals, record as object, prop, () => {\n return derivation(record, options, prop);\n }) as unknown as WarpDriveSignal; // a total lie, for convenience of reusing the storage\n }\n\n return (signal as unknown as () => T)();\n };\n memoizedDerivation[Type] = derivation[Type];\n return memoizedDerivation;\n}\n\ninterface KindFns {\n belongsTo: {\n get: (store: Store, record: object, resourceKey: ResourceKey, field: LegacyBelongsToField) => unknown;\n set: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyBelongsToField, value: unknown) => void;\n };\n hasMany: {\n get: (store: Store, record: object, resourceKey: ResourceKey, field: LegacyHasManyField) => unknown;\n set: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyHasManyField, value: unknown) => void;\n notify: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyHasManyField) => boolean;\n };\n}\n\nexport interface SchemaService {\n doesTypeExist(type: string): boolean;\n attributesDefinitionFor(identifier: { type: string }): InternalSchema['attributes'];\n relationshipsDefinitionFor(identifier: { type: string }): InternalSchema['relationships'];\n}\n\ninterface InternalTrait {\n name: string;\n mode: 'legacy' | 'polaris';\n fields: Map<string, FieldSchema>;\n traits: string[];\n}\n\n/**\n * A SchemaService designed to work with dynamically registered schemas.\n *\n * @public\n */\nexport class SchemaService implements SchemaServiceInterface {\n /** @internal */\n declare _schemas: Map<string, InternalSchema>;\n /** @internal */\n declare _transforms: Map<string, Transformation>;\n /** @internal */\n declare _hashFns: Map<string, HashFn>;\n /** @internal */\n // oxlint-disable-next-line typescript/no-explicit-any\n declare _derivations: Map<string, Derivation<any, any, any>>;\n /** @internal */\n declare _traits: Map<string, InternalTrait>;\n /** @internal */\n declare _modes: Map<string, KindFns>;\n /**\n * Tracks, per abstract type, the relationship fields that concrete\n * implementers have contributed via `options.as`, along with the type\n * that contributed each one (for assertion messages). This is\n * independent of whatever schema (synthesized or user-registered)\n * currently occupies `_schemas` for that type, so that these fields\n * survive regardless of the order in which the abstract type's\n * implementers and its own (optional) concrete schema are registered.\n *\n * @internal\n */\n declare _abstractImplementerFields: Map<string, Map<string, AbstractFieldContribution>>;\n /** @internal */\n declare _extensions: {\n object: Map<string, ProcessedExtension>;\n array: Map<string, ProcessedExtension>;\n };\n /** @internal */\n declare _cachedFieldExtensionsByField: {\n object: Map<object, ProcessedExtension['features'] | null>;\n array: Map<object, ProcessedExtension['features'] | null>;\n };\n\n constructor() {\n this._schemas = new Map();\n this._transforms = new Map();\n this._hashFns = new Map();\n this._derivations = new Map();\n this._traits = new Map();\n this._modes = new Map();\n this._abstractImplementerFields = new Map();\n this._extensions = {\n object: new Map(),\n array: new Map(),\n };\n this._cachedFieldExtensionsByField = {\n object: new Map(),\n array: new Map(),\n };\n }\n\n resourceTypes(): Readonly<string[]> {\n return Array.from(this._schemas.keys());\n }\n\n hasTrait(type: string): boolean {\n return this._traits.has(type);\n }\n resourceHasTrait(resource: ResourceKey | { type: string }, trait: string): boolean {\n return this._schemas.get(resource.type)!.traits.has(trait);\n }\n transformation(field: GenericField | ObjectField | ArrayField | { type: string }): Transformation {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `'${kind}' fields cannot be transformed. Only fields of kind 'field' 'object' or 'array' can specify a transformation. Attempted to find '${field.type ?? '<unknown type>'}' on field '${name}'.`,\n !('kind' in field) || ['field', 'object', 'array'].includes(kind)\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a transformation via 'field.type', but none was present`,\n field.type\n );\n assert(\n `No transformation registered with name '${field.type}' for '${kind}' field '${name}'`,\n this._transforms.has(field.type)\n );\n return this._transforms.get(field.type)!;\n }\n derivation(field: DerivedField | { type: string }): Derivation {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `The '${kind}' field '${name}' is not derived and so cannot be used to lookup a derivation`,\n !('kind' in field) || kind === 'derived'\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a derivation via 'field.type', but no value was present`,\n field.type\n );\n assert(\n `No '${field.type}' derivation registered for use by the '${kind}' field '${name}'`,\n this._derivations.has(field.type)\n );\n return this._derivations.get(field.type)!;\n }\n hashFn(field: HashField | { type: string }): HashFn {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `The '${kind}' field '${name}' is not a HashField and so cannot be used to lookup a hash function`,\n !('kind' in field) || kind === '@hash'\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a hash function via 'field.type', but no value was present`,\n field.type\n );\n assert(\n `No '${field.type}' hash function is registered for use by the '${kind}' field '${name}'`,\n this._hashFns.has(field.type)\n );\n return this._hashFns.get(field.type)!;\n }\n resource(resource: ResourceKey | { type: string }): ResourceSchema | ObjectSchema {\n assert(`No resource registered with name '${resource.type}'`, this._schemas.has(resource.type));\n return this._schemas.get(resource.type)!.original;\n }\n registerResources(schemas: Array<ResourceSchema | ObjectSchema>): void {\n schemas.forEach((schema) => {\n this.registerResource(schema);\n });\n }\n registerResource(schema: ResourceSchema | ObjectSchema): void {\n const fields = new Map<string, FieldSchema>();\n const relationships: Record<string, LegacyRelationshipField> = {};\n const attributes: Record<string, LegacyAttributeField> = {};\n const abstractImplementations: AbstractTypeImplementerField[] = [];\n\n for (const field of schema.fields) {\n assert(\n `${field.kind} is not valid inside a ResourceSchema's fields.`,\n // @ts-expect-error we are checking for mistakes at runtime\n field.kind !== '@id' && field.kind !== '@hash'\n );\n fields.set(field.name, field);\n if (field.kind === 'attribute') {\n attributes[field.name] = field;\n } else if (field.kind === 'belongsTo' || field.kind === 'hasMany') {\n relationships[field.name] = field;\n if (field.options?.as) {\n abstractImplementations.push(field);\n }\n }\n }\n\n // This type may already be known as an abstract polymorphic type,\n // implemented by other concrete types via `options.as`, from before it\n // ever had a schema of its own (see `_registerAbstractTypeImplementation`).\n // Carry those previously-contributed fields forward so that registering\n // a \"real\" schema for the type - whenever that happens to occur - never\n // erases the relationships its implementers depend on.\n const implementerFields = this._abstractImplementerFields.get(schema.type);\n if (implementerFields) {\n for (const [name, contribution] of implementerFields) {\n const ownField = fields.get(name);\n if (!ownField) {\n fields.set(name, contribution.field);\n relationships[name] = contribution.field;\n } else if (DEBUG) {\n assertConsistentAbstractFieldShape(schema.type, name, contribution, { field: ownField, source: schema.type });\n }\n }\n }\n\n const cacheFields = null as unknown as Map<string, Exclude<CacheableFieldSchema, IdentityField>>;\n const traits = new Set<string>(isResourceSchema(schema) ? schema.traits : []);\n const finalized = traits.size === 0;\n const internalSchema: InternalSchema = {\n original: schema,\n finalized,\n fields,\n cacheFields,\n relationships,\n attributes,\n traits,\n };\n\n if (traits.size === 0) {\n internalSchema.cacheFields = getCacheFields(internalSchema);\n }\n\n this._schemas.set(schema.type, internalSchema);\n\n // A relationship field's `as` option marks it as a valid concrete\n // implementer of an abstract polymorphic type (e.g. `as: 'commentable'`).\n // That abstract type may never be given its own schema by the user - it\n // may exist only to be implemented by concrete types like this one - or\n // it may already have (or later receive) a schema of its own, e.g. if it\n // turns out to also be a real, directly-resolvable resource. Either way,\n // ensure it has a schema with this field present, so that it behaves\n // like any other registered resource (`hasResource`, `fields`, etc.)\n // instead of requiring special-casing wherever abstract relationship\n // types are resolved.\n for (const field of abstractImplementations) {\n this._registerAbstractTypeImplementation(field, schema.type);\n }\n }\n\n /** @internal */\n private _registerAbstractTypeImplementation(field: AbstractTypeImplementerField, implementer: string): void {\n const abstractType = field.options.as!;\n\n let implementerFields = this._abstractImplementerFields.get(abstractType);\n if (!implementerFields) {\n implementerFields = new Map();\n this._abstractImplementerFields.set(abstractType, implementerFields);\n }\n\n // Unlike the original approach this replaced, `as` is *not* stripped here:\n // the field as synthesized onto the abstract type's own schema keeps\n // `options.as === abstractType`, redundant/self-referential as that is.\n // This keeps every contributor - implementers and the abstract type's\n // own schema alike - declaring the same thing, which is what\n // `assertConsistentAbstractFieldShape` checks, and it is also what lets\n // `assertPolymorphicType` (which reads a field's declared `as` off\n // whatever `schema.fields()` serves for its type) correctly permit the\n // abstract type itself to be pushed directly into this relationship.\n const abstractField = { ...field };\n const contribution: AbstractFieldContribution = { field: abstractField, source: implementer };\n\n // all concrete implementations of an abstract type are required to\n // share the same shape for the field that implements it, so the first\n // one registered is as good a canonical source as any - but a later,\n // differently-shaped one is almost certainly a mistake rather than an\n // intentional override, so we catch it rather than silently ignoring it.\n const existingImplementer = implementerFields.get(field.name);\n if (existingImplementer) {\n if (DEBUG) {\n assertConsistentAbstractFieldShape(abstractType, field.name, existingImplementer, contribution);\n }\n return;\n }\n implementerFields.set(field.name, contribution);\n\n let abstractSchema = this._schemas.get(abstractType);\n if (!abstractSchema) {\n abstractSchema = {\n original: {\n legacy: true,\n identity: { kind: '@id', name: 'id' },\n type: abstractType,\n fields: [],\n },\n finalized: true,\n fields: new Map(),\n cacheFields: new Map(),\n relationships: {},\n attributes: {},\n traits: new Set(),\n };\n this._schemas.set(abstractType, abstractSchema);\n }\n\n const existingAbstractField = abstractSchema.fields.get(field.name);\n if (existingAbstractField) {\n if (DEBUG) {\n assertConsistentAbstractFieldShape(\n abstractType,\n field.name,\n { field: existingAbstractField, source: abstractType },\n contribution\n );\n }\n return;\n }\n\n abstractSchema.fields.set(field.name, abstractField);\n abstractSchema.relationships[field.name] = abstractField;\n\n // If the schema is mid-finalization (traits pending), finalizeResource\n // will recompute cacheFields from the current `fields` map anyway; avoid\n // doing so prematurely from a partially-resolved set of fields.\n if (abstractSchema.finalized) {\n abstractSchema.cacheFields = getCacheFields(abstractSchema);\n }\n }\n\n /**\n * Registers a {@link Trait} for use by resource schemas.\n *\n * Traits are re-usable collections of fields that can be composed to\n * build up a resource schema. Often they represent polymorphic behaviors\n * a resource should exhibit.\n *\n * When we finalize a resource, we walk its traits and apply their fields\n * to the resource's fields. All specified traits must be registered by\n * this time or an error will be thrown.\n *\n * Traits are applied left-to-right, with traits of traits being applied in the same\n * way. Thus for the most part, application of traits is a post-order graph traversal\n * problem.\n *\n * A trait is only ever processed once. If multiple traits (A, B, C) have the same\n * trait (D) as a dependency, D will be included only once when first encountered by\n * A.\n *\n * If a cycle exists such that trait A has trait B which has Trait A, trait A will\n * be applied *after* trait B in production. In development a cycle error will be thrown.\n *\n * Fields are finalized on a \"last wins principle\". Thus traits appearing higher in\n * the tree and further to the right of a traits array take precedence, with the\n * resource's fields always being applied last and winning out.\n *\n * @public\n */\n registerTrait(trait: Trait): void {\n const internalTrait = Object.assign({}, trait, { fields: new Map() }) as InternalTrait;\n for (const field of trait.fields) {\n internalTrait.fields.set(field.name, field);\n }\n this._traits.set(trait.name, internalTrait);\n }\n\n registerTransformation<T extends Value = string, PT = unknown>(transformation: Transformation<T, PT>): void {\n this._transforms.set(transformation[Type], transformation);\n }\n\n registerDerivation<R, T, FM extends ObjectValue | null>(derivation: Derivation<R, T, FM>): void {\n this._derivations.set(derivation[Type], makeCachedDerivation(derivation));\n }\n\n CAUTION_MEGA_DANGER_ZONE_registerExtension(extension: CAUTION_MEGA_DANGER_ZONE_Extension): void {\n assert(\n `an extension named ${extension.name} for ${extension.kind} already exists!`,\n !this._extensions[extension.kind].has(extension.name)\n );\n this._extensions[extension.kind].set(extension.name, processExtension(extension));\n }\n\n CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resource: ResourceKey | { type: string }\n ): null | ProcessedExtension['features'] {\n const schema = this.resource(resource);\n return processExtensions(this, schema, 'resource', null);\n }\n\n CAUTION_MEGA_DANGER_ZONE_objectExtensions(\n field: ExtensibleField,\n resolvedType: string | null\n ): null | ProcessedExtension['features'] {\n return processExtensions(this, field, 'object', resolvedType);\n }\n\n CAUTION_MEGA_DANGER_ZONE_arrayExtensions(field: ExtensibleField): null | ProcessedExtension['features'] {\n return processExtensions(this, field, 'array', null);\n }\n\n CAUTION_MEGA_DANGER_ZONE_hasExtension(ext: { kind: 'object' | 'array'; name: string }): boolean {\n return this._extensions[ext.kind].has(ext.name);\n }\n\n /**\n * This is an internal method used to register behaviors for legacy mode.\n * It is not intended for public use.\n *\n * We do think a generalized `kind` registration system would be useful,\n * but we have not yet designed it.\n *\n * See https://github.com/warp-drive-data/warp-drive/issues/9534\n *\n * @internal\n */\n _registerMode(mode: string, kinds: KindFns): void {\n assert(`Mode '${mode}' is already registered`, !this._modes.has(mode));\n this._modes.set(mode, kinds);\n }\n\n /**\n * This is an internal method used to enable legacy behaviors for legacy mode.\n * It is not intended for public use.\n *\n * We do think a generalized `kind` registration system would be useful,\n * but we have not yet designed it.\n *\n * See https://github.com/warp-drive-data/warp-drive/issues/9534\n *\n * @internal\n */\n _kind<T extends keyof KindFns>(mode: string, kind: T): KindFns[T] {\n assert(`Mode '${mode}' is not registered`, this._modes.has(mode));\n const kinds = this._modes.get(mode)!;\n assert(`Kind '${kind}' is not registered for mode '${mode}'`, kinds[kind]);\n return kinds[kind];\n }\n\n /**\n * Registers a {@link HashFn} for use with a {@link HashField} for\n * either {@link ObjectSchema} identity or polymorphic type calculation.\n *\n * @public\n */\n registerHashFn<T extends object>(hashFn: HashFn<T>): void {\n this._hashFns.set(hashFn[Type], hashFn as HashFn);\n }\n\n fields({ type }: { type: string }): InternalSchema['fields'] {\n const schema = this._schemas.get(type);\n assert(`No schema defined for ${type}`, schema);\n\n if (!schema.finalized) {\n finalizeResource(this, schema);\n }\n\n return schema.fields;\n }\n\n cacheFields({ type }: { type: string }): InternalSchema['cacheFields'] {\n const schema = this._schemas.get(type);\n assert(`No schema defined for ${type}`, schema);\n\n if (!schema.finalized) {\n finalizeResource(this, schema);\n }\n\n return schema.cacheFields;\n }\n\n hasResource(resource: { type: string }): boolean {\n return this._schemas.has(resource.type);\n }\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n SchemaService.prototype.attributesDefinitionFor = function ({\n type,\n }: {\n type: string;\n }): InternalSchema['attributes'] {\n deprecate(`Use \\`schema.fields({ type })\\` instead of \\`schema.attributesDefinitionFor({ type })\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n const schema = this._schemas.get(type);\n\n if (!schema) {\n throw new Error(`No schema defined for ${type}`);\n }\n\n return schema.attributes;\n };\n\n SchemaService.prototype.relationshipsDefinitionFor = function ({\n type,\n }: {\n type: string;\n }): InternalSchema['relationships'] {\n deprecate(`Use \\`schema.fields({ type })\\` instead of \\`schema.relationshipsDefinitionFor({ type })\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n const schema = this._schemas.get(type);\n\n if (!schema) {\n throw new Error(`No schema defined for ${type}`);\n }\n\n return schema.relationships;\n };\n\n SchemaService.prototype.doesTypeExist = function (type: string): boolean {\n deprecate(`Use \\`schema.hasResource({ type })\\` instead of \\`schema.doesTypeExist(type)\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n return this._schemas.has(type);\n };\n}\n\n/**\n * When we finalize a resource, we walk its traits and apply their fields\n * to the resource's fields.\n *\n * Traits are applied left-to-right, with traits of traits being applied in the same\n * way. Thus for the most part, application of traits is a post-order graph traversal\n * problem.\n *\n * A trait is only ever processed once. If multiple traits (A, B, C) have the same\n * trait (D) as a dependency, D will be included only once when first encountered by\n * A.\n *\n * If a cycle exists such that trait A has trait B which has Trait A, trait A will\n * be applied *after* trait B in production. In development a cycle error will be thrown.\n *\n * Fields are finalized on a \"last wins principle\". Thus traits appearing higher in\n * the tree and further to the right of a traits array take precedence, with the\n * resource's fields always being applied last and winning out.\n */\nfunction finalizeResource(schema: SchemaService, resource: InternalSchema): void {\n const fields: Map<string, FieldSchema> = new Map();\n const seen: Set<InternalTrait> = new Set();\n\n for (const traitName of resource.traits) {\n const trait = schema._traits.get(traitName);\n assert(\n `The trait ${traitName} MUST be supplied before the resource ${resource.original.type} can be finalized for use.`,\n trait\n );\n\n walkTrait(schema, trait, fields, seen, resource.original.type, DEBUG ? [] : null);\n }\n\n mergeMap(fields, resource.fields);\n resource.fields = fields;\n resource.cacheFields = getCacheFields(resource);\n resource.finalized = true;\n}\n\nfunction getCacheFields(resource: InternalSchema) {\n const { fields } = resource;\n const cacheFields = new Map<string, Exclude<CacheableFieldSchema, IdentityField>>();\n for (const [key, value] of fields) {\n if (isNonIdentityCacheableField(value)) {\n assert(\n `The sourceKey '${value.sourceKey}' for the field '${key}' on ${resource.original.type} is invalid because it matches the name of an existing field`,\n !value.sourceKey || value.sourceKey === key || !fields.has(value.sourceKey)\n );\n const cacheKey = getFieldCacheKeyStrict(value);\n cacheFields.set(cacheKey, value);\n }\n }\n return cacheFields;\n}\n\nfunction walkTrait(\n schema: SchemaService,\n trait: InternalTrait,\n fields: Map<string, FieldSchema>,\n seen: Set<InternalTrait>,\n type: string,\n debugPath: string[] | null\n): void {\n if (seen.has(trait)) {\n // if the trait is in the current path, we throw a cycle error in dev.\n if (DEBUG) {\n if (debugPath!.includes(trait.name)) {\n throw new Error(\n `CycleError: The Trait '${trait.name}' utilized by the Resource '${type}' includes the following circular reference \"${debugPath!.join(' > ')} > ${trait.name}\"`\n );\n }\n }\n return;\n }\n const ownPath = DEBUG ? [...debugPath!, trait.name] : null;\n\n // immediately mark as seen to prevent cycles\n // further down the tree from looping back\n seen.add(trait);\n\n // first apply any child traits\n if (trait.traits?.length) {\n for (const traitName of trait.traits) {\n const subtrait = schema._traits.get(traitName);\n if (ENFORCE_STRICT_RESOURCE_FINALIZATION) {\n assert(\n `The trait ${traitName} used by the trait ${trait.name} MUST be supplied before the resource ${type} can be finalized for use.`,\n subtrait\n );\n } else {\n warn(\n `The trait ${traitName} used by the trait ${trait.name} MUST be supplied before the resource ${type} can be finalized for use.`,\n !!subtrait,\n {\n id: 'warp-drive:missing-trait-schema-for-resource',\n }\n );\n }\n if (!subtrait) continue;\n walkTrait(schema, subtrait, fields, seen, type, ownPath);\n }\n }\n\n // then apply our own fields\n mergeMap(fields, trait.fields);\n}\n\nfunction mergeMap(base: Map<string, unknown>, toApply: Map<string, unknown>) {\n for (const [key, value] of toApply) {\n base.set(key, value);\n }\n}\n","/**\n * # About\n *\n * This module provides an implementation of reactive objects that a Store may use for creating\n * reactive representations of the raw data for requests, resources and their relationships\n * stored in the cache.\n *\n * - For configuring the store to use these reactive objects, see [The Setup Guide](/guides/configuration/)\n * - For defining resource schemas, see [The Schema Guide](/guides/the-manual/schemas/)\n *\n * Any method that returns a record instance will use the `instantiateRecord`\n * hook configured above to instantiate a ReactiveResource once this is in place.\n * After that, its up to you what ReactiveResource can do.\n *\n * ## Modes\n *\n * ReactiveResource has two modes: `legacy` and `polaris`.\n *\n * **LegacyMode** can be used to emulate the behaviors and capabilities of WarpDrive's `Model` class,\n * and because there is little distinction between Model and a ReactiveResource in LegacyMode we refer\n * to both of these approaches as LegacyMode. This mode is the default experience in V5.\n *\n * In LegacyMode:\n *\n * - records are mutable\n * - local changes immediately reflect app wide\n * - records have all the APIs of Model (references, state props, currentState, methods etc)\n * - the continued use of `@warp-drive/legacy` is required (though most imports from it can be removed)\n * - `async: true` relationships are supported (but not recommended outside of [LinksMode](/guides/the-manual/misc/links-mode.md))\n *\n * ---\n *\n * **PolarisMode** is an upcoming suite of features that will become the default experience in V6.\n *\n * In PolarisMode:\n *\n * - records are immutable, unless creating a new resource or explicitly checking out a record for editing\n * - local changes are isolated until committed, displaying only via the editable version of the record\n * - records have a more limited API, focused on only what is in their schema.\n * - some common operations may have more friction to perform because intended utilities are not yet available\n * - `async: true` relationships are not supported (see [LinksMode](/guides/the-manual/misc/links-mode.md))\n * - The `@warp-drive/legacy` package is not required\n *\n * These modes are interopable. The reactive object (record) for a resource in PolarisMode can relate to\n * a record in LegacyMode and vice-versa. This interopability is true whether the record in LegacyMode is\n * a ReactiveResource or a Model.\n *\n * ---\n *\n * ## Basic Usage\n *\n * ReactiveResource is a reactive object that transforms raw data from an associated\n * cache into reactive data backed by Signals.\n *\n * The shape of the object and the transformation of raw cache data into its\n * reactive form is controlled by a resource schema.\n *\n * For instance, lets say your API is a [{json:api}](https://jsonapi.org) and your store is using\n * the Cache provided by {@link @warp-drive/json-api! | @warp-drive/json-api}, and a request\n * returns the following raw data:\n *\n * ```ts\n * {\n * data: {\n * type: 'user',\n * id: '1',\n * attributes: { firstName: 'Chris', lastName: 'Thoburn' },\n * relationships: { pets: { data: [{ type: 'dog', id: '1' }] }}\n * },\n * included: [\n * {\n * type: 'dog',\n * id: '1',\n * attributes: { name: 'Rey' },\n * relationships: { owner: { data: { type: 'user', id: '1' }}}\n * }\n * ]\n * }\n * ```\n *\n * We could describe the `'user'` and `'dog'` resources in the above payload\n * with the following schemas:\n *\n * ```ts\n * store.schema.registerResources([\n * {\n * type: 'user',\n * identity: { type: '@id', name: 'id' },\n * fields: [\n * {\n * type: '@identity',\n * name: '$type',\n * kind: 'derived',\n * options: { key: 'type' },\n * },\n * { kind: 'field', name: 'firstName' },\n * { kind: 'field', name: 'lastName' },\n * {\n * kind: 'derived',\n * name: 'name',\n * type: 'concat',\n * options: { fields: ['firstName', 'lastName'], separator: ' ' }\n * },\n * {\n * kind: 'hasMany',\n * name: 'pets',\n * type: 'pet',\n * options: {\n * async: false,\n * inverse: 'owner',\n * polymorphic: true,\n * linksMode: true,\n * }\n * }\n * ]\n * },\n * {\n * type: 'dog',\n * identity: { type: '@id', name: 'id' },\n * fields: [\n * {\n * type: '@identity',\n * name: '$type',\n * kind: 'derived',\n * options: { key: 'type' },\n * },\n * { kind: 'field', name: 'name' },\n * {\n * kind: 'belongsTo',\n * name: 'owner',\n * type: 'user',\n * options: {\n * async: false,\n * inverse: 'pets',\n * as: 'pet',\n * linksMode: true,\n * }\n * }\n * ]\n * }\n * ]);\n * ```\n *\n * With these schemas in place, the reactive objects that the store would\n * provide us whenever we encountered a `'user'` or a `'dog'` would be:\n *\n * ```ts\n * interface Pet {\n * readonly id: string;\n * readonly owner: User;\n * }\n *\n * interface Dog extends Pet {\n * readonly $type: 'dog';\n * readonly name: string;\n * }\n *\n * interface EditableUser {\n * readonly $type: 'user';\n * readonly id: string;\n * firstName: string;\n * lastName: string;\n * readonly name: string;\n * pets: Array<Dog | Pet>;\n * }\n *\n * interface User {\n * readonly $type: 'user';\n * readonly id: string;\n * readonly firstName: string;\n * readonly lastName: string;\n * readonly name: string;\n * readonly pets: Readonly<Array<Dog | Pet>>;\n * [Checkout](): Promise<EditableUser>\n * }>\n * ```\n *\n * Note how based on the schema the reactive object we receive is able to produce\n * `name` on user (despite no name field being in the cache), provide `$type`\n * pulled from the identity of the resource, and flatten the individual attributes\n * and relationships onto the record for easier use.\n *\n * Notice also how we typed this object with `readonly`. This is because while\n * ReactiveResource instances are ***deeply reactive***, they are also ***immutable***.\n *\n * We can mutate a ReactiveResource only be explicitly asking permission to do so, and\n * in the process gaining access to an editable copy. The immutable version will\n * not show any in-process edits made to this editable copy.\n *\n * ```ts\n * import { Checkout } from '@warp-drive/schema-record';\n *\n * const editable = await user[Checkout]();\n * ```\n *\n * ## Utilities\n *\n * ReactiveResource provides a schema builder that simplifies setting up a couple of\n * conventional fields like identity and `$type`. We can rewrite the schema\n * definition above using this utility like so:\n *\n * ```ts\n * import { withDefaults } from '@warp-drive/core/reactive';\n *\n * store.schema.registerResources([\n * withDefaults({\n * type: 'user',\n * fields: [\n * { kind: 'field', name: 'firstName' },\n * { kind: 'field', name: 'lastName' },\n * {\n * kind: 'derived',\n * name: 'name',\n * type: 'concat',\n * options: { fields: ['firstName', 'lastName'], separator: ' ' }\n * },\n * {\n * kind: 'hasMany',\n * name: 'pets',\n * type: 'pet',\n * options: {\n * async: false,\n * inverse: 'owner',\n * polymorphic: true,\n * linksMode: true,\n * resetOnRemoteUpdate: false,\n * }\n * }\n * ]\n * }),\n * withDefaults({\n * type: 'dog',\n * fields: [\n * { kind: 'field', name: 'name' },\n * {\n * kind: 'belongsTo',\n * name: 'owner',\n * type: 'user',\n * options: {\n * async: false,\n * inverse: 'pets',\n * as: 'pet',\n * linksMode: true,\n * resetOnRemoteUpdate: false,\n * }\n * }\n * ]\n * })\n * ]);\n * ```\n *\n * ## Type Support\n *\n * ### Resource Schemas\n *\n * - {@link PolarisResourceSchema}\n * - {@link LegacyResourceSchema}\n * - {@link ObjectSchema}\n *\n * ### Resource Schema Type Utils\n *\n * - {@link resourceSchema}\n * - {@link objectSchema}\n * - {@link isResourceSchema}\n * - {@link isLegacyResourceSchema}\n *\n * ### Field Schemas\n *\n * - {@link LegacyModeFieldSchema}\n * - {@link PolarisModeFieldSchema}\n *\n * @module\n */\nimport { checkout } from './reactive/-private/record.ts';\nimport type {\n // oxlint-disable-next-line no-unused-vars\n isLegacyResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n isResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n LegacyModeFieldSchema,\n // oxlint-disable-next-line no-unused-vars\n LegacyResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n ObjectSchema,\n // oxlint-disable-next-line no-unused-vars\n objectSchema,\n // oxlint-disable-next-line no-unused-vars\n PolarisModeFieldSchema,\n // oxlint-disable-next-line no-unused-vars\n PolarisResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n resourceSchema,\n} from './types/schema/fields';\n\nexport { instantiateRecord, teardownRecord } from './reactive/-private/hooks';\nexport {\n type CAUTION_MEGA_DANGER_ZONE_Extension,\n type ProcessedExtension,\n type ExtensionDef,\n type Transformation,\n SchemaService,\n withDefaults,\n fromIdentity,\n registerDerivations,\n} from './reactive/-private/schema';\nexport { commit, type ReactiveResource } from './reactive/-private/record.ts';\n\nexport { checkout };\nexport {\n /** @deprecated use {@link checkout} */\n Checkout,\n} from './reactive/-private/symbols';\nexport {\n type ReactiveDocument,\n type ReactiveDataDocument,\n type ReactiveErrorDocument,\n} from './reactive/-private/document';\nexport {\n createRequestSubscription,\n getRequestState,\n type RequestSubscription,\n type RequestLoadingState,\n type RequestState,\n} from './signals/-private';\n\nexport {\n getPromiseState,\n type PromiseState,\n type ResolvedPromise,\n type RejectedPromise,\n type PendingPromise,\n} from './signals/-private.ts';\n\nexport type { LegacyLiveArray } from './store/-private/record-arrays/legacy-live-array.ts';\nexport type { LegacyManyArray } from './store/-private/record-arrays/legacy-many-array.ts';\nexport type { LegacyQueryArray } from './store/-private/record-arrays/legacy-query.ts';\nexport type { ReactiveResourceArray } from './store/-private/record-arrays/resource-array.ts';\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { getRuntimeConfig } from '../../types/runtime.ts';\nimport { cloneResponseProperties, type Context } from './context';\nimport { DOMError, type FetchError } from './utils';\n\nexport type { FetchError };\n\ninterface FastbootRequest extends Request {\n protocol: string;\n host: string;\n}\nexport interface FastBoot {\n require(moduleName: string): unknown;\n isFastBoot: boolean;\n request: FastbootRequest;\n}\n\n// Lazily close over fetch to avoid breaking Mirage\nconst _fetch: typeof fetch =\n typeof fetch !== 'undefined'\n ? (...args) => fetch(...args)\n : typeof FastBoot !== 'undefined'\n ? (...args) => ((FastBoot as FastBoot).require('node-fetch') as typeof fetch)(...args)\n : () => {\n throw new Error('No Fetch Implementation Found');\n };\n\n// clones a response in a way that should still\n// allow it to stream\nfunction cloneResponse(response: Response, overrides: Partial<Response>) {\n const props = cloneResponseProperties(response);\n return new Response(response.body, Object.assign(props, overrides));\n}\n\nfunction withDateHeader(response: Response): Response {\n const headers = new Headers(response.headers);\n headers.set('date', new Date().toUTCString());\n return cloneResponse(response, { headers });\n}\n\n// Detects Mirage (or another Pretender-based fetch mock), whose `Response`\n// may (unlike a spec-compliant `fetch()`, whose Response headers are always\n// immutable) allow header mutation and may not support streaming reads.\n//\n// This is inherently a heuristic - many legitimate tools (APM/monitoring\n// agents, browser extensions, polyfills) also patch `window.fetch`, and can\n// produce false positives. `setWarpDriveIsMaybeMirage(value)` lets an app\n// declare the answer explicitly (`true` or `false`), overriding the\n// heuristic in either direction; leave it unset to keep the default\n// detection. See https://github.com/warp-drive-data/warp-drive/issues/10535\nlet IS_MAYBE_MIRAGE = () => false;\nif (DEBUG) {\n IS_MAYBE_MIRAGE = () => {\n const override = getRuntimeConfig().mirage;\n if (override !== undefined) {\n return override;\n }\n return Boolean(\n typeof window !== 'undefined' &&\n ((window as { server?: { pretender: unknown } }).server?.pretender ||\n window.fetch.toString().replace(/\\s+/g, '') !== 'function fetch() { [native code] }'.replace(/\\s+/g, ''))\n );\n };\n}\n\nconst MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);\nconst ERROR_STATUS_CODE_FOR = new Map([\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [402, 'Payment Required'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [405, 'Method Not Allowed'],\n [406, 'Not Acceptable'],\n [407, 'Proxy Authentication Required'],\n [408, 'Request Timeout'],\n [409, 'Conflict'],\n [410, 'Gone'],\n [411, 'Length Required'],\n [412, 'Precondition Failed'],\n [413, 'Payload Too Large'],\n [414, 'URI Too Long'],\n [415, 'Unsupported Media Type'],\n [416, 'Range Not Satisfiable'],\n [417, 'Expectation Failed'],\n [419, 'Page Expired'],\n [420, 'Enhance Your Calm'],\n [421, 'Misdirected Request'],\n [422, 'Unprocessable Entity'],\n [423, 'Locked'],\n [424, 'Failed Dependency'],\n [425, 'Too Early'],\n [426, 'Upgrade Required'],\n [428, 'Precondition Required'],\n [429, 'Too Many Requests'],\n [430, 'Request Header Fields Too Large'],\n [431, 'Request Header Fields Too Large'],\n [450, 'Blocked By Windows Parental Controls'],\n [451, 'Unavailable For Legal Reasons'],\n [500, 'Internal Server Error'],\n [501, 'Not Implemented'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n [505, 'HTTP Version Not Supported'],\n [506, 'Variant Also Negotiates'],\n [507, 'Insufficient Storage'],\n [508, 'Loop Detected'],\n [509, 'Bandwidth Limit Exceeded'],\n [510, 'Not Extended'],\n [511, 'Network Authentication Required'],\n]);\n\n/**\n * ```ts\n * import { Fetch } from '@warp-drive/core';\n * ```\n *\n * A basic Fetch Handler which converts a request into a\n * `fetch` call presuming the response to be `json`.\n *\n * ```ts\n * import { RequestManager, Fetch } from '@warp-drive/core';\n *\n * const manager = new RequestManager()\n * .use([Fetch]);\n * ```\n *\n * @public\n * @badge Handler\n */\nconst Fetch = {\n /**\n * Issues the request via native `fetch`, setting the response and\n * (when requested) streaming the decoded body via {@link Context.setStream}\n * as it downloads, then resolves with the parsed JSON body.\n *\n * @public\n */\n async request<T>(context: Context): Promise<T> {\n let response: Response;\n\n try {\n assert(\n 'The Fetch handler expects the request to have a URL, none was provided.',\n context.request.url && typeof context.request.url === 'string'\n );\n response = await _fetch(context.request.url, context.request);\n } catch (e) {\n const isDOMException = e instanceof DOMError;\n if (isDOMException && e.name === 'AbortError') {\n (e as FetchError).statusText = 'Aborted';\n (e as FetchError).status = 20;\n (e as FetchError).isRequestError = true;\n } else {\n (e as FetchError).statusText = 'Unknown Network Error';\n (e as FetchError).status = 0;\n if (!isDOMException) {\n (e as FetchError).code = 0;\n }\n (e as FetchError).isRequestError = true;\n }\n throw e;\n }\n\n const isError = !response.ok || response.status >= 400;\n const op = context.request.op;\n const isMutationOp = Boolean(op && MUTATION_OPS.has(op));\n\n if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {\n if (IS_MAYBE_MIRAGE()) {\n try {\n response.headers.set('date', new Date().toUTCString());\n } catch {\n // IS_MAYBE_MIRAGE() was a false positive, or the mock's headers\n // are (correctly) immutable - fall back to cloning.\n response = withDateHeader(response);\n }\n } else {\n response = withDateHeader(response);\n }\n }\n\n context.setResponse(response);\n\n if (response.status === 204 || context.request.method === 'HEAD') {\n return null as T;\n }\n\n let text = '';\n // if we are in a mirage context, we cannot support streaming\n if (IS_MAYBE_MIRAGE()) {\n text = await response.text();\n } else {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let isStreaming = context.hasRequestedStream;\n let stream: TransformStream | null = isStreaming ? new TransformStream() : null;\n let writer = stream?.writable.getWriter();\n\n if (isStreaming) {\n // Listen for the abort event on the AbortSignal\n context.request.signal?.addEventListener('abort', () => {\n if (!isStreaming) {\n return;\n }\n void stream!.writable.abort('Request Aborted');\n void stream!.readable.cancel('Request Aborted');\n });\n context.setStream(stream!.readable);\n }\n\n while (true) {\n // we manually read the stream instead of using `response.json()`\n // or `response.text()` because if we need to stream the body\n // we need to be able to pass the stream along efficiently.\n const { done, value } = await reader.read();\n if (done) {\n if (isStreaming) {\n isStreaming = false;\n await writer!.ready;\n await writer!.close();\n }\n break;\n }\n text += decoder.decode(value, { stream: true });\n\n // if we are streaming, we want to pass the stream along\n if (isStreaming) {\n await writer!.ready;\n await writer!.write(value);\n } else if (context.hasRequestedStream) {\n const encode = new TextEncoder();\n isStreaming = true;\n stream = new TransformStream();\n // Listen for the abort event on the AbortSignal\n // oxlint-disable-next-line no-loop-func\n context.request.signal?.addEventListener('abort', () => {\n if (!isStreaming) {\n return;\n }\n void stream!.writable.abort('Request Aborted');\n void stream!.readable.cancel('Request Aborted');\n });\n context.setStream(stream.readable);\n writer = stream.writable.getWriter();\n await writer.ready;\n await writer.write(encode.encode(text));\n await writer.ready;\n await writer.write(value);\n }\n }\n\n if (isStreaming) {\n isStreaming = false;\n await writer!.ready;\n await writer!.close();\n }\n }\n // if we are an error, we will want to throw\n if (isError) {\n let errorPayload: object | undefined;\n try {\n errorPayload = JSON.parse(text) as object;\n } catch {\n // void;\n }\n // attempt errors discovery\n const errors = Array.isArray(errorPayload)\n ? errorPayload\n : isDict(errorPayload) && Array.isArray(errorPayload.errors)\n ? errorPayload.errors\n : null;\n\n const statusText = response.statusText || ERROR_STATUS_CODE_FOR.get(response.status) || 'Unknown Request Error';\n const msg = `[${response.status} ${statusText}] ${context.request.method ?? 'GET'} (${response.type}) - ${\n response.url\n }`;\n\n const error = (errors ? new AggregateError(errors, msg) : new Error(msg)) as Error & {\n content: object | undefined;\n } & FetchError;\n error.status = response.status;\n error.statusText = statusText;\n error.isRequestError = true;\n error.code = error.status;\n error.name = error.statusText.replaceAll(' ', '') + 'Error';\n error.content = errorPayload;\n throw error;\n } else {\n return JSON.parse(text) as T;\n }\n },\n};\n\nfunction isDict(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object';\n}\n\nexport { Fetch };\n","import { DEBUG, TESTING } from '@warp-drive/core/build-config/env';\n\nimport { waitFor } from '../../signals/-private';\nimport { peekUniversalTransient, setUniversalTransient } from '../../types/-private';\nimport type { RequestKey } from '../../types/identifier';\nimport { EnableHydration, type RequestInfo, type StructuredErrorDocument } from '../../types/request';\nimport { assertValidRequest } from './debug';\nimport { upgradePromise } from './future';\nimport { clearRequestResult, getRequestResult, setPromiseResult } from './promise-cache';\nimport type { CacheHandler, Future, GenericCreateArgs, GodContext, Handler, ManagedRequestPriority } from './types';\nimport { executeNextHandler, IS_CACHE_HANDLER } from './utils';\n\n/**\n * ## Import\n *\n * ```js\n * import { RequestManager } from '@warp-drive/core';\n * ```\n *\n * For complete usage guide see the [RequestManager Documentation](/guides/).\n *\n * ## How It Works\n *\n * ```ts\n * interface RequestManager {\n * request<T>(req: RequestInfo): Future<T>;\n * }\n * ```\n *\n * A RequestManager provides a request/response flow in which configured\n * handlers are successively given the opportunity to handle, modify, or\n * pass-along a request.\n *\n * <img src=\"/images/handlers-all-labeled.gif\" alt=\"RequestManager Flow Animation\" width=\"100%\" />\n *\n * For example:\n *\n * ::: code-group\n *\n * ```ts [Setup.ts]\n * import { RequestManager, Fetch } from '@warp-drive/core';\n * import { AutoCompress } from '@warp-drive/utilities/handlers';\n * import Auth from 'ember-simple-auth/handler';\n *\n * // ... create manager\n * const manager = new RequestManager()\n * .use([Auth, new AutoCompress(), Fetch]); // [!code focus]\n * ```\n *\n * ```ts [Usage.ts]\n * import Config from './config';\n *\n * const { apiUrl } = Config;\n *\n * // ... execute a request\n * const response = await manager.request({\n * url: `${apiUrl}/users`\n * });\n * ```\n *\n * :::\n *\n * ### Futures\n *\n * The return value of `manager.request` is a `Future`, which allows\n * access to limited information about the request while it is still\n * pending and fulfills with the final state when the request completes.\n *\n * A `Future` is cancellable via `abort`.\n *\n * Handlers may optionally expose a `ReadableStream` to the `Future` for\n * streaming data; however, when doing so the future should not resolve\n * until the response stream is fully read.\n *\n * ```ts\n * interface Future<T> extends Promise<StructuredDocument<T>> {\n * abort(): void;\n *\n * async getStream(): ReadableStream | null;\n * }\n * ```\n *\n * ### StructuredDocuments\n *\n * A Future resolves with a `StructuredDataDocument` or rejects with a `StructuredErrorDocument`.\n *\n * ```ts\n * interface StructuredDataDocument<T> {\n * request: ImmutableRequestInfo;\n * response: ImmutableResponseInfo;\n * content: T;\n * }\n * interface StructuredErrorDocument extends Error {\n * request: ImmutableRequestInfo;\n * response: ImmutableResponseInfo;\n * error: string | object;\n * }\n * type StructuredDocument<T> = StructuredDataDocument<T> | StructuredErrorDocument;\n * ```\n *\n * @public\n */\nexport class RequestManager {\n /** @internal */\n declare private _handlers: Handler[];\n /** @internal */\n declare private _hasCacheHandler: boolean;\n /**\n * A map of pending requests from request.id to their\n * associated CacheHandler promise.\n *\n * This queue is managed by the CacheHandler\n *\n * @internal\n */\n declare _pending: Map<number, Promise<unknown>>;\n /** @internal */\n declare _deduped: Map<RequestKey, { priority: ManagedRequestPriority; promise: Promise<unknown> }>;\n\n constructor(options?: GenericCreateArgs) {\n Object.assign(this, options);\n this._pending = new Map();\n this._deduped = new Map();\n this._handlers = [];\n }\n\n /**\n * Register a handler to use for primary cache intercept.\n *\n * Only one such handler may exist. If using the same\n * RequestManager as the Store instance the Store\n * registers itself as a Cache handler.\n *\n * @public\n */\n useCache(cacheHandler: CacheHandler & { [IS_CACHE_HANDLER]?: true }): this {\n if (DEBUG) {\n if (this._hasCacheHandler) {\n throw new Error(`\\`RequestManager.useCache(<handler>)\\` May only be invoked once.`);\n }\n if (Object.isFrozen(this._handlers)) {\n throw new Error(\n `\\`RequestManager.useCache(<handler>)\\` May only be invoked prior to any request having been made.`\n );\n }\n this._hasCacheHandler = true;\n }\n cacheHandler[IS_CACHE_HANDLER] = true;\n this._handlers.unshift(cacheHandler as Handler);\n return this;\n }\n\n /**\n * Register handler(s) to use when a request is issued.\n *\n * Handlers will be invoked in the order they are registered.\n * Each Handler is given the opportunity to handle the request,\n * curry the request, or pass along a modified request.\n *\n * @public\n */\n use(newHandlers: Handler[]): this {\n const handlers = this._handlers;\n if (DEBUG) {\n if (Object.isFrozen(handlers)) {\n throw new Error(`Cannot add a Handler to a RequestManager after a request has been made`);\n }\n if (!Array.isArray(newHandlers)) {\n throw new Error(\n `\\`RequestManager.use(<Handler[]>)\\` expects an array of handlers, but was called with \\`${typeof newHandlers}\\``\n );\n }\n newHandlers.forEach((handler, index) => {\n if (\n !handler ||\n (typeof handler !== 'function' && typeof handler !== 'object') ||\n typeof handler.request !== 'function'\n ) {\n throw new Error(\n `\\`RequestManager.use(<Handler[]>)\\` expected to receive an array of handler objects with request methods, by the handler at index ${index} does not conform.`\n );\n }\n });\n }\n handlers.push(...newHandlers);\n return this;\n }\n\n /**\n * Issue a Request.\n *\n * Returns a Future that fulfills with a StructuredDocument\n *\n * @public\n */\n request<RT>(request: RequestInfo<RT>): Future<RT> {\n const handlers = this._handlers;\n if (DEBUG) {\n if (!Object.isFrozen(handlers)) {\n Object.freeze(handlers);\n }\n assertValidRequest(request, true);\n }\n\n const controller = request.controller || new AbortController();\n if (request.controller) {\n delete request.controller;\n }\n\n const requestId = peekUniversalTransient<number>('REQ_ID') ?? 0;\n setUniversalTransient('REQ_ID', requestId + 1);\n\n const context = {\n controller,\n response: null,\n stream: null,\n hasRequestedStream: false,\n id: requestId,\n identifier: null,\n requester: request[EnableHydration] && request.store ? request.store : this,\n } satisfies GodContext;\n const promise = executeNextHandler<RT>(handlers, request, 0, context);\n\n // the cache handler will set the result of the request synchronously\n // if it is able to fulfill the request from the cache\n const cacheResult = getRequestResult(requestId);\n\n if (TESTING) {\n if (!request.disableTestWaiter) {\n const newPromise = waitFor(promise);\n const finalPromise = upgradePromise(\n newPromise.then(\n (result) => {\n setPromiseResult(finalPromise, { isError: false, result });\n clearRequestResult(requestId);\n return result;\n },\n (error: StructuredErrorDocument) => {\n setPromiseResult(finalPromise, { isError: true, result: error });\n clearRequestResult(requestId);\n throw error;\n }\n ),\n promise\n );\n\n if (cacheResult) {\n setPromiseResult(finalPromise, cacheResult);\n }\n\n return finalPromise;\n }\n }\n\n // const promise1 = store.request(myRequest);\n // const promise2 = store.request(myRequest);\n // promise1 === promise2; // false\n // either we need to make promise1 === promise2, or we need to make sure that\n // we need to have a way to key from request to result\n // such that we can lookup the result here and return it if it exists\n const finalPromise = upgradePromise(\n promise.then(\n (result) => {\n setPromiseResult(finalPromise, { isError: false, result });\n clearRequestResult(requestId);\n return result;\n },\n (error: StructuredErrorDocument) => {\n setPromiseResult(finalPromise, { isError: true, result: error });\n clearRequestResult(requestId);\n throw error;\n }\n ),\n promise\n );\n\n if (cacheResult) {\n setPromiseResult(finalPromise, cacheResult);\n }\n\n return finalPromise;\n }\n\n /**\n * This method exists so that the RequestManager can be created\n * can be created by container/factory systems that expect to\n * call a static `create` method to instantiate the class.\n *\n * Using `new RequestManager()` directly is preferred.\n *\n * @private\n */\n static create(options?: GenericCreateArgs): RequestManager {\n return new this(options);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRequestManager extends RequestManager {\n /**\n * A map of pending requests from request.id to their\n * associated CacheHandler promise.\n *\n * This queue is managed by the CacheHandler\n *\n */\n _pending: Map<number, Promise<unknown>>;\n _deduped: Map<RequestKey, { priority: ManagedRequestPriority; promise: Promise<unknown> }>;\n}\n","/**\n * @module\n * @mergeModuleWith <project>\n */\n\nimport { TESTING } from '@warp-drive/build-config/env';\n\nimport type { CAUTION_MEGA_DANGER_ZONE_Extension } from './reactive.ts';\nimport { instantiateRecord, registerDerivations, SchemaService, teardownRecord } from './reactive.ts';\nimport type { ReactiveDocument } from './reactive/-private/document.ts';\nimport type { Handler } from './request.ts';\nimport { Fetch } from './request/-private/fetch.ts';\nimport { RequestManager } from './request/-private/manager.ts';\nimport { DefaultCachePolicy } from './store.ts';\nimport { CacheHandler, type CachePolicy, Store, recordIdentifierFor } from './store/-private.ts';\nimport type { CacheCapabilitiesManager, ResourceKey } from './types.ts';\nimport type { Cache } from './types/cache.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { RequestInfo } from './types/request.ts';\nimport { getRuntimeConfig, setIsMaybeMirage, setLogging } from './types/runtime.ts';\nimport type { Derivation, HashFn, Transformation } from './types/schema/concepts.ts';\nimport type { ObjectSchema, PolarisResourceSchema, Trait } from './types/schema/fields.ts';\n\nexport { recordIdentifierFor, recordIdentifierFor as cacheKeyFor };\n\nexport { Fetch, RequestManager };\n\nif (TESTING) {\n // @ts-expect-error adding to globalThis\n globalThis.setWarpDriveLogging = setLogging;\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveRuntimeConfig = getRuntimeConfig;\n}\n\n// Mirage (or another Pretender-based fetch mock) may be used outside of a\n// `TESTING` build (e.g. `ember serve` in dev mode), so this override is\n// exposed unconditionally rather than gated to the `TESTING` env.\n// @ts-expect-error adding to globalThis\nglobalThis.setWarpDriveIsMaybeMirage = setIsMaybeMirage;\n\nexport { Store, CacheHandler, type CachePolicy };\n\nexport { type StoreRequestContext, type StoreRequestInput, storeFor } from './store/-private.ts';\n\n/**\n * @deprecated use {@link ReactiveDocument} instead\n */\nexport type Document<T> = ReactiveDocument<T>;\n\nexport type {\n DocumentCacheOperation,\n CacheOperation,\n NotificationChannel,\n NotificationType,\n NotifyKeys,\n} from './store/-private/managers/notification-manager.ts';\n\nexport {\n setIdentifierGenerationMethod,\n setIdentifierUpdateMethod,\n setIdentifierForgetMethod,\n setIdentifierResetMethod,\n setKeyInfoForResource,\n} from './store/-private/managers/cache-key-manager.ts';\n\n/**\n * Options for setting up a Store instance with `useRecommendedStore`.\n */\nexport interface StoreSetupOptions<T extends Cache = Cache> {\n /**\n * A constructor for the {@link Cache} implementation to use, receiving the\n * store's {@link CacheCapabilitiesManager} when instantiated.\n */\n cache: {\n /**\n * Constructs a new {@link Cache} instance for the store.\n */\n new (capabilities: CacheCapabilitiesManager): T;\n };\n /**\n * The Cache policy to use.\n *\n * Defaults to {@link DefaultCachePolicy} configured to\n * respect `Expires`, `X-WarpDrive-Expires`, and `Cache-Control` headers\n * with a fallback to 30s soft expiration and 15m hard expiration.\n */\n policy?: CachePolicy;\n /**\n * The request handlers to use. {@link Fetch} will automatically\n * be added to the end of the handler chain and {@link CacheHandler}\n * will automatically be added as the cache handler.\n *\n * May also be given as a function that receives the {@link Store} instance\n * and returns the handlers to use. This is useful when a handler needs\n * access to the store (e.g. to look up its owner for injections) or when\n * the set of handlers should be decided lazily (e.g. based on a feature\n * flag service that may not be ready until after the store is constructed).\n *\n * The function is invoked lazily, the first time the store's `requestManager`\n * is accessed, and only once per store instance.\n *\n * See the \"Adding Stateful Handlers\" section of {@link useRecommendedStore}\n * for an example of using this callback to construct a handler that needs\n * access to an Ember service.\n */\n handlers?: Handler[] | ((store: Store) => Handler[]);\n /**\n * Schemas describing the structure of your resource data.\n *\n * See {@link PolarisResourceSchema,} and {@link ObjectSchema} for more information.\n */\n schemas?: Array<PolarisResourceSchema | ObjectSchema>;\n /**\n * {@link Trait | Traits} to use with {@link PolarisResourceSchema, | Resource Schemas}\n */\n traits?: Trait[];\n /**\n * {@link Derivation | Derivations} to use for derived fields.\n */\n derivations?: Derivation[];\n /**\n * {@link Transformation | Transformations} to use for transforming fields.\n */\n transformations?: Transformation[];\n /**\n * {@link HashFn | Hash Functions} to use for embedded object identity and polymorphic type calculations\n */\n hashFns?: HashFn[];\n /**\n * {@link CAUTION_MEGA_DANGER_ZONE_Extension | Extensions} to use with resources, objects and arrays\n * to provide custom behaviors and capabilities that are not described by Schema.\n *\n * This feature should only be used during a transition period to support migrating towards\n * schemas from existing Model and ModelFragments implementations.\n */\n CAUTION_MEGA_DANGER_ZONE_extensions?: CAUTION_MEGA_DANGER_ZONE_Extension[];\n}\n\nexport declare class ConfiguredStore<\n T extends {\n /**\n * The {@link Cache} instance type this configured store's `createCache`\n * method produces.\n */\n cache: Cache;\n },\n Policy extends CachePolicy = CachePolicy,\n> extends Store {\n lifetimes: Policy;\n // get cache(): T extends OptionsWithCache<infer R> ? R : never;\n createCache(capabilities: CacheCapabilitiesManager): T['cache'];\n}\n\n/**\n * Creates a configured Store class with recommended defaults\n * for schema handling, reactivity, caching, and request management.\n *\n * ```ts\n * import { useRecommendedStore } from '@warp-drive/core';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * export const Store = useRecommendedStore({\n * cache: JSONAPICache,\n * schemas: [],\n * });\n * ```\n *\n * ### Adding Stateful Handlers\n *\n * A request {@link Handler} is sometimes more than a plain object or class with\n * a `request` method — it may need access to a stateful dependency such as an\n * Ember service (an auth token, a feature-flags service, an i18n helper, etc.).\n *\n * A plain class handler that only relies on Ember's `@service` decorator will\n * not work here on its own: the handler is never instantiated *through* Ember's\n * container (it's just `new`'d up), so it has no owner and its `@service`\n * injections would fail to resolve.\n *\n * Instead, give {@link StoreSetupOptions.handlers | handlers} a function. It\n * receives the {@link Store} instance being configured, which by the time the\n * function runs already has an owner assigned. Use `getOwner`/`setOwner` from\n * `@ember/owner` to transfer that owner onto your handler instance before\n * returning it, exactly as you would when constructing any other DI-aware\n * object outside of the container:\n *\n * ```ts\n * import { getOwner, setOwner } from '@ember/owner';\n * import { service } from '@ember/service';\n * import { useRecommendedStore } from '@warp-drive/core';\n * import type { NextFn } from '@warp-drive/core/request';\n * import type { RequestContext } from '@warp-drive/core/types/request';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * class AuthHandler {\n * @service session;\n *\n * request<T>(context: RequestContext, next: NextFn<T>) {\n * const headers = new Headers(context.request.headers);\n * headers.append('Authorization', `Bearer ${this.session.accessToken}`);\n * return next(Object.assign({}, context.request, { headers }));\n * }\n * }\n *\n * export default useRecommendedStore({\n * cache: JSONAPICache,\n * handlers: (store) => {\n * const authHandler = new AuthHandler();\n * setOwner(authHandler, getOwner(store)!);\n * return [authHandler];\n * },\n * });\n * ```\n *\n * The `handlers` function is invoked lazily and only once per store instance,\n * the first time `store.requestManager` is accessed, so it is safe to do\n * owner-dependent setup like this inside of it.\n *\n * ### Accessing the Store from a Handler's Context\n *\n * If a handler only needs to read something *off of the store itself*\n * (its cache, or a property/service you've attached to a custom store\n * subclass) rather than an unrelated Ember service, there is a second,\n * simpler option that requires no DI/`setOwner` wiring at all.\n *\n * Every request issued via {@link Store.request | store.request(...)}\n * automatically carries the originating store along as\n * {@link RequestInfo.store | context.request.store}. Any handler — a plain\n * object, a function-built handler, or a class — can read it directly,\n * without needing the `handlers` callback form shown above:\n *\n * ```ts\n * import { useRecommendedStore } from '@warp-drive/core';\n * import type { NextFn } from '@warp-drive/core/request';\n * import type { RequestContext } from '@warp-drive/core/types/request';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * const LoggingHandler = {\n * request<T>(context: RequestContext, next: NextFn<T>) {\n * // only present when the request was made via `store.request(...)`\n * const store = context.request.store;\n * if (store) {\n * console.log(`[${store.constructor.name}] ${context.request.url ?? ''}`);\n * }\n * return next(context.request);\n * },\n * };\n *\n * export default useRecommendedStore({\n * cache: JSONAPICache,\n * handlers: [LoggingHandler],\n * });\n * ```\n *\n * The trade-off versus the `getOwner`/`setOwner` pattern above is that\n * `context.request.store` is only populated for requests issued via\n * `store.request(...)`; a request made directly against a\n * {@link RequestManager} won't have it set unless the caller supplies it\n * explicitly, so a handler relying on it should treat it as optional (as\n * `LoggingHandler` does above).\n */\nexport function useRecommendedStore<T extends Cache, Policy extends CachePolicy>(\n options: StoreSetupOptions<T> & { policy: Policy },\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }, Policy>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T> & { policy?: undefined },\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }, DefaultCachePolicy>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T>,\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T>,\n StoreKlass: typeof Store = Store\n): typeof ConfiguredStore<{ cache: T }> {\n return class AppStore extends StoreKlass {\n constructor(createArgs?: unknown) {\n super(createArgs);\n // installed via defineProperty (rather than a class field/accessor) so that\n // this lazy override of the inherited `requestManager` field does not\n // conflict with the documented pattern of assigning it directly on\n // consumer-authored Store subclasses. The setter preserves the ability\n // to replace `requestManager` outright after construction.\n let requestManager: RequestManager | undefined;\n Object.defineProperty(this, 'requestManager', {\n configurable: true,\n enumerable: true,\n get: (): RequestManager => {\n if (!requestManager) {\n const handlers = typeof options.handlers === 'function' ? options.handlers(this) : (options.handlers ?? []);\n requestManager = new RequestManager().use([...handlers, Fetch]).useCache(CacheHandler);\n }\n return requestManager;\n },\n set: (value: RequestManager): void => {\n requestManager = value;\n },\n });\n }\n\n lifetimes =\n options.policy ??\n new DefaultCachePolicy({\n apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes\n apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds\n constraints: {\n headers: {\n 'X-WarpDrive-Expires': true,\n 'Cache-Control': true,\n Expires: true,\n },\n },\n });\n\n createSchemaService() {\n const schema = new SchemaService();\n registerDerivations(schema);\n if (options.schemas) schema.registerResources(options.schemas);\n\n if (options.traits) {\n for (const trait of options.traits) {\n schema.registerTrait(trait);\n }\n }\n\n if (options.derivations) {\n for (const derivation of options.derivations) {\n schema.registerDerivation(derivation);\n }\n }\n\n if (options.transformations) {\n for (const transformation of options.transformations) {\n schema.registerTransformation(transformation);\n }\n }\n\n if (options.hashFns) {\n for (const hashFn of options.hashFns) {\n schema.registerHashFn(hashFn);\n }\n }\n\n if (options.CAUTION_MEGA_DANGER_ZONE_extensions) {\n for (const extension of options.CAUTION_MEGA_DANGER_ZONE_extensions) {\n schema.CAUTION_MEGA_DANGER_ZONE_registerExtension(extension);\n }\n }\n\n return schema;\n }\n\n createCache(capabilities: CacheCapabilitiesManager) {\n // oxlint-disable-next-line new-cap\n return new options.cache(capabilities);\n }\n\n instantiateRecord(key: ResourceKey, createArgs?: Record<string, unknown>) {\n return instantiateRecord(this, key, createArgs);\n }\n\n teardownRecord(record: unknown): void {\n return teardownRecord(record);\n }\n };\n}\n"],"x_google_ignoreList":[18],"mappings":";;;;;;;;;;;;;;;AAcA,SAASM,YAAYC,MAAoB;CACvC,IAAI,OAAOA,SAAS,UAAU,OAAOA;CACrC,OAAOA,KAAKC;AACd;;;;;;;;;;;;AAmLA,MAAMG,wBAAwB;CAC5B,MAAMC,SAEJL,MACAM,UAA4Cb,UAA+B;EAAEc,KAAK;EAAIC,QAAQ;CAAM,CAAC,GAC5D;EAEzC,MAAMP,OAAO,KAAKQ,QAAQT;EAC1B,I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AQiC,iBACV,KAAK,MAAMC,kBAAkBlC,QAAQiC,iBACnCT,OAAOW,uBAAuBD,cAAc;GAIhD,IAAIlC,QAAQoC,SACV,KAAK,MAAMC,UAAUrC,QAAQoC,SAC3BZ,OAAOc,eAAeD,MAAM;GAIhC,IAAIrC,QAAQuC,qCACV,KAAK,MAAMC,aAAaxC,QAAQuC,qCAC9Bf,OAAOiB,2CAA2CD,SAAS;GAI/D,OAAOhB;EACT;EAEAkB,YAAYC,cAAwC;GAElD,OAAO,IAAI3C,QAAQ4C,MAAMD,YAAY;EACvC;EAEApE,kBAAkBsE,KAAkBzC,YAAsC;GACxE,OAAO7B,kBAAkB,MAAMsE,KAAKzC,UAAU;EAChD;EAEA1B,eAAeoE,QAAuB;GACpC,OAAOpE,eAAeoE,MAAM;EAC9B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"src-BW5t6nJR.js","names":["withBrand","defineGate","notifyInternalSignal","peekInternalSignal","withSignalStore","Destroy","urlFromLink","link","href","upgradeThis","doc","ReactiveDocumentProto","_request","options","url","method","links","Object","assign","response","_store","request","content","fetch","test","Error","related","self","cacheOptions","key","identifier","lid","next","prev","first","last","toJSON","data","undefined","errors","meta","_subscription","notifications","unsubscribe","get","document","_localCache","cache","peek","Array","isArray","recordArrayManager","getCollection","source","slice","requestKey","peekRecord","createReactiveDocument","store","cacheKey","localCache","create","signals","subscribe","_key","type","TEXT_COLORS","TEXT","notify","graph","request","cache","BG_COLORS","NOTIFY_BORDER","LIGHT_DARK_ALT","lightgreen","green","badge","isLight","color","bgColor","border","correctColor","colorForBucket","scope","bucket","logGroup","prefix","subScop1","subScop2","subScop3","subScop4","console","groupCollapsed","_log","log","isLightMode","window","matchMedia","matches","scopePath","path","coerceId","id","normalized","undefined","String","console","warn","JSON","stringify","test","Error","length","ensureStringId","isNaN","dasherize","normalizeModelName","type","result","console","warn","getOrSetGlobal","peekTransient","setTransient","CACHE_OWNER","DEBUG_CLIENT_ORIGINATED","DEBUG_KEY_TYPE","DEBUG_STALE_CACHE_OWNER","hasId","hasLid","hasType","coerceId","normalizeModelName","installPolyfill","getGlobalConfig","getGlobalConfig0","isResourceKey","identifier","type","undefined","isRequestKey","isFastBoot","FastBoot","_crypto","require","globalThis","crypto","uuidv4","test","Error","randomUUID","freeze","obj","Object","setIdentifierGenerationMethod","method","setIdentifierUpdateMethod","setIdentifierForgetMethod","setIdentifierResetMethod","setKeyInfoForResource","assertIsRequest","request","NEW_IDENTIFIERS","Map","IDENTIFIER_CACHE_ID","updateTypeIdMapping","typeMap","id","idMap","get","set","lid","defaultUpdateMethod","data","bucket","defaultKeyInfoMethod","resource","known","defaultGenerationMethod","url","toUpperCase","defaultEmptyCallback","args","defaultMergeMethod","a","_b","_c","DEBUG_MAP","WeakMap","CacheKeyManager","_cache","constructor","_generate","_update","_forget","_reset","_merge","_keyInfoForResource","_id","resources","resourcesByType","create","documents","polymorphicLidBackMap","__configureMerge","upgradeIdentifier","_getRecordIdentifier","shouldGenerate","WarpDrive","debug","LOG_IDENTIFIERS","getWarpDriveRuntimeConfig","console","groupCollapsed","has","JSON","stringify","log","groupEnd","getIdentifierFromLid","makeResourceKey","keyInfo","addResourceToCache","peekResourceKey","peekRequestKey","cacheKey","cacheOptions","key","getOrCreateDocumentIdentifier","getOrCreateRecordIdentifier","createIdentifierForNewRecord","newLid","String","updateRecordIdentifier","identifierObject","existingIdentifier","detectMerge","hadLid","generatedIdentifier","_mergeRecordIdentifiers","performRecordIdentifierUpdate","newId","typeSet","delete","kept","abandoned","abandonedBackReferences","forgetRecordIdentifier","keptBackReferences","push","forEach","backReferences","destroy","clear","recordIdentifier","clientOriginated","wrapper","proto","value","defineProperty","enumerable","setPrototypeOf","updateFn","warn","cache","newType","newTypeSet","isRequestKey","isResourceKey","CacheCapabilitiesManager","constructor","_store","_willNotify","_pendingNotifies","Map","cacheKeyManager","identifierCache","_scheduleNotification","identifier","key","channel","pending","get","set","channels","Set","add","_cbs","_schedule","_flushNotifications","forEach","channelsByKey","keysByChannel","keys","notifications","notify","notifyChange","namespace","test","Error","schema","setRecordId","id","_instanceCache","hasRecord","Boolean","peek","disconnectRecord","disconnect","delete","prototype","getSchemaDefinitionService","assertPrivateCapabilities","manager","createReactiveDocument","_CHECKOUT","ReactiveResource","getOrSetGlobal","log","logGroup","CacheCapabilitiesManager","getGlobalConfig","getGlobalConfig0","isDestroyable","record","Boolean","destroy","RecordCache","Map","peekResourceKey","get","recordIdentifierFor","test","Error","String","has","setRecordIdentifier","identifier","set","removeRecordIdentifier","delete","StoreMap","storeFor","ignoreMissing","store","InstanceCache","constructor","__instances","document","_storeWrapper","cacheKeyManager","__configureMerge","matchedIdentifier","resourceData","keptIdentifier","id","type","staleIdentifier","keptHasRecord","staleHasRecord","lid","cache","patch","op","value","unloadRecord","peek","getDocument","doc","getRecord","_createRecord","recordIsLoaded","filterDeleted","isNew","isEmpty","isDeleted","isDeletionCommitted","disconnect","isDestroyed","isDestroying","_graph","remove","forgetRecordIdentifier","_requestCache","_clearEntries","WarpDrive","debug","LOG_INSTANCE_CACHE","globalThis","getWarpDriveRuntimeConfig","requests","getRequestStateService","getPendingRequestsForRecord","some","req","console","groupCollapsed","_join","clear","_cache","undefined","resources","forEach","typeCache","resourcesByType","identifiers","setRecordId","oldId","warn","existingIdentifier","updateRecordIdentifier","notifications","notify","getNewRecord","instances","properties","schema","resource","legacy","editable","Object","assign","instantiateRecord","groupEnd","_clearCaches","teardownRecord","willSyncFlushWatchers","getOrSetGlobal","log","isRequestKey","isResourceKey","getGlobalConfig","getGlobalConfig0","isCacheOperationValue","value","UnscopedChannel","Symbol","keyToString","key","Set","Array","from","join","mergeIntoBuffer","buffer","channel","set","existing","get","undefined","channels","Map","channelsForKey","values","ch","add","map","keys","k","shouldDeliverToChannel","subscriberChannel","has","count","label","globalThis","__WarpDriveMetricCountData","asInternalToken","token","test","Error","_unsubscribe","cache","cacheKey","for","WarpDrive","debug","LOG_NOTIFICATIONS","getWarpDriveRuntimeConfig","console","callbacks","index","indexOf","splice","NotificationManager","constructor","store","isDestroyed","_buffered","_hasFlush","_cache","subscribe","callback","includes","push","unsubscribe","notify","String","_hasSubscribers","hasSubscribers","LOG_METRIC_COUNTS","type","_scheduleNotify","lid","_onNextFlush","cb","_onFlushCB","asyncFlush","_enableAsyncFlush","_flush","buffered","size","states","bucket","_flushNotification","destroy","clear","callbackMap","forEach","length","hasSubscriber","Boolean","Context","upgradeThis","obj","update","isUpdating","_updatingPromise","updatingPromise","_update","finally","isDestroying","isDestroyed","save","context","promise","Promise","all","map","record","store","saveRecord","then","ARRAY_GETTER_METHODS","Set","Symbol","iterator","ARRAY_SETTER_METHODS","isArrayGetter","prop","has","isArraySetter","convertToInt","num","Number","isNaN","safeForEach","instance","arr","callback","target","undefined","slice","test","Error","length","index","call","_instanceCache","getRecord","consumeInternalSignal","getOrCreateInternalSignal","expectNever","value","isExtensionProp","extensions","prop","Boolean","has","performObjectExtensionGet","receiver","signals","desc","get","kind","fn","signal","call","test","Error","String","undefined","performExtensionSet","set","performArrayExtensionGet","_SIGNAL","boundFns","transaction","result","Reflect","apply","arguments","NativeProxy","Proxy","Context","isExtensionProp","performArrayExtensionGet","performExtensionSet","ARRAY_SIGNAL","consumeInternalSignal","createInternalSignal","createSignalDescriptor","notifyInternalSignal","Signals","withSignalStore","getOrSetGlobal","recordIdentifierFor","isResourceKey","convertToInt","isArrayGetter","isArraySetter","safeForEach","NativeProxy","IS_COLLECTION","Symbol","for","isContextProp","prop","MUTABLE_PROPS","ARR_BRACKET_DESC","enumerable","configurable","get","IS_UPDATING_DESC","ArrayHandler","getOwnPropertyDescriptor","target","underlying","Reflect","Object","defineProperty","receiver","CONTEXT","signals","index","signal","isStale","data","manager","_syncArray","identifier","transaction","store","_instanceCache","getRecord","length","call","fn","boundFns","undefined","result","arguments","apply","set","editable","test","Error","String","args","Array","prototype","slice","mutate","features","outcome","extensions","v","value","includes","original","newIdentifier","extractIdentifierFromRecord","deleteProperty","getPrototypeOf","ILLEGAL_MUTATION","createReactiveResourceArray","options","TARGET","source","context","destroy","isDestroying","isDestroyed","Map","proxy","record","clear","createRequestCollection","config","createRelatedCollection","Context","save","update","createReactiveResourceArray","createLegacyLiveArray","options","store","manager","editable","source","data","features","modelName","type","_update","_updateLiveArray","DEPRECATED_CLASS_NAME","isUpdating","isLoaded","_updatingPromise","extensions","destroy","mutate","upgradeThis","obj","context","test","Error","findAll","reload","Context","save","update","createReactiveResourceArray","destroy","createLegacyQueryArray","options","store","manager","editable","source","data","links","meta","features","query","modelName","type","_update","_updateCollection","DEPRECATED_CLASS_NAME","isUpdating","isLoaded","_updatingPromise","extensions","destroyCollection","mutate","context","test","Error","promise","_recordArray","upgradeManager","obj","clear","call","_managed","delete","_pending","Context","notifyInternalSignal","getOrSetGlobal","createLegacyLiveArray","createLegacyQueryArray","createRequestCollection","FAKE_ARR","SLICE_BATCH_SIZE","fastPush","target","source","batch","length","splice","push","RecordArrayManager","constructor","options","store","isDestroying","isDestroyed","_live","Map","_managed","Set","_pending","_staged","_keyedArrays","_identifiers","_set","_visibilitySet","_documentSubscription","notifications","subscribe","identifier","type","has","lid","array","get","dirtyArray","_subscribeToResourceChanges","_subscription","schema","resource","legacy","cache","isNew","set","identifierAdded","identifierRemoved","identifierChanged","_syncArray","pending","isLegacyQuery","isLegacyQueryArray","sync","delete","isLegacyLiveArray","context","signal","requestKey","value","doc","peek","test","Error","data","Array","isArray","populateManagedArray","mutate","mutation","liveArrayFor","identifiers","staged","forEach","key","manager","getCollection","config","associate","query","isLoaded","links","meta","add","delta","shouldSyncFromCache","isStale","_getPendingFor","includeManaged","isRemove","liveArray","allPending","managed","arr","changes","pendingLive","size","payload","old","slice","disassociate","changeSets","existing","newState","_instanceCache","recordIsLoaded","pause","unsubscribe","resume","clear","isClear","values","destroy","ArraysCache","i","disassociateIdentifier","arraySet","state","adds","removes","index","indexOf","features","DEPRECATED_CLASS_NAME","getOrSetGlobal","Touching","Symbol","RequestPromise","EMPTY_ARR","Object","freeze","hasRecordIdentifier","op","RequestStateService","_pending","Map","_done","_subscriptions","_toFlush","_store","constructor","store","_clearEntries","identifier","delete","_enqueue","promise","queryRequest","query","data","recordIdentifier","type","has","set","request","state","get","push","_triggerSubscriptions","then","result","_dequeue","finalizedRequest","response","_addDone","error","test","Error","req","_flushRequest","length","notifications","_onNextFlush","_flush","forEach","subscriptions","callback","pending","filter","requestDataOp","requests","Array","isArray","subscribeForRecord","getPendingRequestsForRecord","getLastRequestForRecord","ReactiveResource","EnableHydration","getRuntimeConfig","setLogging","getNewRecord","InstanceCache","peekResourceKey","recordIdentifierFor","storeFor","CacheKeyManager","CacheManager","NotificationManager","RecordArrayManager","RequestPromise","RequestStateService","coerceId","ensureStringId","normalizeModelName","getGlobalConfig","getGlobalConfig0","esc","_importSync20","globalThis","setWarpDriveLogging","getWarpDriveRuntimeConfig","WarpDrive","debug","LOG_METRIC_COUNTS","__WarpDriveMetricCountData","getWarpDriveMetricCounts","structuredClone","resetWarpDriveMetricCounts","__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS","__primitiveInstanceId","interceptAndLog","klassName","methodName","klass","instantiationLabel","constructor","args","instanceId","instanceName","Error","stack","split","original","prototype","logName","instanceLogName","apply","upgradeStore","store","EmptyClass","_BaseClass","BaseClass","default","console","warn","Store","schema","_schema","createSchemaService","isDestroying","_isDestroying","value","isDestroyed","_isDestroyed","identifierCache","cacheKeyManager","createArgs","Object","assign","notifications","recordArrayManager","_requestCache","_instanceCache","_run","cb","test","_cbs","coalesce","sync","notify","_join","_schedule","name","getRequestStateService","_getAllPending","all","pending","_pending","forEach","requests","push","map","v","requestManager","promise","Promise","allSettled","length","request","requestConfig","opts","records","r","getOrCreateRecordIdentifier","DISABLE_WAITER","disableTestWaiter","LOG_REQUESTS","options","JSON","parse","stringify","log","op","url","method","future","onFinalize","_flush","createRecord","type","inputProperties","context","assertDestroyingStore","record","normalizedModelName","properties","id","undefined","adapter","adapterFor","generateIdForRecord","resource","identifier","String","lid","createIdentifierForNewRecord","cache","createOptions","normalizeProperties","resultProps","clientDidCreate","deleteRecord","setIsDeleted","isNew","unloadRecord","peekRecord","arguments","isMaybeIdentifier","stableIdentifier","isLoaded","recordIsLoaded","getRecord","normalizedId","peekAll","liveArrayFor","unloadAll","assertDestroyedStoreOnly","assertPrivateStore","_enableAsyncFlush","pause","_graph","identifiers","clear","resume","data","pushed","_push","Array","isArray","jsonApiDoc","asyncFlush","ret","put","content","createCache","_storeWrapper","destroy","create","isPrivateStore","getSchemaDefinitionService","registerSchemaDefinitionService","registerSchema","maybeIdentifier","Boolean","defs","fields","size","keys","i","prop","field","get","kind","assertRecordsPassedToHasMany","extractIdentifiersFromRecords","extractIdentifierFromRecord","join","every","recordOrPromiseRecord","extract","ensureStringId","recordIdentifierFor","defineSignal","getOrSetGlobal","preloadData","store","identifier","preload","jsonPayload","schemas","schema","fields","Object","keys","forEach","key","preloadValue","field","get","kind","relationships","preloadRelationship","attributes","cache","hasRecord","Boolean","_instanceCache","peek","upsert","relatedType","type","test","Error","Array","isArray","data","map","value","_convertPreloadRelationshipToJSON","id","_resourceIsFullDeleted","isDeletionCommitted","isNew","isDeleted","resourceIsFullyDeleted","instanceCache","RecordReference","___token","___identifier","constructor","notifications","subscribe","_","bucket","notifiedKey","_ref","destroy","unsubscribe","remoteType","push","objectOrPromise","Promise","resolve","then","peekRecord","load","findRecord","reload","prototype","AvailableShims","WeakMap","getShimClass","modelName","shims","create","set","shim","undefined","ShimModelClass","__store","Map","fieldSchemas","attrs","relationshipsByName","rels","eachAttribute","callback","binding","call","eachRelationship","eachTransformedAttribute","constructResource","ensureStringId","recordIdentifierFor","storeFor","isMaybeIdentifier","Store","normalizeModelName","SkipCache","getShimClass","preloadData","RecordReference","resourceIsFullyDeleted","prototype","findRecord","resource","id","options","console","warn","test","Error","isDestroying","isDestroyed","type","normalizedId","identifier","cacheKeyManager","getOrCreateRecordIdentifier","preload","_instanceCache","recordIsLoaded","reload","_join","promise","request","op","data","record","cacheOptions","then","document","content","findAll","query","queryRecord","getReference","resourceIdentifier","arguments","length","cache","upgradeInstanceCaches","__instances","reference","get","set","modelFor","schema","hasResource","saveRecord","Promise","reject","lid","resolve","operation","isNew","isDeleted","records","withReferences","WeakMap","MUTATION_OPS","createReactiveDocument","EnableHydration","SkipCache","log","calcShouldBackgroundFetch","calcShouldFetch","cloneError","getPriority","isCacheAffecting","isMutation","getGlobalConfig","getGlobalConfig0","CacheHandler","request","context","next","store","cacheOptions","identifier","cacheKeyManager","getOrCreateDocumentIdentifier","setIdentifier","DEDUPE","requestManager","_deduped","activeRequest","get","peeked","cache","peekRequest","priority","blocking","WarpDrive","debug","LOG_REQUESTS","globalThis","getWarpDriveRuntimeConfig","lid","promise","url","op","fetchContentAndHydrate","finally","delete","notifications","notify","set","queueMicrotask","_pending","id","test","Error","shouldHydrate","setResponse","response","content","maybeUpdateUiObjects","newError","result","options","document","_instanceCache","getDocument","updateCacheForSuccess","Array","isArray","records","didCommit","data","record","put","handleFetchSuccess","_enableAsyncFlush","_join","lifetimes","didRequest","finalPriority","_flush","updateCacheForError","error","errors","undefined","commitWasRejected","handleFetchError","signal","aborted","isMut","forEach","willCommit","willRequest","then","_requestCache","_enqueue","recordIdentifier","isResourceKey","coerceId","isNonEmptyString","constructResource","type","id","lid","resource","test","Error","trueId","Context","notifyInternalSignal","recordIdentifierFor","isResourceKey","save","createReactiveResourceArray","destroy","createLegacyManyArray","options","extensions","store","schema","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","field","manager","editable","source","data","links","meta","features","modelName","type","DEPRECATED_CLASS_NAME","isLoaded","isAsync","isPolymorphic","identifier","key","name","reload","createRecord","notify","destroyLegacyManyArray","mutate","_MUTATE","target","receiver","prop","args","_SIGNAL","collection","Reflect","set","mutateReplaceRelatedRecords","index","prior","value","mutateReplaceRelatedRecord","newValues","extractIdentifiersFromRecords","assertNoDuplicates","currentState","push","seen","Set","unique","forEach","item","has","add","newArgs","Array","from","result","apply","length","mutateAddToRelatedRecords","mutateRemoveFromRelatedRecords","unshift","mutateSortRelatedRecords","map","start","_deleteCount","adds","deleteCount","Infinity","Math","min","splice","current","concat","slice","test","Error","signal","reloadHasMany","hash","record","call","assertRecordPassedToHasMany","records","extractIdentifierFromRecord","recordOrPromiseRecord","callback","reason","state","size","duplicates","filter","currentValue","currentIndex","indexOf","console","warn","id","lid","r","sort","a","b","localeCompare","join","operationInfo","op","mutation","getAliasField","context","test","Error","setAliasField","ARRAY_SIGNAL","consumeInternalSignal","entangleSignal","withSignalStore","ReactiveResource","Context","Destroy","SOURCE","isExtensionProp","performArrayExtensionGet","performExtensionSet","ARRAY_GETTER_METHODS","Set","Symbol","iterator","SYNC_PROPS","isArrayGetter","prop","has","ARRAY_SETTER_METHODS","isArraySetter","convertToInt","num","Number","isNaN","safeForEach","instance","arr","store","callback","target","undefined","slice","test","Error","length","index","call","ManagedArray","constructor","context","owner","data","self","IS_EDITABLE","editable","schema","cache","field","signals","_SIGNAL","boundFns","Map","identifier","resourceKey","path","transaction","KeyMode","options","key","RefStorage","WeakMap","ManagedRecordRefs","kind","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","proxy","Proxy","get","receiver","isStale","newData","getAttr","push","rawValue","type","transform","transformation","hydrate","objectType","polymorphic","typePath","hashFn","schemaObjectKeyValue","hashField","resource","identity","name","isPathKeyMode","modeField","fields","recordRef","record","value","deref","Promise","resolve","then","recordPath","objectContext","modeName","schemaObject","set","WeakRef","fn","result","arguments","Reflect","apply","String","v","errorPath","reflect","setAttr","map","item","serialize","desc","enumerable","configurable","Object","defineProperty","prototype","ARRAY_SIGNAL","entangleSignal","peekInternalSignal","ManagedArray","getArrayField","context","signal","signals","record","path","at","managedArray","value","isStale","store","resourceKey","field","cache","rawValue","getAttr","options","defaultValue","editable","getRemoteAttr","setArrayField","schema","fieldSignal","peeked","transform","type","transformation","map","item","serialize","slice","setAttr","test","Error","kind","arrSignal","Array","isArray","InvalidKinds","isInvalidKind","kind","includes","isNonIdentityCacheableField","field","getFieldCacheKeyStrict","sourceKey","name","getFieldCacheKey","assertIsCacheField","test","Error","cacheKeyFor","entangleSignal","getFieldCacheKeyStrict","getBelongsToField","context","signals","record","path","at","field","resourceKey","store","schema","cache","options","linksMode","rawValue","editable","getRelationship","getRemoteRelationship","data","peekRecord","test","Error","legacy","_kind","get","setBelongsToField","isValidPolarisConfig","async","name","mutate","op","value","getResourceKey","set","entangleSignal","getCollectionField","context","signals","record","path","at","test","Error","setCollectionField","getDerivedField","context","schema","store","derivation","field","record","options","name","setDerivedField","test","Error","path","join","resourceKey","type","kind","fastPush","EnableHydration","Context","ManyArrayManager","constructor","record","editable","context","store","identifier","resourceKey","_syncArray","array","method","rawValue","cache","key","meta","links","currentState","source","data","undefined","length","reloadHasMany","options","field","schema","fields","get","test","Error","kind","cacheOptions","extractCacheOptions","reload","types","type","getRelationship","req","url","getRelatedLink","op","records","request","mutate","mutation","resource","related","href","backgroundReload","entangleSignal","createLegacyManyArray","getFieldCacheKeyStrict","ManyArrayManager","getHasManyField","context","signal","signals","record","path","at","store","field","options","linksMode","cached","value","editable","resourceKey","cache","rawValue","getRelationship","getRemoteRelationship","managedArray","manager","source","data","slice","type","isLoaded","isAsync","async","isPolymorphic","polymorphic","identifier","links","meta","test","Error","legacy","schema","_kind","get","setHasManyField","Array","isArray","set","getHashField","context","field","path","resourceKey","schema","cache","store","test","Error","kind","Array","isArray","length","realPath","slice","rawData","editable","getAttr","getRemoteAttr","hashFn","options","name","setHashField","join","type","entangleSignal","getIdentityField","context","signals","record","resourceKey","id","setIdentityField","value","store","test","Error","length","normalizedId","String","didChange","type","_instanceCache","setRecordId","notifications","notify","consumeInternalSignal","entangleSignal","notifyInternalSignal","OBJECT_SIGNAL","withSignalStore","getOrSetGlobal","Context","SOURCE","isExtensionProp","performExtensionSet","performObjectExtensionGet","notifyObject","obj","ObjectSymbols","Set","ManagedObject","constructor","context","field","path","self","Object","assign","value","signals","_SIGNAL","undefined","identifier","resourceKey","cache","schema","store","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_objectExtensions","proxy","Proxy","ownKeys","keys","has","target","prop","getOwnPropertyDescriptor","writable","editable","enumerable","configurable","get","receiver","Symbol","toPrimitive","toStringTag","type","id","lid","isStale","newData","getAttr","transform","transformation","hydrate","options","record","structuredClone","Reflect","set","test","Error","String","reflect","setAttr","val","serialize","ManagedObjectMap","Map","peekManagedObject","managedObjectMapForRecord","name","defineSignal","entangleSignal","getFieldCacheKeyStrict","Context","ResourceRelationship","constructor","context","store","resourceKey","cache","name","field","rawValue","editable","getRelationship","getRemoteRelationship","lid","links","self","data","peekRecord","Object","freeze","assign","meta","fetch","options","url","getHref","related","Error","method","type","String","request","prototype","link","href","getResourceField","signals","record","path","at","setResourceField","test","ARRAY_SIGNAL","peekInternalSignal","getArrayField","getSchemaArrayField","setSchemaArrayField","context","arrayValue","value","slice","fieldSignal","signals","path","at","peeked","store","cache","setAttr","resourceKey","test","Error","field","kind","arrSignal","isStale","Array","isArray","entangleSignal","ManagedObjectMap","ReactiveResource","Destroy","getSchemaObjectField","context","signal","signals","record","path","at","store","resourceKey","field","cache","rawValue","editable","getAttr","getRemoteAttr","options","polymorphic","defaultValue","value","Promise","resolve","then","schema","objectType","typePath","type","test","Error","hashFn","hashField","resource","identity","name","cachedSchemaObject","schemaObject","modeName","legacy","setSchemaObjectField","newValue","schemaFields","fields","key","Object","keys","has","delete","setAttr","getAliasField","setAliasField","getArrayField","setArrayField","getAttributeField","setAttributeField","getBelongsToField","setBelongsToField","getCollectionField","setCollectionField","getDerivedField","setDerivedField","getGenericField","setGenericField","getHasManyField","setHasManyField","getHashField","setHashField","getIdentityField","setIdentityField","getLocalField","setLocalField","getObjectField","setObjectField","getResourceField","setResourceField","getSchemaArrayField","setSchemaArrayField","getSchemaObjectField","setSchemaObjectField","DefaultMode","get","set","mutable","enumerable","serializable","alias","array","attribute","belongsTo","collection","derived","field","hasMany","object","resource","ARRAY_SIGNAL","entangleSignal","notifyInternalSignal","OBJECT_SIGNAL","Signals","withSignalStore","recordIdentifierFor","setRecordIdentifier","removeRecordIdentifier","STRUCTURED","RecordStore","DefaultMode","isExtensionProp","performExtensionSet","performObjectExtensionGet","getFieldCacheKey","peekManagedObject","Checkout","Commit","Context","Destroy","IgnoredGlobalFields","Set","symbolList","RecordSymbols","isPathMatch","a","b","length","every","v","i","isNonEnumerableProp","prop","Editables","Map","ReactiveResource","constructor","context","resourceKey","isEmbedded","path","schema","store","objectType","value","type","ResourceSchema","resource","identityField","identity","BoundFns","extensions","legacy","CAUTION_MEGA_DANGER_ZONE_objectExtensions","field","CAUTION_MEGA_DANGER_ZONE_resourceExtensions","fields","method","cacheFields","signals","___notifications","notifications","subscribe","_","key","name","kind","signal","get","Array","isArray","console","warn","join","proxy","peeked","test","Error","arrSignal","objSignal","options","linksMode","_kind","notify","async","editable","Proxy","ownKeys","identityKey","keys","from","unshift","has","target","getOwnPropertyDescriptor","schemaForField","String","writable","enumerable","configurable","id","receiver","_DESTROY","Promise","resolve","_CHECKOUT","_COMMIT","maybeField","undefined","Symbol","toStringTag","fn","lid","set","json","toPrimitive","iterator","includes","propArray","slice","fieldCacheKey","push","modeName","record","assertNeverField","Object","defineProperty","data","cache","willCommit","didCommit","editableRecord","isDestroying","isDestroyed","unsubscribe","identifier","checkout","commit","isResourceSchema","ReactiveResource","Destroy","instantiateRecord","store","identifier","createArgs","schema","resourceSchema","resource","test","Error","legacy","editable","record","resourceKey","modeName","path","field","value","Object","assign","assertReactiveResource","teardownRecord","recordIdentifierFor","createInternalMemo","withSignalStore","getOrSetGlobal","isResourceSchema","Type","getFieldCacheKeyStrict","isNonIdentityCacheableField","Context","Support","WeakMap","ConstructorField","type","name","kind","TypeField","options","key","IdentifierField","DefaultIdentityField","_constructor","record","state","get","set","modelName","test","Error","undefined","BannedKeys","processExtension","extension","features","Map","baseFeatures","prototype","Object","getOwnPropertyNames","includes","decl","getOwnPropertyDescriptor","value","fn","writable","getExt","extCache","extName","ext","String","hasObjectSchema","field","pretendIsResourceOrObjectSchema","processExtensions","schema","scenario","resolvedType","objectExtensions","length","_extensions","fieldCache","_cachedFieldExtensionsByField","has","extensions","arrayExtensions","CAUTION_MEGA_DANGER_ZONE_resourceExtensions","baseExtensions","feature","desc","size","withDefaults","identity","fields","unshift","push","fromIdentity","context","identifier","resourceKey","registerDerivations","registerDerivation","comparableAbstractFieldShape","sourceKey","as","async","inverse","polymorphic","linksMode","resetOnRemoteUpdate","assertConsistentAbstractFieldShape","abstractType","fieldName","existing","incoming","existingShape","incomingShape","source","JSON","stringify","makeCachedDerivation","derivation","memoizedDerivation","prop","signals","signal","SchemaService","constructor","_schemas","_transforms","_hashFns","_derivations","_traits","_modes","_abstractImplementerFields","object","array","resourceTypes","Array","from","keys","hasTrait","resourceHasTrait","resource","trait","traits","transformation","hashFn","original","registerResources","schemas","forEach","registerResource","relationships","attributes","abstractImplementations","implementerFields","contribution","ownField","cacheFields","Set","finalized","internalSchema","getCacheFields","_registerAbstractTypeImplementation","implementer","abstractField","existingImplementer","abstractSchema","legacy","existingAbstractField","registerTrait","internalTrait","assign","registerTransformation","CAUTION_MEGA_DANGER_ZONE_registerExtension","CAUTION_MEGA_DANGER_ZONE_objectExtensions","CAUTION_MEGA_DANGER_ZONE_arrayExtensions","CAUTION_MEGA_DANGER_ZONE_hasExtension","_registerMode","mode","kinds","_kind","registerHashFn","finalizeResource","hasResource","attributesDefinitionFor","console","warn","relationshipsDefinitionFor","doesTypeExist","seen","traitName","walkTrait","mergeMap","cacheKey","debugPath","join","ownPath","add","subtrait","id","base","toApply","checkout","instantiateRecord","teardownRecord","SchemaService","withDefaults","fromIdentity","registerDerivations","commit","Checkout","createRequestSubscription","getRequestState","getPromiseState","getRuntimeConfig","cloneResponseProperties","DOMError","_fetch","fetch","args","FastBoot","require","Error","cloneResponse","response","overrides","props","Response","body","Object","assign","withDateHeader","headers","Headers","set","Date","toUTCString","IS_MAYBE_MIRAGE","override","mirage","undefined","Boolean","window","server","pretender","toString","replace","MUTATION_OPS","Set","ERROR_STATUS_CODE_FOR","Map","Fetch","request","context","test","url","e","isDOMException","name","statusText","status","isRequestError","code","isError","ok","op","isMutationOp","has","setResponse","method","text","reader","getReader","decoder","TextDecoder","isStreaming","hasRequestedStream","stream","TransformStream","writer","writable","getWriter","signal","addEventListener","abort","readable","cancel","setStream","done","value","read","ready","close","decode","write","encode","TextEncoder","errorPayload","JSON","parse","errors","Array","isArray","isDict","get","msg","type","error","AggregateError","replaceAll","content","v","waitFor","peekUniversalTransient","setUniversalTransient","EnableHydration","assertValidRequest","upgradePromise","clearRequestResult","getRequestResult","setPromiseResult","executeNextHandler","IS_CACHE_HANDLER","RequestManager","constructor","options","Object","assign","_pending","Map","_deduped","_handlers","useCache","cacheHandler","_hasCacheHandler","Error","isFrozen","unshift","use","newHandlers","handlers","Array","isArray","forEach","handler","index","request","push","freeze","controller","AbortController","requestId","context","response","stream","hasRequestedStream","id","identifier","requester","store","promise","cacheResult","disableTestWaiter","newPromise","finalPromise","then","result","isError","error","create","instantiateRecord","registerDerivations","SchemaService","teardownRecord","Fetch","RequestManager","DefaultCachePolicy","CacheHandler","Store","recordIdentifierFor","getRuntimeConfig","setIsMaybeMirage","setLogging","cacheKeyFor","globalThis","setWarpDriveLogging","getWarpDriveRuntimeConfig","setWarpDriveIsMaybeMirage","storeFor","setIdentifierGenerationMethod","setIdentifierUpdateMethod","setIdentifierForgetMethod","setIdentifierResetMethod","setKeyInfoForResource","useRecommendedStore","options","StoreKlass","AppStore","constructor","createArgs","requestManager","Object","defineProperty","configurable","enumerable","get","handlers","use","useCache","set","value","lifetimes","policy","apiCacheHardExpires","apiCacheSoftExpires","constraints","headers","Expires","createSchemaService","schema","schemas","registerResources","traits","trait","registerTrait","derivations","derivation","registerDerivation","transformations","transformation","registerTransformation","hashFns","hashFn","registerHashFn","CAUTION_MEGA_DANGER_ZONE_extensions","extension","CAUTION_MEGA_DANGER_ZONE_registerExtension","createCache","capabilities","cache","key","record"],"sources":["../../../src/reactive/-private/document.ts","../../../src/store/-private/debug/utils.ts","../../../src/store/-private/caches/resource-utils.ts","../../../src/store/-private/utils/coerce-id.ts","../../../src/store/-private/utils/normalize-model-name.ts","../../../src/store/-private/managers/cache-key-manager.ts","../../../src/store/-private/managers/cache-capabilities-manager.ts","../../../src/store/-private/caches/instance-cache.ts","../../../src/store/-private/managers/cache-manager.ts","../../../src/store/-private/managers/notification-manager.ts","../../../src/store/-private/record-arrays/-utils.ts","../../../src/reactive/-private/fields/extension.ts","../../../src/store/-private/record-arrays/native-proxy-type-fix.ts","../../../src/store/-private/record-arrays/resource-array.ts","../../../src/store/-private/record-arrays/legacy-live-array.ts","../../../src/store/-private/record-arrays/legacy-query.ts","../../../src/store/-private/managers/record-array-manager.ts","../../../src/store/-private/network/request-cache.ts","../../../../../node_modules/.pnpm/@embroider+macros@1.20.6/node_modules/@embroider/macros/src/addon/es-compat2.js","../../../src/store/-private/store-service.ts","../../../src/store/deprecated/-private.ts","../../../src/store/deprecated/store.ts","../../../src/store/-private/cache-handler/utils.ts","../../../src/store/-private/cache-handler/handler.ts","../../../src/store/-private/utils/is-non-empty-string.ts","../../../src/store/-private/utils/construct-resource.ts","../../../src/store/-private/record-arrays/legacy-many-array.ts","../../../src/reactive/-private/kind/alias-field.ts","../../../src/reactive/-private/fields/managed-array.ts","../../../src/reactive/-private/kind/array-field.ts","../../../src/reactive/-private/kind/attribute-field.ts","../../../src/reactive/-private/fields/get-field-key.ts","../../../src/reactive/-private/kind/belongs-to-field.ts","../../../src/reactive/-private/kind/collection-field.ts","../../../src/reactive/-private/kind/derived-field.ts","../../../src/reactive/-private/kind/generic-field.ts","../../../src/reactive/-private/fields/many-array-manager.ts","../../../src/reactive/-private/kind/has-many-field.ts","../../../src/reactive/-private/kind/hash-field.ts","../../../src/reactive/-private/kind/identity-field.ts","../../../src/reactive/-private/kind/local-field.ts","../../../src/reactive/-private/fields/managed-object.ts","../../../src/reactive/-private/kind/object-field.ts","../../../src/reactive/-private/kind/resource-field.ts","../../../src/reactive/-private/kind/schema-array-field.ts","../../../src/reactive/-private/kind/schema-object-field.ts","../../../src/reactive/-private/default-mode.ts","../../../src/reactive/-private/record.ts","../../../src/reactive/-private/hooks.ts","../../../src/reactive/-private/schema.ts","../../../src/reactive.ts","../../../src/request/-private/fetch.ts","../../../src/request/-private/manager.ts","../../../src/index.ts"],"sourcesContent":["import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { withBrand } from '../../request.ts';\nimport { defineGate, notifyInternalSignal, peekInternalSignal, withSignalStore } from '../../signals/-private.ts';\nimport type { DocumentCacheOperation, UnsubscribeToken } from '../../store/-private/managers/notification-manager.ts';\nimport type { Store } from '../../store/-private/store-service.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport type { RequestKey } from '../../types/identifier.ts';\nimport type { ImmutableRequestInfo, RequestInfo } from '../../types/request.ts';\nimport type { ResourceDocument } from '../../types/spec/document.ts';\nimport type { Link, Meta, PaginationLinks } from '../../types/spec/json-api-raw.ts';\nimport type { Mutable } from '../../types/utils.ts';\nimport { Destroy } from './symbols.ts';\n\nfunction urlFromLink(link: Link): string {\n if (typeof link === 'string') return link;\n return link.href;\n}\n\nexport interface ReactiveDocumentBase<T> {\n /**\n * The links object for this document, if any\n *\n * e.g.\n *\n * ```ts\n * {\n * self: '/articles?page[number]=3',\n * }\n * ```\n *\n * @public\n */\n readonly links?: PaginationLinks;\n\n /**\n * The meta object for this document, if any\n *\n * @public\n */\n readonly meta?: Meta;\n\n /**\n * The RequestKey associated with this document, if any\n *\n * @public\n */\n readonly identifier: RequestKey | null;\n\n /**\n * Fetches the related link for this document, returning a promise that resolves\n * with the document when the request completes. If no related link is present,\n * will fallback to the self link if present\n *\n * @public\n */\n fetch(options?: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T>>;\n\n /**\n * Fetches the next link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * next link.\n *\n * @public\n */\n next(options?: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the prev link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * prev link.\n *\n * @public\n */\n prev(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the first link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * first link.\n *\n * @public\n */\n first(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Fetches the last link for this document, returning a promise that resolves\n * with the new document when the request completes, or null if there is no\n * last link.\n *\n * @public\n */\n last(options: RequestInfo<ReactiveDocument<T>>): Promise<ReactiveDocument<T> | null>;\n\n /**\n * Implemented for `JSON.stringify` support.\n *\n * Returns the JSON representation of the document wrapper.\n *\n * This is a shallow serialization, it does not deeply serialize\n * the document's contents, leaving that to the individual record\n * instances to determine how to do, if at all.\n *\n * @public\n * @return\n */\n toJSON(): object;\n}\n\n/**\n * The variant of {@link ReactiveDocument} returned for a request whose\n * response contained no primary data, e.g. an error response.\n *\n * @public\n */\nexport interface ReactiveErrorDocument<T> extends ReactiveDocumentBase<T> {\n /**\n * The primary data for this document, if any.\n *\n * If this document has no primary data (e.g. because it is an error document)\n * this property will be `undefined`.\n *\n * For collections this will be an array of record instances,\n * for single resource requests it will be a single record instance or null.\n *\n * @public\n */\n readonly data?: undefined;\n\n /**\n * The errors returned by the API for this request, if any\n *\n * @public\n */\n readonly errors: object[];\n}\n\n/**\n * The variant of {@link ReactiveDocument} returned for a request whose\n * response contained primary data.\n *\n * @public\n */\nexport interface ReactiveDataDocument<T> extends ReactiveDocumentBase<T> {\n /**\n * The primary data for this document, if any.\n *\n * If this document has no primary data (e.g. because it is an error document)\n * this property will be `undefined`.\n *\n * For collections this will be an array of record instances,\n * for single resource requests it will be a single record instance or null.\n *\n * @public\n */\n readonly data: T;\n\n /**\n * The errors returned by the API for this request, if any\n *\n * @public\n */\n readonly errors?: undefined;\n}\n\ninterface PrivateReactiveDocument {\n /** @internal */\n _store: Store;\n\n /** @internal */\n _localCache: { document: ResourceDocument; request: ImmutableRequestInfo } | null;\n\n /** @internal */\n _subscription: UnsubscribeToken;\n\n _request<T>(\n this: ReactiveDocumentBase<T>,\n link: keyof PaginationLinks,\n options?: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null>;\n}\nfunction upgradeThis(doc: unknown): asserts doc is PrivateReactiveDocument {}\n\n/**\n * A Document is a class that wraps the response content from a request to the API\n * returned by `Cache.put` or `Cache.peek`, converting ResourceKeys into\n * ReactiveResource instances.\n *\n * It is not directly instantiated by the user, and its properties should not\n * be directly modified. Whether individual properties are mutable or not is\n * determined by the record instance itself.\n *\n * @public\n */\nexport type ReactiveDocument<T> = ReactiveDataDocument<T> | ReactiveErrorDocument<T>;\n\nconst ReactiveDocumentProto = {\n async _request<T>(\n this: ReactiveDocumentBase<T>,\n link: keyof PaginationLinks,\n options: RequestInfo<ReactiveDocument<T>> = withBrand<ReactiveDocument<T>>({ url: '', method: 'GET' })\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n const href = this.links?.[link];\n if (!href) {\n return null;\n }\n\n options.method = options.method || 'GET';\n Object.assign(options, { url: urlFromLink(href) });\n const response = await this._store.request<ReactiveDataDocument<T>>(options);\n\n return response.content;\n },\n\n fetch<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDocument<T>> = withBrand<ReactiveDataDocument<T>>({ url: '', method: 'GET' })\n ): Promise<ReactiveDataDocument<T>> {\n upgradeThis(this);\n assert(`No self or related link`, this.links?.related || this.links?.self);\n options.cacheOptions = options.cacheOptions || {};\n options.cacheOptions.key = this.identifier?.lid;\n return this._request(\n this.links.related ? 'related' : 'self',\n options as RequestInfo<ReactiveDataDocument<T>>\n ) as Promise<ReactiveDataDocument<T>>;\n },\n\n next<T>(\n this: ReactiveDocument<T>,\n options?: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('next', options);\n },\n\n prev<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('prev', options);\n },\n\n first<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('first', options);\n },\n\n last<T>(\n this: ReactiveDocument<T>,\n options: RequestInfo<ReactiveDataDocument<T>>\n ): Promise<ReactiveDataDocument<T> | null> {\n upgradeThis(this);\n return this._request('last', options);\n },\n\n toJSON<T>(this: ReactiveDocument<T>): object {\n upgradeThis(this);\n const data: Mutable<Partial<ReactiveDocument<T>>> = {};\n data.identifier = this.identifier;\n if (this.data !== undefined) {\n data.data = this.data;\n }\n if (this.links !== undefined) {\n data.links = this.links;\n }\n if (this.errors !== undefined) {\n data.errors = this.errors;\n }\n if (this.meta !== undefined) {\n data.meta = this.meta;\n }\n return data;\n },\n\n [Destroy]<T>(this: ReactiveDocument<T>): void {\n upgradeThis(this);\n assert(`Cannot destroy a ReactiveDocument which has already been destroyed`, this._store);\n if (this._subscription) {\n this._store.notifications.unsubscribe(this._subscription);\n // @ts-expect-error\n this._store = null;\n // @ts-expect-error\n this._subscription = null;\n }\n },\n};\n\ndefineGate(ReactiveDocumentProto, 'errors', {\n get<T>(this: ReactiveDocument<T>): object[] | undefined {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n const { document } = this._localCache!;\n if ('errors' in document) {\n return document.errors;\n }\n return;\n }\n\n const doc = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, doc);\n return 'errors' in doc ? doc.errors : undefined;\n },\n});\ndefineGate(ReactiveDocumentProto, 'data', {\n get<T>(this: ReactiveDocument<T>) {\n upgradeThis(this);\n const { identifier, _localCache } = this;\n\n const doc = identifier ? this._store.cache.peek(identifier) : _localCache!.document;\n assert(`No cache data was found for the document '${identifier?.lid ?? '<uncached document>'}'`, doc);\n const data = 'data' in doc ? (doc.data as T | undefined) : undefined;\n\n if (Array.isArray(data)) {\n return identifier\n ? (this._store.recordArrayManager.getCollection({\n source: data.slice() as ResourceKey[],\n requestKey: identifier,\n }) as T)\n : (this._store.recordArrayManager.getCollection({\n source: data.slice() as ResourceKey[],\n }) as T);\n } else if (data) {\n return this._store.peekRecord(data as unknown as ResourceKey) as T;\n } else {\n return data;\n }\n },\n});\ndefineGate(ReactiveDocumentProto, 'links', {\n get<T>(this: ReactiveDocument<T>) {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n return this._localCache!.document.links;\n }\n const data = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, data);\n return data.links;\n },\n});\ndefineGate(ReactiveDocumentProto, 'meta', {\n get<T>(this: ReactiveDocument<T>): Meta | undefined {\n upgradeThis(this);\n const { identifier } = this;\n\n if (!identifier) {\n return this._localCache!.document.meta;\n }\n const data = this._store.cache.peek(identifier);\n assert(`No cache data was found for the document '${identifier.lid}'`, data);\n return data.meta;\n },\n});\n\nexport function createReactiveDocument<T>(\n store: Store,\n cacheKey: RequestKey | null,\n localCache: { document: ResourceDocument; request: ImmutableRequestInfo } | null\n): ReactiveDocument<T> {\n const doc = Object.create(ReactiveDocumentProto) as ReactiveDocument<T> & PrivateReactiveDocument;\n doc._store = store;\n doc._localCache = localCache;\n // @ts-expect-error we are initializing it here\n doc.identifier = cacheKey;\n const signals = withSignalStore(doc);\n\n // TODO if we ever enable auto-cleanup of the cache, we will need to tear this down\n // in a destroy method\n if (cacheKey) {\n doc._subscription = store.notifications.subscribe(cacheKey, (_key: RequestKey, type: DocumentCacheOperation) => {\n switch (type) {\n case 'updated':\n // FIXME in the case of a collection we need to notify it's length\n // and have it recalc\n notifyInternalSignal(peekInternalSignal(signals, 'data'));\n notifyInternalSignal(peekInternalSignal(signals, 'links'));\n notifyInternalSignal(peekInternalSignal(signals, 'meta'));\n notifyInternalSignal(peekInternalSignal(signals, 'errors'));\n break;\n case 'added':\n case 'removed':\n case 'invalidated':\n case 'state':\n break;\n }\n });\n }\n\n return doc;\n}\n","type SCOPE = 'notify' | 'reactive-ui' | 'graph' | 'request' | 'cache';\n\nconst TEXT_COLORS = {\n TEXT: 'inherit',\n notify: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n 'reactive-ui': ['white', 'white', 'inherit', 'magenta', 'inherit'],\n graph: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n request: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n cache: ['white', 'white', 'inherit', 'magenta', 'inherit'],\n};\nconst BG_COLORS = {\n TEXT: 'transparent',\n notify: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n 'reactive-ui': ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n graph: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n request: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n cache: ['dimgray', 'cadetblue', 'transparent', 'transparent', 'transparent'],\n};\nconst NOTIFY_BORDER = {\n TEXT: 0,\n notify: [3, 2, 0, 0, 0],\n 'reactive-ui': [3, 2, 0, 0, 0],\n graph: [3, 2, 0, 0, 0],\n request: [3, 2, 0, 0, 0],\n cache: [3, 2, 0, 0, 0],\n};\n\nconst LIGHT_DARK_ALT: Record<string, string> = {\n lightgreen: 'green',\n green: 'lightgreen',\n};\n\nfunction badge(isLight: boolean, color: string, bgColor: string, border: number) {\n return [\n `color: ${correctColor(isLight, color)}; background-color: ${correctColor(isLight, bgColor)}; padding: ${border}px ${2 * border}px; border-radius: ${border}px;`,\n `color: ${TEXT_COLORS.TEXT}; background-color: ${BG_COLORS.TEXT};`,\n ];\n}\n\nfunction colorForBucket(isLight: boolean, scope: SCOPE, bucket: string) {\n if (scope === 'request') {\n return bucket === 'blocking'\n ? badge(isLight, 'red', 'transparent', 0)\n : bucket === 'cached'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'non-blocking'\n ? badge(isLight, 'orange', 'transparent', 0)\n : badge(isLight, 'gray', 'transparent', 0);\n }\n if (scope === 'notify') {\n return bucket === 'added'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'removed'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n if (scope === 'reactive-ui') {\n return bucket === 'created'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'disconnected'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n if (scope === 'cache') {\n return bucket === 'inserted'\n ? badge(isLight, 'lightgreen', 'transparent', 0)\n : bucket === 'removed'\n ? badge(isLight, 'red', 'transparent', 0)\n : badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]);\n }\n\n return badge(isLight, TEXT_COLORS[scope][3], BG_COLORS[scope][3], NOTIFY_BORDER[scope][3]);\n}\n\n/**\n * Opens a collapsed console group for a `cache` scoped debug message, using\n * `type`/`lid`/`bucket`/`key` to build the colorized group label.\n *\n * @private\n */\nexport function logGroup(scope: 'cache', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Opens a collapsed console group for a `reactive-ui` scoped debug message.\n * The trailing `key` segment is unused for this scope and must be an empty string.\n *\n * @private\n */\nexport function logGroup(\n scope: 'reactive-ui',\n prefix: string,\n type: string,\n lid: string,\n bucket: string,\n key: ''\n): void;\n/**\n * Opens a collapsed console group for a `notify` scoped debug message, using\n * `type`/`lid`/`bucket`/`key` to build the colorized group label.\n *\n * @private\n */\nexport function logGroup(scope: 'notify', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Implementation for {@link logGroup}. Builds the colorized label for the\n * given scope via `_log` and opens it as a collapsed `console.groupCollapsed`.\n *\n * @private\n */\nexport function logGroup(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): void {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(..._log(scope, prefix, subScop1, subScop2, subScop3, subScop4));\n}\n\n/**\n * Logs a colorized, scoped debug message to the console for the `request`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the request being logged.\n *\n * @private\n */\nexport function log(scope: 'request', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `cache`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the cache operation being logged.\n *\n * @private\n */\nexport function log(scope: 'cache', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `reactive-ui`\n * scope. The trailing `key` segment is unused for this scope and must be an empty string.\n *\n * @private\n */\nexport function log(scope: 'reactive-ui', prefix: string, type: string, lid: string, bucket: string, key: ''): void;\n/**\n * Logs a colorized, scoped debug message to the console for the `notify`\n * scope, using `type`/`lid`/`bucket`/`key` to describe the notification being logged.\n *\n * @private\n */\nexport function log(scope: 'notify', prefix: string, type: string, lid: string, bucket: string, key: string): void;\n/**\n * Implementation for {@link log}. Builds the colorized message for the given\n * scope via `_log` and writes it to the console with `console.log`.\n *\n * @private\n */\nexport function log(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): void {\n // oxlint-disable-next-line no-console\n console.log(..._log(scope, prefix, subScop1, subScop2, subScop3, subScop4));\n}\n\nfunction correctColor(isLight: boolean, color: string) {\n if (!isLight) {\n return color;\n }\n return color in LIGHT_DARK_ALT ? LIGHT_DARK_ALT[color] : color;\n}\n\nfunction isLightMode() {\n if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {\n return true;\n }\n return false;\n}\n\nfunction _log(\n scope: SCOPE,\n prefix: string,\n subScop1: string,\n subScop2: string,\n subScop3: string,\n subScop4: string\n): string[] {\n const isLight = isLightMode();\n switch (scope) {\n case 'request':\n case 'reactive-ui':\n case 'notify': {\n const scopePath = prefix ? `[${prefix}] ${scope}` : scope;\n const path = subScop4 ? `${subScop3}.${subScop4}` : subScop3;\n return [\n `%c@warp%c-%cdrive%c %c${scopePath}%c %c${subScop1}%c %c${subScop2}%c %c${path}%c`,\n ...badge(isLight, 'lightgreen', 'transparent', 0),\n ...badge(isLight, 'magenta', 'transparent', 0),\n ...badge(isLight, TEXT_COLORS[scope][0], BG_COLORS[scope][0], NOTIFY_BORDER[scope][0]),\n ...badge(isLight, TEXT_COLORS[scope][1], BG_COLORS[scope][1], NOTIFY_BORDER[scope][1]),\n ...badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]),\n ...colorForBucket(isLight, scope, path),\n ];\n }\n case 'cache': {\n const scopePath = prefix ? `${scope} (${prefix})` : scope;\n return [\n `%c@warp%c-%cdrive%c %c${scopePath}%c %c${subScop1}%c %c${subScop2}%c %c${subScop3}%c %c${subScop4}%c`,\n ...badge(isLight, 'lightgreen', 'transparent', 0),\n ...badge(isLight, 'magenta', 'transparent', 0),\n ...badge(isLight, TEXT_COLORS[scope][0], BG_COLORS[scope][0], NOTIFY_BORDER[scope][0]),\n ...badge(isLight, TEXT_COLORS[scope][1], BG_COLORS[scope][1], NOTIFY_BORDER[scope][1]),\n ...badge(isLight, TEXT_COLORS[scope][2], BG_COLORS[scope][2], NOTIFY_BORDER[scope][2]),\n ...colorForBucket(isLight, scope, subScop3),\n ...badge(isLight, TEXT_COLORS[scope][4], BG_COLORS[scope][4], NOTIFY_BORDER[scope][4]),\n ];\n }\n }\n return [];\n}\n","function isResource(resource: unknown): resource is Record<string, unknown> {\n return Boolean(resource && typeof resource === 'object');\n}\n\nfunction hasProp<T extends string, K extends { [J in T]: string }>(resource: unknown, prop: T): resource is K {\n return Boolean(\n isResource(resource) && prop in resource && typeof resource[prop] === 'string' && resource[prop].length\n );\n}\n\nexport function hasLid(resource: unknown): resource is { lid: string } {\n return hasProp(resource, 'lid');\n}\n\nexport function hasId(resource: unknown): resource is { id: string } {\n return (\n hasProp(resource, 'id') || Boolean(isResource(resource) && 'id' in resource && typeof resource.id === 'number')\n );\n}\n\nexport function hasType(resource: unknown): resource is { type: string } {\n return hasProp(resource, 'type');\n}\n","import { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_NON_STRICT_ID } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\n// Used by the store to normalize IDs entering the store. Despite the fact\n// that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`),\n// it is important that internally we use strings, since IDs may be serialized\n// and lose type information. For example, Ember's router may put a record's\n// ID into the URL, and if we later try to deserialize that URL and find the\n// corresponding record, we will not know if it is a string or a number.\ntype Coercable = string | number | boolean | null | undefined | symbol;\n\n/**\n * Normalizes a resource `id` entering the store to a string (or `null`).\n *\n * When `DEPRECATE_NON_STRICT_ID` is enabled, any non-string, non-nullish id\n * is stringified and a deprecation is issued; `''`/`null`/`undefined` all\n * normalize to `null`. Otherwise, `id` must already be `null` or a\n * non-empty string, which is asserted.\n *\n * @private\n */\nexport function coerceId(id: unknown): string | null {\n if (DEPRECATE_NON_STRICT_ID) {\n let normalized: string | null;\n if (id === null || id === undefined || id === '') {\n normalized = null;\n } else {\n normalized = String(id);\n }\n\n deprecate(\n `The resource id '<${typeof id}> ${String(\n id\n )} ' is not normalized. Update your application code to use '${JSON.stringify(normalized)}' instead.`,\n normalized === id,\n {\n id: 'ember-data:deprecate-non-strict-id',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.3',\n },\n }\n );\n\n return normalized;\n }\n\n assert(\n `Resource IDs must be a non-empty string or null. Received '${String(id)}'.`,\n id === null || (typeof id === 'string' && id.length > 0)\n );\n\n return id;\n}\n\n/**\n * Coerces `id` to a non-empty string, asserting if it is not already a\n * non-empty string or a valid (non-`NaN`) number.\n *\n * Unlike {@link coerceId}, this never returns `null` and does not honor\n * `DEPRECATE_NON_STRICT_ID`.\n *\n * @private\n */\nexport function ensureStringId(id: Coercable): string {\n let normalized: string | null = null;\n if (typeof id === 'string') {\n normalized = id.length > 0 ? id : null;\n } else if (typeof id === 'number' && !isNaN(id)) {\n normalized = String(id);\n }\n\n assert(`Expected id to be a string or number, received ${String(id)}`, normalized !== null);\n\n return normalized;\n}\n","import { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_NON_STRICT_TYPES } from '@warp-drive/core/build-config/deprecations';\n\nimport { dasherize } from '../../../utils/string.ts';\n\n/**\n * Normalizes a resource `type` to its dasherized form, e.g. `myClass` to\n * `my-class`. Re-exported elsewhere as `_deprecatingNormalize`.\n *\n * When `DEPRECATE_NON_STRICT_TYPES` is enabled, dasherizes `type` and issues\n * a deprecation if it was not already normalized. Otherwise, `type` is\n * returned unchanged and callers are expected to have already normalized it.\n *\n * @private\n */\nexport function normalizeModelName(type: string): string {\n if (DEPRECATE_NON_STRICT_TYPES) {\n const result = dasherize(type);\n\n deprecate(\n `The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`,\n result === type,\n {\n id: 'ember-data:deprecate-non-strict-types',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.3',\n },\n }\n );\n\n return result;\n }\n\n return type;\n}\n","import { warn } from '@ember/debug';\n\nimport { getGlobalConfig, macroCondition } from '@embroider/macros';\n\nimport { LOG_IDENTIFIERS } from '@warp-drive/core/build-config/debugging';\nimport { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type {\n ForgetMethod,\n GenerationMethod,\n KeyInfo,\n KeyInfoMethod,\n ResetMethod,\n UpdateMethod,\n} from '../../-types/q/identifier.ts';\nimport { getOrSetGlobal, peekTransient, setTransient } from '../../../types/-private.ts';\nimport {\n CACHE_OWNER,\n type CacheKeyType,\n DEBUG_CLIENT_ORIGINATED,\n DEBUG_KEY_TYPE,\n DEBUG_STALE_CACHE_OWNER,\n type PersistedResourceKey,\n type RequestKey,\n type ResourceKey,\n} from '../../../types/identifier.ts';\nimport type { ImmutableRequestInfo, RequestInfo } from '../../../types/request.ts';\nimport type {\n ExistingResourceIdentifierObject,\n ExistingResourceObject,\n ResourceIdentifierObject,\n} from '../../../types/spec/json-api-raw.ts';\nimport { hasId, hasLid, hasType } from '../caches/resource-utils.ts';\nimport { coerceId } from '../utils/coerce-id.ts';\nimport { normalizeModelName } from '../utils/normalize-model-name.ts';\nimport installPolyfill from '../utils/uuid-polyfill.ts';\n\ntype TypeFromIdentifier<T> = T extends { type: infer U } ? U : string;\n\ntype NarrowIdentifierIfPossible<T> = T extends ExistingResourceIdentifierObject\n ? PersistedResourceKey<TypeFromIdentifier<T>>\n : ResourceKey;\n\n/**\n * Type-guard that returns `true` if the given value is a stable {@link ResourceKey}\n * (as opposed to a {@link RequestKey} or arbitrary, not-yet-stabilized resource data).\n */\nexport function isResourceKey(identifier: unknown): identifier is ResourceKey {\n if (DEBUG) {\n return (\n !!identifier &&\n typeof identifier === 'object' &&\n 'type' in identifier &&\n 'id' in identifier &&\n identifier.type !== '@document' &&\n (identifier as ResourceKey)[CACHE_OWNER] !== undefined\n );\n } else {\n return (identifier as RequestKey).type !== '@document' && (identifier as RequestKey)[CACHE_OWNER] !== undefined;\n }\n}\n\n/**\n * Type-guard that returns `true` if the given value is a stable {@link RequestKey}\n * (as opposed to a {@link ResourceKey} or arbitrary, not-yet-stabilized data).\n */\nexport function isRequestKey(identifier: unknown): identifier is RequestKey {\n if (DEBUG) {\n return (\n !!identifier &&\n typeof identifier === 'object' &&\n 'type' in identifier &&\n !('id' in identifier) &&\n identifier.type === '@document' &&\n (identifier as ResourceKey)[CACHE_OWNER] !== undefined\n );\n } else {\n return (identifier as RequestKey).type === '@document' && (identifier as RequestKey)[CACHE_OWNER] !== undefined;\n }\n}\n\nconst isFastBoot = typeof FastBoot !== 'undefined';\nconst _crypto: Crypto = isFastBoot ? (FastBoot.require('crypto') as Crypto) : globalThis.crypto;\n\nif (macroCondition(getGlobalConfig<{ WarpDrive: { polyfillUUID: boolean } }>().WarpDrive.polyfillUUID)) {\n installPolyfill();\n}\n\nfunction uuidv4(): string {\n assert(\n 'crypto.randomUUID needs to be avaliable. Some browsers incorrectly disallow it in insecure contexts. You maybe want to enable the polyfill: https://github.com/warp-drive-data/warp-drive#randomuuid-polyfill',\n typeof _crypto.randomUUID === 'function'\n );\n return _crypto.randomUUID();\n}\n\nfunction freeze<T>(obj: T): T {\n if (typeof Object.freeze === 'function') {\n return Object.freeze(obj);\n }\n return obj;\n}\n\ninterface KeyOptions {\n lid: IdentifierMap;\n id: IdentifierMap;\n}\ntype TypeMap = { [key: string]: KeyOptions };\n\n// type IdentifierTypeLookup = { all: Set<ResourceKey>; id: Map<string, ResourceKey> };\n// type IdentifiersByType = Map<string, IdentifierTypeLookup>;\ntype IdentifierMap = Map<string, ResourceKey>;\n\ntype StableCache = {\n resources: IdentifierMap;\n documents: Map<string, RequestKey>;\n resourcesByType: TypeMap;\n polymorphicLidBackMap: Map<string, string[]>;\n};\n\nexport type MergeMethod = (\n targetIdentifier: ResourceKey,\n matchedIdentifier: ResourceKey,\n resourceData: unknown\n) => ResourceKey;\n\n/**\n Configures how unique identifier lid strings are generated by @ember-data/store.\n\n This configuration MUST occur prior to the store instance being created.\n\n Takes a method which can expect to receive various data as its first argument\n and the name of a bucket as its second argument.\n\n Currently there are two buckets, 'record' and 'document'.\n\n ### Resource (`Record`) Identity\n\n If the bucket is `record` the method must return a unique (to at-least\n the given bucket) string identifier for the given data as a string to be\n used as the `lid` of an `Identifier` token.\n\n This method will only be called by either `getOrCreateRecordIdentifier` or\n `createIdentifierForNewRecord` when an identifier for the supplied data\n is not already known via `lid` or `type + id` combo and one needs to be\n generated or retrieved from a proprietary cache.\n\n `data` will be the same data argument provided to `getOrCreateRecordIdentifier`\n and in the `createIdentifierForNewRecord` case will be an object with\n only `type` as a key.\n\n ```ts\n import { setIdentifierGenerationMethod } from '@warp-drive/core';\n\n export function initialize(applicationInstance) {\n // note how `count` here is now scoped to the application instance\n // for our generation method by being inside the closure provided\n // by the initialize function\n let count = 0;\n\n setIdentifierGenerationMethod((resource, bucket) => {\n return resource.lid || `my-key-${count++}`;\n });\n }\n\n export default {\n name: 'configure-ember-data-identifiers',\n initialize\n };\n ```\n\n ### Document Identity\n\n If the bucket is `document` the method will receive the associated\n immutable `request` passed to `store.request` as its first argument\n and should return a unique string for the given request if the document\n should be cached, and `null` if it should not be cached.\n\n Note, the request result will still be passed to the cache via `Cache.put`,\n but caches should take this as a signal that the document should not itself\n be cached, while its contents may still be used to update other cache state.\n\n The presence of `cacheOptions.key` on the request will take precedence\n for the document cache key, and this method will not be called if it is\n present.\n\n The default method implementation for this bucket is to return `null`\n for all requests whose method is not `GET`, and to return the `url` for\n those where it is.\n\n This means that queries via `POST` MUST provide `cacheOptions.key` or\n implement this hook.\n\n ⚠️ Caution: Requests that do not have a `method` assigned are assumed to be `GET`\n\n @public\n*/\nexport function setIdentifierGenerationMethod(method: GenerationMethod | null): void {\n setTransient('configuredGenerationMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache encounters new resource\n data for an existing resource.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierUpdateMethod } from '@warp-drive/core';\n ```\n\n Takes a method which can expect to receive an existing `Identifier` alongside\n some new data to consider as a second argument. This is an opportunity\n for secondary lookup tables and caches associated with the identifier\n to be amended.\n\n This method is called everytime `updateRecordIdentifier` is called and\n with the same arguments. It provides the opportunity to update secondary\n lookup tables for existing identifiers.\n\n It will always be called after an identifier created with `createIdentifierForNewRecord`\n has been committed, or after an update to the `record` a `RecordIdentifier`\n is assigned to has been committed. Committed here meaning that the server\n has acknowledged the update (for instance after a call to `.save()`)\n\n If `id` has not previously existed, it will be assigned to the `Identifier`\n prior to this `UpdateMethod` being called; however, calls to the parent method\n `updateRecordIdentifier` that attempt to change the `id` or calling update\n without providing an `id` when one is missing will throw an error.\n\n @public\n*/\nexport function setIdentifierUpdateMethod(method: UpdateMethod | null): void {\n setTransient('configuredUpdateMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is going to release an identifier.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierForgetMethod } from '@warp-drive/core';\n ```\n\n Takes method which can expect to receive an existing `Identifier` that should be eliminated\n from any secondary lookup tables or caches that the user has populated for it.\n\n @public\n*/\nexport function setIdentifierForgetMethod(method: ForgetMethod | null): void {\n setTransient('configuredForgetMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is being torn down.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setIdentifierResetMethod } from '@warp-drive/core';\n ```\n\n Takes a method which can expect to be called when the parent application is destroyed.\n\n If you have properly used a WeakMap to encapsulate the state of your customization\n to the application instance, you may not need to implement the `resetMethod`.\n\n @public\n*/\nexport function setIdentifierResetMethod(method: ResetMethod | null): void {\n setTransient('configuredResetMethod', method);\n}\n\n/**\n Configure a callback for when the identifier cache is generating a new\n ResourceKey for a resource.\n\n This method controls the `type` and `id` that will be assigned to the\n `ResourceKey` that is created.\n\n This configuration MUST occur prior to the store instance being created.\n\n ```js\n import { setKeyInfoForResource } from '@warp-drive/core';\n ```\n\n @public\n */\nexport function setKeyInfoForResource(method: KeyInfoMethod | null): void {\n setTransient('configuredKeyInfoMethod', method);\n}\n\nfunction assertIsRequest(request: unknown): asserts request is ImmutableRequestInfo {\n return;\n}\n\n// Map<type, Map<id, lid>>\ntype TypeIdMap = Map<string, Map<string, string>>;\n// TODO can we just delete this?\nconst NEW_IDENTIFIERS: TypeIdMap = new Map();\n// TODO @runspired maybe needs peekTransient ?\nlet IDENTIFIER_CACHE_ID = 0;\n\nfunction updateTypeIdMapping(typeMap: TypeIdMap, identifier: ResourceKey, id: string): void {\n let idMap = typeMap.get(identifier.type);\n if (!idMap) {\n idMap = new Map();\n typeMap.set(identifier.type, idMap);\n }\n idMap.set(id, identifier.lid);\n}\n\nfunction defaultUpdateMethod(identifier: ResourceKey, data: unknown, bucket: 'record'): void;\nfunction defaultUpdateMethod(identifier: RequestKey, data: unknown, bucket: 'document'): void;\nfunction defaultUpdateMethod(identifier: { lid: string }, newData: unknown, bucket: never): void;\nfunction defaultUpdateMethod(\n identifier: RequestKey | ResourceKey | { lid: string },\n data: unknown,\n bucket: 'record' | 'document'\n): void {\n if (bucket === 'record') {\n assert(`Expected identifier to be a ResourceKey`, isResourceKey(identifier));\n if (!identifier.id && hasId(data)) {\n updateTypeIdMapping(NEW_IDENTIFIERS, identifier, data.id);\n }\n }\n}\n\nfunction defaultKeyInfoMethod(resource: unknown, known: ResourceKey | null): KeyInfo {\n // TODO RFC something to make this configurable\n const id = hasId(resource) ? coerceId(resource.id) : null;\n const type = hasType(resource) ? normalizeModelName(resource.type) : known ? known.type : null;\n\n assert(`Expected keyInfoForResource to provide a type for the resource`, type);\n\n return { type, id };\n}\n\nfunction defaultGenerationMethod(data: unknown, bucket: CacheKeyType): string | null {\n if (bucket === 'record') {\n if (hasLid(data)) {\n return data.lid;\n }\n\n assert(`Cannot generate an identifier for a resource without a type`, hasType(data));\n\n if (hasId(data)) {\n const type = normalizeModelName(data.type);\n const lid = NEW_IDENTIFIERS.get(type)?.get(data.id);\n\n return lid || `@lid:${type}-${data.id}`;\n }\n\n return uuidv4();\n } else if (bucket === 'document') {\n assertIsRequest(data);\n if (!data.url) {\n return null;\n }\n if (!data.method || data.method.toUpperCase() === 'GET') {\n return data.url;\n }\n return null;\n }\n assert(`Unknown bucket ${bucket as string}`, false);\n}\n\nfunction defaultEmptyCallback(...args: unknown[]): void {}\nfunction defaultMergeMethod(a: ResourceKey, _b: ResourceKey, _c: unknown): ResourceKey {\n return a;\n}\n\nlet DEBUG_MAP: WeakMap<ResourceKey, ResourceKey>;\nif (DEBUG) {\n DEBUG_MAP = getOrSetGlobal('DEBUG_MAP', new WeakMap<ResourceKey, ResourceKey>());\n}\n\n/**\n * Each instance of {@link Store} receives a unique instance of a CacheKeyManager.\n *\n * This cache is responsible for assigning or retrieving the unique identify\n * for arbitrary resource data encountered by the store. Data representing\n * a unique resource or record should always be represented by the same\n * identifier.\n *\n * It can be configured by consuming applications.\n *\n * @hideconstructor\n * @public\n */\nexport class CacheKeyManager {\n /** @internal */\n _cache: StableCache;\n /** @internal */\n declare private _generate: GenerationMethod;\n /** @internal */\n declare private _update: UpdateMethod;\n /** @internal */\n declare private _forget: ForgetMethod;\n /** @internal */\n declare private _reset: ResetMethod;\n /** @internal */\n declare private _merge: MergeMethod;\n /** @internal */\n declare private _keyInfoForResource: KeyInfoMethod;\n /** @internal */\n declare private _id: number;\n\n constructor() {\n // we cache the user configuredGenerationMethod at init because it must\n // be configured prior and is not allowed to be changed\n this._generate =\n peekTransient<GenerationMethod>('configuredGenerationMethod') || (defaultGenerationMethod as GenerationMethod);\n this._update = peekTransient<UpdateMethod>('configuredUpdateMethod') || defaultUpdateMethod;\n this._forget = peekTransient<ForgetMethod>('configuredForgetMethod') || defaultEmptyCallback;\n this._reset = peekTransient<ResetMethod>('configuredResetMethod') || defaultEmptyCallback;\n this._merge = defaultMergeMethod;\n this._keyInfoForResource = peekTransient<KeyInfoMethod>('configuredKeyInfoMethod') || defaultKeyInfoMethod;\n this._id = IDENTIFIER_CACHE_ID++;\n\n this._cache = {\n resources: new Map<string, ResourceKey>(),\n resourcesByType: Object.create(null) as TypeMap,\n documents: new Map<string, RequestKey>(),\n polymorphicLidBackMap: new Map<string, string[]>(),\n };\n }\n\n /**\n * Internal hook to allow management of merge conflicts with identifiers.\n *\n * we allow late binding of this private internal merge so that\n * the cache can insert itself here to handle elimination of duplicates\n *\n * @internal\n */\n __configureMerge(method: MergeMethod | null): void {\n this._merge = method || defaultMergeMethod;\n }\n\n /** @internal */\n upgradeIdentifier(resource: { type: string; id: string | null; lid?: string }): ResourceKey {\n return this._getRecordIdentifier(resource, 2);\n }\n\n /** @internal */\n private _getRecordIdentifier(\n resource: { type: string; id: string | null; lid?: string },\n shouldGenerate: 2\n ): ResourceKey;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 1): ResourceKey;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 0): ResourceKey | undefined;\n /** @internal */\n private _getRecordIdentifier(resource: unknown, shouldGenerate: 0 | 1 | 2): ResourceKey | undefined {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(`Identifiers: ${shouldGenerate ? 'Generating' : 'Peeking'} Identifier`, resource);\n }\n // short circuit if we're already the stable version\n if (isResourceKey(resource)) {\n if (DEBUG) {\n // TODO should we instead just treat this case as a new generation skipping the short circuit?\n if (!this._cache.resources.has(resource.lid) || this._cache.resources.get(resource.lid) !== resource) {\n throw new Error(`The supplied identifier ${JSON.stringify(resource)} does not belong to this store instance`);\n }\n }\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: cache HIT - Stable ${resource.lid}`);\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return resource;\n }\n\n // the resource is unknown, ask the application to identify this data for us\n const lid = this._generate(resource, 'record');\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: ${lid ? 'no ' : ''}lid ${lid ? lid + ' ' : ''}determined for resource`, resource);\n }\n\n let identifier: ResourceKey | null = /*#__NOINLINE__*/ getIdentifierFromLid(this._cache, lid, resource);\n if (identifier !== null) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return identifier;\n }\n\n if (shouldGenerate === 0) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n return;\n }\n\n // if we still don't have an identifier, time to generate one\n if (shouldGenerate === 2) {\n (resource as ResourceKey).lid = lid;\n (resource as ResourceKey)[CACHE_OWNER] = this._id;\n identifier = /*#__NOINLINE__*/ makeResourceKey(resource as ResourceKey, 'record', false);\n } else {\n // we lie a bit here as a memory optimization\n const keyInfo = this._keyInfoForResource(resource, null) as ResourceKey;\n keyInfo.lid = lid;\n keyInfo[CACHE_OWNER] = this._id;\n identifier = /*#__NOINLINE__*/ makeResourceKey(keyInfo, 'record', false);\n }\n\n addResourceToCache(this._cache, identifier);\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n\n return identifier;\n }\n\n /**\n * allows us to peek without generating when needed\n * useful for the \"create\" case when we need to see if\n * we are accidentally overwritting something\n *\n * @private\n */\n peekResourceKey(resource: ResourceIdentifierObject): ResourceKey | undefined {\n return this._getRecordIdentifier(resource, 0);\n }\n\n /**\n * Peeks the {@link RequestKey} for the given {@link RequestInfo}, but will not\n * create one if none has been previously generated.\n *\n * @public\n */\n peekRequestKey(request: RequestInfo): RequestKey | null {\n let cacheKey: string | null | undefined = request.cacheOptions?.key;\n\n if (!cacheKey) {\n cacheKey = this._generate(request, 'document');\n }\n\n if (!cacheKey) {\n return null;\n }\n\n const identifier = this._cache.documents.get(cacheKey);\n return identifier ?? null;\n }\n\n /**\n * Returns the {@link RequestKey} for the given {@link RequestInfo} if the request is\n * considered cacheable. For cacheable requests, this method will create\n * a RequestKey if none is found.\n *\n * A `null` response indicates the request cannot/will not be cached,\n * generally this means either\n *\n * - {@link RequestInfo.cacheOptions.key} is not present on the `RequestInfo`\n * - the request's method is `GET` but it has no `url`\n *\n * Generally you should not seek to cache requests that are not idempotent\n * or have side effects, such as mutations that create, update or delete\n * a resource.\n *\n * @public\n */\n getOrCreateDocumentIdentifier(request: RequestInfo): RequestKey | null {\n let cacheKey: string | null | undefined = request.cacheOptions?.key;\n\n if (!cacheKey) {\n cacheKey = this._generate(request, 'document');\n }\n\n if (!cacheKey) {\n return null;\n }\n\n let identifier = this._cache.documents.get(cacheKey);\n\n if (identifier === undefined) {\n identifier = { lid: cacheKey, type: '@document', [CACHE_OWNER]: this._id };\n if (DEBUG) {\n Object.freeze(identifier);\n }\n this._cache.documents.set(cacheKey, identifier);\n }\n\n return identifier;\n }\n\n /**\n Returns the {@link ResourceKey} for the given Resource, creates one if it does not yet exist.\n\n Specifically this means that we:\n\n - validate the `id` `type` and `lid` combo against known identifiers\n - return an object with an `lid` that is stable (repeated calls with the same\n `id` + `type` or `lid` will return the same `lid` value)\n - this referential stability of the object itself is guaranteed\n\n @public\n */\n getOrCreateRecordIdentifier<T>(resource: T): NarrowIdentifierIfPossible<T> {\n return this._getRecordIdentifier(resource as unknown, 1) as NarrowIdentifierIfPossible<T>;\n }\n\n /**\n Returns a new Identifier for the supplied data. Call this method to generate\n an identifier when a new resource is being created local to the client and\n potentially does not have an `id`.\n\n Delegates generation to the user supplied `GenerateMethod` if one has been provided\n with the signature `generateMethod({ type }, 'record')`.\n\n @public\n */\n createIdentifierForNewRecord(data: { type: string; id?: string | null; lid?: string }): ResourceKey {\n const newLid = this._generate(data, 'record');\n const identifier = /*#__NOINLINE__*/ makeResourceKey(\n { id: data.id || null, type: data.type, lid: newLid, [CACHE_OWNER]: this._id },\n 'record',\n true\n );\n\n // populate our unique table\n if (DEBUG) {\n if (this._cache.resources.has(identifier.lid)) {\n throw new Error(`The lid generated for the new record is not unique as it matches an existing identifier`);\n }\n }\n\n /*#__NOINLINE__*/ addResourceToCache(this._cache, identifier);\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: created identifier ${String(identifier)} for newly generated resource`, data);\n }\n\n return identifier;\n }\n\n /**\n Provides the opportunity to update secondary lookup tables for existing identifiers\n Called after an identifier created with `createIdentifierForNewRecord` has been\n committed.\n\n Assigned `id` to an `Identifier` if `id` has not previously existed; however,\n attempting to change the `id` or calling update without providing an `id` when\n one is missing will throw an error.\n\n - sets `id` (if `id` was previously `null`)\n - `lid` and `type` MUST NOT be altered post creation\n\n If a merge occurs, it is possible the returned identifier does not match the originally\n provided identifier. In this case the abandoned identifier will go through the usual\n `forgetRecordIdentifier` codepaths.\n\n @public\n */\n // FIXME audit usage\n updateRecordIdentifier(identifierObject: ResourceKey, data: unknown): ResourceKey {\n let identifier = this.getOrCreateRecordIdentifier(identifierObject);\n\n const keyInfo = this._keyInfoForResource(data, identifier);\n let existingIdentifier = /*#__NOINLINE__*/ detectMerge(this._cache, keyInfo, identifier, data);\n const hadLid = hasLid(data);\n\n if (!existingIdentifier) {\n // If the incoming type does not match the identifier type, we need to create an identifier for the incoming\n // data so we can merge the incoming data with the existing identifier, see #7325 and #7363\n if (identifier.type !== keyInfo.type) {\n if (hadLid) {\n // Strip the lid to ensure we force a new identifier creation\n delete (data as { lid?: string }).lid;\n }\n existingIdentifier = this.getOrCreateRecordIdentifier(data);\n }\n }\n\n if (existingIdentifier) {\n const generatedIdentifier = identifier;\n identifier = this._mergeRecordIdentifiers(keyInfo, generatedIdentifier, existingIdentifier, data);\n\n // make sure that the `lid` on the data we are processing matches the lid we kept\n if (hadLid) {\n data.lid = identifier.lid;\n }\n\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Identifiers: merged identifiers ${generatedIdentifier.lid} and ${existingIdentifier.lid} for resource into ${identifier.lid}`,\n data\n );\n }\n }\n\n const id = identifier.id;\n /*#__NOINLINE__*/ performRecordIdentifierUpdate(identifier, keyInfo, data, this._update);\n const newId = identifier.id;\n\n // add to our own secondary lookup table\n if (id !== newId && newId !== null) {\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Identifiers: updated id for identifier ${identifier.lid} from '${String(id)}' to '${String(\n newId\n )}' for resource`,\n data\n );\n }\n\n const typeSet = this._cache.resourcesByType[identifier.type];\n assert(`Expected to find a typeSet for ${identifier.type}`, typeSet);\n typeSet.id.set(newId, identifier);\n\n if (id !== null) {\n typeSet.id.delete(id);\n }\n } else if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: updated identifier ${identifier.lid} resource`, data);\n }\n\n return identifier;\n }\n\n /**\n * @internal\n */\n _mergeRecordIdentifiers(\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n existingIdentifier: ResourceKey,\n data: unknown\n ): ResourceKey {\n assert(`Expected keyInfo to contain an id`, hasId(keyInfo));\n // delegate determining which identifier to keep to the configured MergeMethod\n const kept = this._merge(identifier, existingIdentifier, data);\n const abandoned = kept === identifier ? existingIdentifier : identifier;\n\n // get any backreferences before forgetting this identifier, as it will be removed from the cache\n // and we will no longer be able to find them\n const abandonedBackReferences = this._cache.polymorphicLidBackMap.get(abandoned.lid);\n // delete the backreferences for the abandoned identifier so that forgetRecordIdentifier\n // does not try to remove them.\n if (abandonedBackReferences) this._cache.polymorphicLidBackMap.delete(abandoned.lid);\n\n // cleanup the identifier we no longer need\n this.forgetRecordIdentifier(abandoned);\n\n // ensure a secondary cache entry for the original lid for the abandoned identifier\n this._cache.resources.set(abandoned.lid, kept);\n\n // backReferences let us know which other identifiers are pointing at this identifier\n // so we can delete them later if we forget this identifier\n const keptBackReferences = this._cache.polymorphicLidBackMap.get(kept.lid) ?? [];\n keptBackReferences.push(abandoned.lid);\n\n // update the backreferences from the abandoned identifier to be for the kept identifier\n if (abandonedBackReferences) {\n abandonedBackReferences.forEach((lid) => {\n keptBackReferences.push(lid);\n this._cache.resources.set(lid, kept);\n });\n }\n\n this._cache.polymorphicLidBackMap.set(kept.lid, keptBackReferences);\n return kept;\n }\n\n /**\n Provides the opportunity to eliminate an identifier from secondary lookup tables\n as well as eliminates it from ember-data's own lookup tables and book keeping.\n\n Useful when a record has been deleted and the deletion has been persisted and\n we do not care about the record anymore. Especially useful when an `id` of a\n deleted record might be reused later for a new record.\n\n @public\n */\n // FIXME audit usage\n forgetRecordIdentifier(identifierObject: ResourceKey): void {\n const identifier = this.getOrCreateRecordIdentifier(identifierObject);\n const typeSet = this._cache.resourcesByType[identifier.type];\n assert(`Expected to find a typeSet for ${identifier.type}`, typeSet);\n\n if (identifier.id !== null) {\n typeSet.id.delete(identifier.id);\n }\n this._cache.resources.delete(identifier.lid);\n typeSet.lid.delete(identifier.lid);\n\n const backReferences = this._cache.polymorphicLidBackMap.get(identifier.lid);\n if (backReferences) {\n backReferences.forEach((lid) => {\n this._cache.resources.delete(lid);\n });\n this._cache.polymorphicLidBackMap.delete(identifier.lid);\n }\n\n if (DEBUG) {\n identifier[DEBUG_STALE_CACHE_OWNER] = identifier[CACHE_OWNER];\n }\n identifier[CACHE_OWNER] = undefined;\n this._forget(identifier, 'record');\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: released identifier ${identifierObject.lid}`);\n }\n }\n\n /** @internal */\n destroy(): void {\n NEW_IDENTIFIERS.clear();\n this._reset();\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateCacheKeyManager extends CacheKeyManager {\n _cache: StableCache;\n /**\n * Internal hook to allow management of merge conflicts with identifiers.\n *\n * we allow late binding of this private internal merge so that\n * the cache can insert itself here to handle elimination of duplicates\n */\n __configureMerge(method: MergeMethod | null): void;\n _mergeRecordIdentifiers(\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n existingIdentifier: ResourceKey,\n data: unknown\n ): ResourceKey;\n destroy(): void;\n}\n\nfunction makeResourceKey(\n recordIdentifier: {\n type: string;\n id: string | null;\n lid: string;\n [CACHE_OWNER]: number | undefined;\n },\n bucket: CacheKeyType,\n clientOriginated: boolean\n): ResourceKey {\n if (DEBUG) {\n // we enforce immutability in dev\n // but preserve our ability to do controlled updates to the reference\n let wrapper = {\n type: recordIdentifier.type,\n lid: recordIdentifier.lid,\n get id() {\n return recordIdentifier.id;\n },\n } as ResourceKey;\n const proto = {\n get [CACHE_OWNER](): number | undefined {\n return recordIdentifier[CACHE_OWNER];\n },\n set [CACHE_OWNER](value: number) {\n recordIdentifier[CACHE_OWNER] = value;\n },\n get [DEBUG_STALE_CACHE_OWNER](): number | undefined {\n return (recordIdentifier as ResourceKey)[DEBUG_STALE_CACHE_OWNER];\n },\n set [DEBUG_STALE_CACHE_OWNER](value: number | undefined) {\n (recordIdentifier as ResourceKey)[DEBUG_STALE_CACHE_OWNER] = value;\n },\n get [DEBUG_CLIENT_ORIGINATED]() {\n return clientOriginated;\n },\n get [DEBUG_KEY_TYPE]() {\n return bucket;\n },\n };\n Object.defineProperty(proto, 'toString', {\n enumerable: false,\n value: () => {\n const { type, id, lid } = recordIdentifier;\n return `${clientOriginated ? '[CLIENT_ORIGINATED] ' : ''}${String(type)}:${String(id)} (${lid})`;\n },\n });\n Object.defineProperty(proto, 'toJSON', {\n enumerable: false,\n value: () => {\n const { type, id, lid } = recordIdentifier;\n return { type, id, lid };\n },\n });\n Object.setPrototypeOf(wrapper, proto);\n DEBUG_MAP.set(wrapper, recordIdentifier);\n wrapper = freeze(wrapper);\n return wrapper;\n }\n\n return recordIdentifier;\n}\n\nfunction performRecordIdentifierUpdate(\n identifier: ResourceKey,\n keyInfo: KeyInfo,\n data: unknown,\n updateFn: UpdateMethod\n) {\n if (DEBUG) {\n const { id, type } = keyInfo;\n\n // get the mutable instance behind our proxy wrapper\n const wrapper = identifier;\n identifier = DEBUG_MAP.get(wrapper)!;\n\n if (hasLid(data)) {\n const lid = data.lid;\n if (lid !== identifier.lid) {\n throw new Error(\n `The 'lid' for a ResourceKey cannot be updated once it has been created. Attempted to set lid for '${wrapper.lid}' to '${lid}'.`\n );\n }\n }\n\n if (id && identifier.id !== null && identifier.id !== id) {\n // here we warn and ignore, as this may be a mistake, but we allow the user\n // to have multiple cache-keys pointing at a single lid so we cannot error\n warn(\n `The 'id' for a ResourceKey should not be updated once it has been set. Attempted to set id for '${wrapper.lid}' to '${id}'.`,\n false,\n { id: 'ember-data:multiple-ids-for-identifier' }\n );\n }\n\n // TODO consider just ignoring here to allow flexible polymorphic support\n if (type && type !== identifier.type) {\n throw new Error(\n `The 'type' for a ResourceKey cannot be updated once it has been set. Attempted to set type for '${wrapper.lid}' to '${type}'.`\n );\n }\n\n updateFn(wrapper, data, 'record');\n } else {\n updateFn(identifier, data, 'record');\n }\n\n // upgrade the ID, this is a \"one time only\" ability\n // for the multiple-cache-key scenario we \"could\"\n // use a heuristic to guess the best id for display\n // (usually when `data.id` is available and `data.attributes` is not)\n if ((data as ExistingResourceObject).id !== undefined) {\n identifier.id = coerceId((data as ExistingResourceObject).id);\n }\n}\n\nfunction detectMerge(\n cache: StableCache,\n keyInfo: KeyInfo,\n identifier: ResourceKey,\n data: unknown\n): ResourceKey | false {\n const newId = keyInfo.id;\n const { id, type, lid } = identifier;\n const typeSet = cache.resourcesByType[identifier.type];\n\n // if the IDs are present but do not match\n // then check if we have an existing identifier\n // for the newer ID.\n if (id !== null && id !== newId && newId !== null) {\n const existingIdentifier = typeSet && typeSet.id.get(newId);\n\n return existingIdentifier !== undefined ? existingIdentifier : false;\n } else {\n const newType = keyInfo.type;\n\n // If the ids and type are the same but lid is not the same, we should trigger a merge of the identifiers\n // we trigger a merge of the identifiers\n // though probably we should just throw an error here\n if (id !== null && id === newId && newType === type && hasLid(data) && data.lid !== lid) {\n return getIdentifierFromLid(cache, data.lid, data) || false;\n\n // If the lids are the same, and ids are the same, but types are different we should trigger a merge of the identifiers\n } else if (id !== null && id === newId && newType && newType !== type && hasLid(data) && data.lid === lid) {\n const newTypeSet = cache.resourcesByType[newType];\n const existingIdentifier = newTypeSet && newTypeSet.id.get(newId);\n\n return existingIdentifier !== undefined ? existingIdentifier : false;\n }\n }\n\n return false;\n}\n\nfunction getIdentifierFromLid(cache: StableCache, lid: string, resource: unknown): ResourceKey | null {\n const identifier = cache.resources.get(lid);\n if (LOG_IDENTIFIERS) {\n // oxlint-disable-next-line no-console\n console.log(`Identifiers: cache ${identifier ? 'HIT' : 'MISS'} - Non-Stable ${lid}`, resource);\n }\n return identifier || null;\n}\n\nfunction addResourceToCache(cache: StableCache, identifier: ResourceKey): void {\n cache.resources.set(identifier.lid, identifier);\n let typeSet = cache.resourcesByType[identifier.type];\n\n if (!typeSet) {\n typeSet = { lid: new Map(), id: new Map() };\n cache.resourcesByType[identifier.type] = typeSet;\n }\n\n typeSet.lid.set(identifier.lid, identifier);\n if (identifier.id) {\n typeSet.id.set(identifier.id, identifier);\n }\n}\n","import { ENABLE_LEGACY_SCHEMA_SERVICE } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { CacheCapabilitiesManager as StoreWrapper } from '../../-types/q/cache-capabilities-manager.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { SchemaService } from '../../../types/schema/schema-service.ts';\nimport type { PrivateStore, Store } from '../store-service.ts';\nimport type { CacheKeyManager } from './cache-key-manager.ts';\nimport { isRequestKey, isResourceKey } from './cache-key-manager.ts';\nimport type { NotificationChannel, NotificationType, NotifyKeys } from './notification-manager.ts';\n\nexport interface CacheCapabilitiesManager {\n /** @deprecated - use {@link CacheCapabilitiesManager.schema} */\n getSchemaDefinitionService(): SchemaService;\n}\nexport class CacheCapabilitiesManager implements StoreWrapper {\n /** @internal */\n declare private _willNotify: boolean;\n\n /** @internal */\n declare private _pendingNotifies: Map<ResourceKey, Map<string, Set<NotificationChannel | undefined>>>;\n\n /** @internal */\n declare _store: Store;\n\n constructor(_store: Store) {\n this._store = _store;\n this._willNotify = false;\n this._pendingNotifies = new Map();\n }\n\n get cacheKeyManager(): CacheKeyManager {\n return this._store.cacheKeyManager;\n }\n\n /** @deprecated use {@link CacheCapabilitiesManager.cacheKeyManager} */\n get identifierCache(): CacheKeyManager {\n return this.cacheKeyManager;\n }\n\n /** @internal */\n private _scheduleNotification(identifier: ResourceKey, key: string, channel: NotificationChannel | undefined): void {\n let pending = this._pendingNotifies.get(identifier);\n\n if (!pending) {\n pending = new Map();\n this._pendingNotifies.set(identifier, pending);\n }\n let channels = pending.get(key);\n if (!channels) {\n channels = new Set();\n pending.set(key, channels);\n }\n channels.add(channel);\n\n if (this._willNotify === true) {\n return;\n }\n\n this._willNotify = true;\n // it's possible a cache adhoc notifies us,\n // in which case we sync flush\n if (this._store._cbs) {\n this._store._schedule('notify', () => this._flushNotifications());\n } else {\n // TODO @runspired determine if relationship mutations should schedule\n // into join/run vs immediate flush\n this._flushNotifications();\n }\n }\n\n /** @internal */\n private _flushNotifications(): void {\n if (this._willNotify === false) {\n return;\n }\n\n const pending = this._pendingNotifies;\n this._pendingNotifies = new Map();\n this._willNotify = false;\n\n // deliver all relationship keys pending for a given identifier as a single\n // batch instead of one `notify` call per key: subscribers still receive one\n // notification per key (in Set-insertion order), but the per-call overhead\n // (subscriber lookups, buffer scheduling, etc) that `notify` would otherwise\n // repeat for every key is paid only once per identifier. This mirrors the\n // same N*M concern `attributes` notifications have (the json-api Cache\n // batches a record's changed attribute keys into a single `notifyChange`\n // Set for the same reason): a single push/mutation pass can dirty many\n // relationships across many records at once, and each of those records\n // funnels through this same per-identifier `pending` Set.\n //\n // Keys touched with more than one distinct channel during this window\n // (e.g. once unscoped and once on `'local'`) are re-grouped by channel\n // below so that each distinct channel is still handed off to `notify` as\n // a single `Set<string>` batch call (never one call per key) -- `notify`'s\n // own buffer (see NotificationManager) is what dedupes/coalesces these\n // per-channel batches back down to a single delivery per subscriber.\n pending.forEach((channelsByKey, identifier) => {\n const keysByChannel = new Map<NotificationChannel | undefined, Set<string>>();\n channelsByKey.forEach((channels, key) => {\n channels.forEach((channel) => {\n let keys = keysByChannel.get(channel);\n if (!keys) {\n keys = new Set();\n keysByChannel.set(channel, keys);\n }\n keys.add(key);\n });\n });\n keysByChannel.forEach((keys, channel) => {\n this._store.notifications.notify(identifier, 'relationships', keys, channel);\n });\n });\n }\n\n notifyChange(identifier: ResourceKey, namespace: 'added' | 'removed', key: null): void;\n notifyChange(identifier: RequestKey, namespace: 'added' | 'updated' | 'removed', key: null): void;\n notifyChange(\n identifier: ResourceKey,\n namespace: 'attributes',\n key: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): void;\n notifyChange(\n identifier: ResourceKey,\n namespace: NotificationType,\n key: string | null,\n channel?: NotificationChannel\n ): void;\n notifyChange(\n identifier: ResourceKey | RequestKey,\n namespace: NotificationType | 'added' | 'removed' | 'updated',\n key: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier) || isRequestKey(identifier));\n\n // TODO do we still get value from this?\n if (namespace === 'relationships' && key) {\n assert(`Expected a single relationship key`, typeof key === 'string');\n this._scheduleNotification(identifier as ResourceKey, key, channel);\n return;\n }\n\n // @ts-expect-error\n this._store.notifications.notify(identifier, namespace, key, channel);\n }\n\n get schema(): SchemaService {\n return this._store.schema;\n }\n\n setRecordId(identifier: ResourceKey, id: string): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier));\n this._store._instanceCache.setRecordId(identifier, id);\n }\n\n hasRecord(identifier: ResourceKey): boolean {\n return Boolean(this._store._instanceCache.peek(identifier));\n }\n\n disconnectRecord(identifier: ResourceKey): void {\n assert(`Expected a stable identifier`, isResourceKey(identifier));\n this._store._instanceCache.disconnect(identifier);\n this._pendingNotifies.delete(identifier);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateCacheCapabilitiesManager extends CacheCapabilitiesManager {\n _store: PrivateStore;\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n CacheCapabilitiesManager.prototype.getSchemaDefinitionService = function () {\n // FIXME add deprecation for this\n return this.schema;\n };\n}\n\n/**\n * Upgrade the type for {@link CacheCapabilitiesManager} to {@link PrivateCacheCapabilitiesManager}.\n *\n * @private\n */\nexport function assertPrivateCapabilities(manager: unknown): asserts manager is PrivateCacheCapabilitiesManager {}\n","import { warn } from '@ember/debug';\n\nimport { LOG_INSTANCE_CACHE } from '@warp-drive/core/build-config/debugging';\nimport { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { OpaqueRecordInstance } from '../../-types/q/record-instance.ts';\nimport { createReactiveDocument, type ReactiveDocument } from '../../../reactive/-private/document.ts';\nimport { _CHECKOUT, ReactiveResource } from '../../../reactive/-private/record.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { Cache } from '../../../types/cache.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { TypedRecordInstance, TypeFromInstance, TypeFromInstanceOrString } from '../../../types/record.ts';\nimport type { ResourceSchema } from '../../../types/schema/fields.ts';\nimport { log, logGroup } from '../debug/utils.ts';\nimport { CacheCapabilitiesManager } from '../managers/cache-capabilities-manager.ts';\nimport type { CacheManager } from '../managers/cache-manager.ts';\nimport type { CreateRecordProperties, Store } from '../store-service.ts';\n\ntype Destroyable = {\n isDestroyed: boolean;\n isDestroying: boolean;\n destroy(): void;\n};\n\nfunction isDestroyable(record: OpaqueRecordInstance): record is Destroyable {\n return Boolean(record && typeof record === 'object' && typeof (record as Destroyable).destroy === 'function');\n}\n\nconst RecordCache = getOrSetGlobal('RecordCache', new Map<OpaqueRecordInstance, ResourceKey>());\n\nexport function peekResourceKey(record: OpaqueRecordInstance): ResourceKey | undefined {\n return RecordCache.get(record);\n}\n\n/**\n Retrieves the unique referentially-stable {@link ResourceKey}\n assigned to the given record instance.\n\n ```js\n import { recordIdentifierFor } from \"@warp-drive/core\";\n // ... gain access to a record, for instance with peekRecord or findRecord\n const record = store.peekRecord(\"user\", \"1\");\n // get the identifier for the record (see docs for ResourceKey)\n const identifier = recordIdentifierFor(record);\n // access the identifier's properties.\n const { id, type, lid } = identifier;\n ```\n\n @public\n @param record a record instance previously obstained from the store.\n */\nexport function recordIdentifierFor<T extends TypedRecordInstance>(record: T): ResourceKey<TypeFromInstance<T>>;\nexport function recordIdentifierFor(record: OpaqueRecordInstance): ResourceKey;\nexport function recordIdentifierFor<T>(record: T): ResourceKey<TypeFromInstanceOrString<T>> {\n assert(`${String(record)} is not a ReactiveResource or Model known to WarpDrive`, RecordCache.has(record));\n return RecordCache.get(record)! as ResourceKey<TypeFromInstanceOrString<T>>;\n}\n\n/**\n * Assigns the given {@link ResourceKey} as the identifier for a record instance,\n * enabling later lookup via {@link recordIdentifierFor}.\n *\n * In debug builds, asserts that the record has not already been assigned a\n * different identifier.\n *\n * @private\n */\nexport function setRecordIdentifier(record: OpaqueRecordInstance, identifier: ResourceKey): void {\n if (DEBUG) {\n if (RecordCache.has(record) && RecordCache.get(record) !== identifier) {\n throw new Error(`${String(record)} was already assigned an identifier`);\n }\n }\n\n /*\n It would be nice to do a reverse check here that an identifier has not\n previously been assigned a record; however, unload + rematerialization\n prevents us from having a great way of doing so when CustomRecordClasses\n don't necessarily give us access to a `isDestroyed` for dematerialized\n instance.\n */\n\n RecordCache.set(record, identifier);\n}\nexport function removeRecordIdentifier(record: OpaqueRecordInstance): void {\n if (DEBUG) {\n if (!RecordCache.has(record)) {\n throw new Error(`${String(record)} had no assigned identifier to remove`);\n }\n }\n RecordCache.delete(record);\n}\n\n/**\n * Module-level lookup of the {@link Store} that owns a given record instance\n * (or {@link ResourceKey}), used by {@link storeFor}.\n *\n * @private\n */\nexport const StoreMap: Map<unknown, Store> = getOrSetGlobal('StoreMap', new Map<OpaqueRecordInstance, Store>());\n\n/**\n * We may eventually make this public, but its likely better for this to be killed off\n * @private\n */\nexport function storeFor(record: OpaqueRecordInstance, ignoreMissing: boolean): Store | null {\n const store = StoreMap.get(record);\n\n assert(\n `A record in a disconnected state cannot utilize the store. This typically means the record has been destroyed, most commonly by unloading it.`,\n ignoreMissing || store\n );\n return store ?? null;\n}\n\nexport type Caches = {\n record: Map<ResourceKey, OpaqueRecordInstance>;\n document: Map<RequestKey, ReactiveDocument<OpaqueRecordInstance | OpaqueRecordInstance[] | null | undefined>>;\n};\n\n/**\n * The internal cache of materialized record and document instances for a {@link Store}.\n *\n * Maps {@link ResourceKey}s to their materialized record instances and\n * {@link RequestKey}s to their {@link ReactiveDocument} instances, instantiating\n * them on demand and coordinating their teardown against the underlying {@link Cache}.\n */\nexport class InstanceCache {\n /** The {@link Store} instance this cache belongs to. */\n declare store: Store;\n /** The underlying {@link Cache} instance backing this store, lazily assigned by the {@link Store}. */\n declare cache: Cache;\n /** The {@link CacheCapabilitiesManager} given to the {@link Cache} to allow it to interact with the store. */\n declare _storeWrapper: CacheCapabilitiesManager;\n\n /** Reserved for a future {@link CacheManager} reference; currently unassigned and unused. */\n declare __cacheManager: CacheManager;\n /** The materialized record and document instances for this store, keyed by {@link ResourceKey} and {@link RequestKey} respectively. */\n declare __instances: Caches;\n\n constructor(store: Store) {\n this.store = store;\n this.__instances = {\n record: new Map(),\n document: new Map(),\n };\n\n this._storeWrapper = new CacheCapabilitiesManager(this.store);\n\n store.cacheKeyManager.__configureMerge(\n (identifier: ResourceKey, matchedIdentifier: ResourceKey, resourceData: unknown) => {\n let keptIdentifier = identifier;\n if (identifier.id !== matchedIdentifier.id) {\n // @ts-expect-error TODO this needs to be fixed\n keptIdentifier = 'id' in resourceData && identifier.id === resourceData.id ? identifier : matchedIdentifier;\n } else if (identifier.type !== matchedIdentifier.type) {\n keptIdentifier = // @ts-expect-error TODO this needs to be fixed\n 'type' in resourceData && identifier.type === resourceData.type ? identifier : matchedIdentifier;\n }\n const staleIdentifier = identifier === keptIdentifier ? matchedIdentifier : identifier;\n\n // check for duplicate entities\n const keptHasRecord = this.__instances.record.has(keptIdentifier);\n const staleHasRecord = this.__instances.record.has(staleIdentifier);\n\n // we cannot merge entities when both have records\n // (this may not be strictly true, we could probably swap the cache data the record points at)\n if (keptHasRecord && staleHasRecord) {\n // TODO we probably don't need to throw these errors anymore\n // we can probably just \"swap\" what data source the abandoned\n // record points at so long as\n // it itself is not retained by the store in any way.\n // @ts-expect-error TODO this needs to be fixed\n if ('id' in resourceData) {\n throw new Error(\n `Failed to update the 'id' for the ResourceKey '${identifier.type}:${String(identifier.id)} (${\n identifier.lid\n })' to '${String(resourceData.id)}', because that id is already in use by '${\n matchedIdentifier.type\n }:${String(matchedIdentifier.id)} (${matchedIdentifier.lid})'`\n );\n }\n\n assert(\n `Failed to update the ResourceKey '${identifier.type}:${String(identifier.id)} (${\n identifier.lid\n })' to merge with the detected duplicate identifier '${matchedIdentifier.type}:${String(\n matchedIdentifier.id\n )} (${String(matchedIdentifier.lid)})'`\n );\n }\n\n this.store.cache.patch({\n op: 'mergeIdentifiers',\n record: staleIdentifier,\n value: keptIdentifier,\n });\n\n /*\n TODO @runspired consider adding this to make polymorphism even nicer\n if (identifier.type !== matchedIdentifier.type) {\n this.store._graph?.registerPolymorphicType(identifier.type, matchedIdentifier.type);\n }\n */\n\n this.unloadRecord(staleIdentifier);\n return keptIdentifier;\n }\n );\n }\n /** Returns the materialized record instance for the given {@link ResourceKey} if one exists, without creating one. */\n peek(identifier: ResourceKey): Cache | OpaqueRecordInstance | undefined {\n return this.__instances.record.get(identifier);\n }\n\n /** Returns the {@link ReactiveDocument} for the given {@link RequestKey}, creating and caching an empty one if none exists yet. */\n getDocument<T>(identifier: RequestKey): ReactiveDocument<T> {\n let doc = this.__instances.document.get(identifier);\n if (!doc) {\n doc = createReactiveDocument<T>(this.store, identifier, null);\n this.__instances.document.set(identifier, doc);\n }\n return doc as ReactiveDocument<T>;\n }\n\n /** Returns the materialized record instance for the given {@link ResourceKey}, instantiating one via the {@link Store} if it does not already exist. */\n getRecord(identifier: ResourceKey): OpaqueRecordInstance {\n let record = this.__instances.record.get(identifier);\n\n if (!record) {\n record = _createRecord(this, identifier, {});\n }\n\n return record;\n }\n\n /**\n * Determines whether the record for the given {@link ResourceKey} is considered loaded.\n *\n * New records are always considered loaded unless they have been deleted. Existing\n * records are considered loaded so long as they are not empty (e.g. after being\n * unloaded), or, when `filterDeleted` is `true`, so long as their deletion has not\n * been committed.\n */\n recordIsLoaded(identifier: ResourceKey, filterDeleted = false): boolean {\n const cache = this.cache;\n if (!cache) {\n return false;\n }\n const isNew = cache.isNew(identifier);\n const isEmpty = cache.isEmpty(identifier);\n\n // if we are new we must consider ourselves loaded\n if (isNew) {\n return !cache.isDeleted(identifier);\n }\n // even if we have a past request, if we are now empty we are not loaded\n // typically this is true after an unloadRecord call\n\n // if we are not empty, not new && we have a fulfilled request then we are loaded\n // we should consider allowing for something to be loaded that is simply \"not empty\".\n // which is how RecordState currently handles this case; however, RecordState is buggy\n // in that it does not account for unloading.\n return filterDeleted && cache.isDeletionCommitted(identifier) ? false : !isEmpty;\n }\n\n /**\n * Fully removes a {@link ResourceKey} from the store: forgets it from the graph and\n * the store's cache key manager, clears its pending request state, and removes it\n * from {@link StoreMap}.\n *\n * Expects that any materialized record for the identifier has already been destroyed.\n */\n disconnect(identifier: ResourceKey): void {\n const record = this.__instances.record.get(identifier);\n assert(\n 'Cannot destroy record while it is still materialized',\n !isDestroyable(record) || record.isDestroyed || record.isDestroying\n );\n\n this.store._graph?.remove(identifier);\n\n this.store.cacheKeyManager.forgetRecordIdentifier(identifier);\n StoreMap.delete(identifier);\n this.store._requestCache._clearEntries(identifier);\n if (LOG_INSTANCE_CACHE) {\n log('reactive-ui', '', identifier.type, identifier.lid, 'disconnected', '');\n }\n }\n\n /**\n * Unloads the record for the given {@link ResourceKey}: tears down its materialized\n * instance (if any) and removes its data from the underlying {@link Cache}, disconnecting\n * the identifier entirely if there is no cache to own it.\n *\n * Asserts that no mutation request is currently in flight for the record.\n */\n unloadRecord(identifier: ResourceKey): void {\n if (DEBUG) {\n const requests = this.store.getRequestStateService().getPendingRequestsForRecord(identifier);\n if (\n requests.some((req) => {\n return req.type === 'mutation';\n })\n ) {\n assert(`You can only unload a record which is not inFlight. '${String(identifier)}'`);\n }\n }\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.groupCollapsed(`InstanceCache: unloading record for ${String(identifier)}`);\n }\n\n // TODO is this join still necessary?\n this.store._join(() => {\n unloadRecord(this, identifier);\n });\n }\n\n /** Unloads all records, or, when `type` is provided, only those records of that resource type. */\n clear(type?: string): void {\n const cache = this.store.cacheKeyManager._cache;\n if (type === undefined) {\n // it would be cool if we could just de-ref cache here\n // but probably would require WeakRef models to do so.\n cache.resources.forEach((identifier) => {\n this.unloadRecord(identifier);\n });\n } else {\n const typeCache = cache.resourcesByType;\n const identifiers = typeCache[type]?.lid;\n if (identifiers) {\n identifiers.forEach((identifier) => {\n // if (rds.has(identifier)) {\n this.unloadRecord(identifier);\n // }\n // TODO we don't remove the identifier, should we?\n });\n }\n }\n }\n\n /**\n * Updates the `id` for a {@link ResourceKey} that did not previously have one, e.g. after\n * a newly created record has been saved to the server, and notifies subscribers of the\n * identity change.\n */\n // TODO this should move into something coordinating operations\n setRecordId(identifier: ResourceKey, id: string): void {\n const { type, lid } = identifier;\n const oldId = identifier.id;\n\n // ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record)\n assert(\n `'${type}' was saved to the server, but the response does not have an id and your record does not either.`,\n !(id === null && oldId === null)\n );\n\n // ID absolutely can't be different than oldID if oldID is not null\n // TODO this assertion and restriction may not strictly be needed in the identifiers world\n assert(\n `Cannot update the id for '${type}:${lid}' from '${String(oldId)}' to '${id}'.`,\n !(oldId !== null && id !== oldId)\n );\n\n // ID can be null if oldID is not null (altered ID in response for a record)\n // however, this is more than likely a developer error.\n if (oldId !== null && id === null) {\n warn(\n `Your ${type} record was saved to the server, but the response does not have an id.`,\n !(oldId !== null && id === null)\n );\n return;\n }\n\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: updating id to '${id}' for record ${String(identifier)}`);\n }\n\n const existingIdentifier = this.store.cacheKeyManager.peekResourceKey({ type, id });\n assert(\n `'${type}' was saved to the server, but the response returned the new id '${id}', which has already been used with another record.'`,\n !existingIdentifier || existingIdentifier === identifier\n );\n\n if (identifier.id === null) {\n // TODO potentially this needs to handle merged result\n this.store.cacheKeyManager.updateRecordIdentifier(identifier, { type, id });\n }\n\n // TODO update resource cache if needed ?\n // TODO handle consequences of identifier merge for notifications\n this.store.notifications.notify(identifier, 'identity', null);\n }\n}\n\nexport function getNewRecord(\n instances: InstanceCache,\n identifier: ResourceKey,\n properties: CreateRecordProperties\n): OpaqueRecordInstance {\n let record = instances.__instances.record.get(identifier);\n\n if (!record) {\n record = _createRecord(instances, identifier, properties);\n\n if (record instanceof ReactiveResource && instances.store.schema.resource) {\n // this is a work around until we introduce a new async createRecord API\n const schema = instances.store.schema.resource(identifier) as ResourceSchema;\n if (!schema.legacy) {\n const editable = _CHECKOUT(record);\n if (properties) {\n Object.assign(editable, properties);\n }\n return editable;\n }\n }\n }\n\n return record;\n}\n\nfunction _createRecord(\n instances: InstanceCache,\n identifier: ResourceKey,\n properties: CreateRecordProperties\n): OpaqueRecordInstance {\n assert(\n `Cannot create a new record instance while the store is being destroyed`,\n !instances.store.isDestroying && !instances.store.isDestroyed\n );\n\n const record = instances.store.instantiateRecord(identifier, properties);\n\n setRecordIdentifier(record, identifier);\n StoreMap.set(record, instances.store);\n instances.__instances.record.set(identifier, record);\n\n if (LOG_INSTANCE_CACHE) {\n logGroup('reactive-ui', '', identifier.type, identifier.lid, 'created', '');\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n\n return record;\n}\n\n/**\n * Resets the module-level record-to-identifier and record/identifier-to-store lookup\n * caches used by {@link recordIdentifierFor} and {@link storeFor}.\n *\n * Leaked for test and legacy use only; not intended for application use.\n *\n * @private\n */\nexport function _clearCaches(): void {\n RecordCache.clear();\n StoreMap.clear();\n}\n\nfunction unloadRecord(instances: InstanceCache, identifier: ResourceKey) {\n const record = instances.__instances.record.get(identifier);\n const cache = instances.cache;\n\n if (record) {\n instances.store.teardownRecord(record);\n instances.__instances.record.delete(identifier);\n StoreMap.delete(record);\n RecordCache.delete(record);\n\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: destroyed record for ${String(identifier)}`);\n }\n }\n\n if (cache) {\n cache.unloadRecord(identifier);\n StoreMap.delete(identifier);\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: destroyed cache for ${String(identifier)}`);\n }\n } else {\n instances.disconnect(identifier);\n }\n\n instances.store._requestCache._clearEntries(identifier);\n if (LOG_INSTANCE_CACHE) {\n // oxlint-disable-next-line no-console\n console.log(`InstanceCache: unloaded RecordData for ${String(identifier)}`);\n // oxlint-disable-next-line no-console\n console.groupEnd();\n }\n}\n","import type { Cache, ChangedAttributesHash, RelationshipDiff } from '../../../types/cache.ts';\nimport type { Change } from '../../../types/cache/change.ts';\nimport type { Operation } from '../../../types/cache/operations.ts';\nimport type { CollectionRelationship, ResourceRelationship } from '../../../types/cache/relationship.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { Value } from '../../../types/json/raw.ts';\nimport type { StructuredDataDocument, StructuredDocument } from '../../../types/request.ts';\nimport type {\n CollectionResourceDataDocument,\n ResourceDocument,\n SingleResourceDataDocument,\n} from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { StoreRequestContext } from '../cache-handler/handler.ts';\n\n/**\n * The CacheManager wraps a Cache enforcing that only\n * the public API surface area is exposed.\n *\n * Hence, it is the value of `Store.cache`, wrapping\n * the cache instance returned by `Store.createCache`.\n *\n * It handles translating between cache versions when\n * necessary, for instance when a Store is configured\n * to use both a v1 and a v2 cache depending on some\n * heuristic.\n *\n * Starting with the v2 spec, the cache is designed such\n * that it must be implemented as a singleton.\n *\n * @class CacheManager\n * @public\n */\nexport class CacheManager implements Cache {\n version = '2' as const;\n\n /** @internal */\n declare private ___cache: Cache;\n\n constructor(cache: Cache) {\n this.___cache = cache;\n }\n\n // Cache Management\n // ================\n\n /**\n * Cache the response to a request\n *\n * Unlike `store.push` which has UPSERT\n * semantics, `put` has `replace` semantics similar to\n * the `http` method `PUT`\n *\n * the individually cacheable\n * e resource data it may contain\n * should upsert, but the document data surrounding it should\n * fully replace any existing information\n *\n * Note that in order to support inserting arbitrary data\n * to the cache that did not originate from a request `put`\n * should expect to sometimes encounter a document with only\n * a `content` member and therefor must not assume the existence\n * of `request` and `response` on the document.\n *\n * @public\n */\n put<T>(doc: StructuredDocument<T> | { content: T }): ResourceDocument {\n return this.___cache.put(doc);\n }\n\n /**\n * Perform an operation on the cache to update the remote state.\n *\n * @public\n * @param op the operation to perform\n */\n patch(op: Operation | Operation[]): void {\n this.___cache.patch(op);\n }\n\n /**\n * Update resource data with a local mutation. Currently supports operations\n * on relationships only.\n *\n * @public\n */\n mutate(mutation: LocalRelationshipOperation): void {\n this.___cache.mutate(mutation);\n }\n\n /**\n * Peek resource data from the Cache.\n *\n * In development, if the return value\n * is JSON the return value\n * will be deep-cloned and deep-frozen\n * to prevent mutation thereby enforcing cache\n * Immutability.\n *\n * This form of peek is useful for implementations\n * that want to feed raw-data from cache to the UI\n * or which want to interact with a blob of data\n * directly from the presentation cache.\n *\n * An implementation might want to do this because\n * de-referencing records which read from their own\n * blob is generally safer because the record does\n * not require retaining connections to the Store\n * and Cache to present data on a per-field basis.\n *\n * This generally takes the place of `getAttr` as\n * an API and may even take the place of `getRelationship`\n * depending on implementation specifics, though this\n * latter usage is less recommended due to the advantages\n * of the Graph handling necessary entanglements and\n * notifications for relational data.\n *\n * @public\n * @return the known resource data\n */\n peek(cacheKey: ResourceKey): unknown;\n peek(cacheKey: RequestKey): ResourceDocument | null;\n peek(cacheKey: ResourceKey | RequestKey): unknown {\n return this.___cache.peek(cacheKey as ResourceKey);\n }\n\n peekRemoteState(cacheKey: ResourceKey): unknown;\n peekRemoteState(cacheKey: RequestKey): ResourceDocument | null;\n peekRemoteState(cacheKey: ResourceKey | RequestKey): unknown {\n return this.___cache.peekRemoteState(cacheKey as ResourceKey);\n }\n /**\n * Peek the Cache for the existing request data associated with\n * a cacheable request\n *\n * @public\n */\n peekRequest(key: RequestKey): StructuredDocument<ResourceDocument> | null {\n return this.___cache.peekRequest(key);\n }\n\n /**\n * Push resource data from a remote source into the cache for this ResourceKey\n *\n * @public\n * @return if `hasRecord` is true then calculated key changes should be returned\n */\n upsert(key: ResourceKey, data: unknown, hasRecord: boolean): void | string[] {\n return this.___cache.upsert(key, data, hasRecord);\n }\n\n // Cache Forking Support\n // =====================\n\n /**\n * Create a fork of the cache from the current state.\n *\n * Applications should typically not call this method themselves,\n * preferring instead to fork at the Store level, which will\n * utilize this method to fork the cache.\n *\n * @public\n */\n fork(): Promise<Cache> {\n return this.___cache.fork();\n }\n\n /**\n * Merge a fork back into a parent Cache.\n *\n * Applications should typically not call this method themselves,\n * preferring instead to merge at the Store level, which will\n * utilize this method to merge the caches.\n *\n * @public\n */\n merge(cache: Cache): Promise<void> {\n return this.___cache.merge(cache);\n }\n\n /**\n * Generate the list of changes applied to all\n * record in the store.\n *\n * Each individual resource or document that has\n * been mutated should be described as an individual\n * `Change` entry in the returned array.\n *\n * A `Change` is described by an object containing up to\n * three properties: (1) the `ResourceKey` of the entity that\n * changed; (2) the `op` code of that change being one of\n * `upsert` or `remove`, and if the op is `upsert` a `patch`\n * containing the data to merge into the cache for the given\n * entity.\n *\n * This `patch` is opaque to the Store but should be understood\n * by the Cache and may expect to be utilized by an Adapter\n * when generating data during a `save` operation.\n *\n * It is generally recommended that the `patch` contain only\n * the updated state, ignoring fields that are unchanged\n *\n * ```ts\n * interface Change {\n * key: ResourceKey | RequestKey;\n * op: 'upsert' | 'remove';\n * patch?: unknown;\n * }\n * ```\n *\n * @public\n */\n diff(): Promise<Change[]> {\n return this.___cache.diff();\n }\n\n // SSR Support\n // ===========\n\n /**\n * Serialize the entire contents of the Cache into a Stream\n * which may be fed back into a new instance of the same Cache\n * via `cache.hydrate`.\n *\n * @public\n */\n dump(): Promise<ReadableStream<unknown>> {\n return this.___cache.dump();\n }\n\n /**\n * hydrate a Cache from a Stream with content previously serialized\n * from another instance of the same Cache, resolving when hydration\n * is complete.\n *\n * This method should expect to be called both in the context of restoring\n * the Cache during application rehydration after SSR **AND** at unknown\n * times during the lifetime of an already booted application when it is\n * desired to bulk-load additional information into the cache. This latter\n * behavior supports optimizing pre/fetching of data for route transitions\n * via data-only SSR modes.\n *\n * @public\n */\n hydrate(stream: ReadableStream<unknown>): Promise<void> {\n return this.___cache.hydrate(stream);\n }\n\n // Cache\n // =====\n\n // Resource Support\n // ================\n\n /**\n * [LIFECYCLE] Signal to the cache that a new record has been instantiated on the client\n *\n * It returns properties from options that should be set on the record during the create\n * process. This return value behavior is deprecated.\n *\n * @public\n */\n clientDidCreate(key: ResourceKey, options?: Record<string, unknown>): Record<string, unknown> {\n return this.___cache.clientDidCreate(key, options);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * will be part of a save transaction.\n *\n * @public\n * @param key\n */\n willCommit(key: ResourceKey | ResourceKey[], context: StoreRequestContext): void {\n this.___cache.willCommit(key, context);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * was successfully updated as part of a save transaction.\n *\n * @public\n */\n didCommit(\n key: ResourceKey,\n result: StructuredDataDocument<SingleResourceDataDocument> | null\n ): SingleResourceDataDocument;\n didCommit(\n key: ResourceKey[],\n result: StructuredDataDocument<SingleResourceDataDocument> | null\n ): SingleResourceDataDocument;\n didCommit(\n key: ResourceKey[],\n result: StructuredDataDocument<CollectionResourceDataDocument> | null\n ): CollectionResourceDataDocument;\n didCommit(\n key: ResourceKey | ResourceKey[],\n result: StructuredDataDocument<SingleResourceDataDocument | CollectionResourceDataDocument> | null\n ): CollectionResourceDataDocument | SingleResourceDataDocument {\n // @ts-expect-error TS doesn't enable proxying overload calls\n return this.___cache.didCommit(key, result);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that a resource\n * was update via a save transaction failed.\n *\n * @public\n */\n commitWasRejected(key: ResourceKey | ResourceKey[], errors?: ApiError[]): void {\n this.___cache.commitWasRejected(key, errors);\n }\n\n /**\n * [LIFECYCLE] Signals to the cache that all data for a resource\n * should be cleared.\n *\n * @public\n */\n unloadRecord(key: ResourceKey): void {\n this.___cache.unloadRecord(key);\n }\n\n // Granular Resource Data APIs\n // ===========================\n\n /**\n * Retrieve the data for an attribute from the cache\n *\n * @public\n */\n getAttr(key: ResourceKey, propertyName: string): Value | undefined {\n return this.___cache.getAttr(key, propertyName);\n }\n\n /**\n * Retrieve the remote state for an attribute from the cache\n *\n * @public\n */\n getRemoteAttr(key: ResourceKey, propertyName: string): Value | undefined {\n return this.___cache.getRemoteAttr(key, propertyName);\n }\n\n /**\n * Mutate the data for an attribute in the cache\n *\n * @public\n */\n setAttr(key: ResourceKey, propertyName: string, value: Value): void {\n this.___cache.setAttr(key, propertyName, value);\n }\n\n /**\n * Query the cache for the changed attributes of a resource.\n *\n * @public\n */\n changedAttrs(key: ResourceKey): ChangedAttributesHash {\n return this.___cache.changedAttrs(key);\n }\n\n /**\n * Query the cache for whether any mutated attributes exist\n *\n * @public\n */\n hasChangedAttrs(key: ResourceKey): boolean {\n return this.___cache.hasChangedAttrs(key);\n }\n\n /**\n * Tell the cache to discard any uncommitted mutations to attributes\n *\n * @public\n * @return the names of attributes that were restored\n */\n rollbackAttrs(key: ResourceKey): string[] {\n return this.___cache.rollbackAttrs(key);\n }\n\n // Relationships\n // =============\n\n /**\n * Query the cache for the changes to relationships of a resource.\n *\n * Returns a map of relationship names to RelationshipDiff objects.\n *\n * ```ts\n * type RelationshipDiff =\n | {\n kind: 'collection';\n remoteState: ResourceKey[];\n additions: Set<ResourceKey>;\n removals: Set<ResourceKey>;\n localState: ResourceKey[];\n reordered: boolean;\n }\n | {\n kind: 'resource';\n remoteState: ResourceKey | null;\n localState: ResourceKey | null;\n };\n ```\n *\n * @public\n */\n changedRelationships(key: ResourceKey): Map<string, RelationshipDiff> {\n return this.___cache.changedRelationships(key);\n }\n\n /**\n * Query the cache for whether any mutated attributes exist\n *\n * @public\n */\n hasChangedRelationships(key: ResourceKey): boolean {\n return this.___cache.hasChangedRelationships(key);\n }\n\n /**\n * Tell the cache to discard any uncommitted mutations to relationships.\n *\n * This will also discard the change on any appropriate inverses.\n *\n * This method is a candidate to become a mutation\n *\n * @public\n * @return the names of relationships that were restored\n */\n rollbackRelationships(key: ResourceKey): string[] {\n return this.___cache.rollbackRelationships(key);\n }\n\n /**\n * Query the cache for the current state of a relationship property\n *\n * @public\n * @return resource relationship object\n */\n getRelationship(key: ResourceKey, propertyName: string): ResourceRelationship | CollectionRelationship {\n return this.___cache.getRelationship(key, propertyName);\n }\n\n /**\n * Query the cache for the remote state of a relationship property\n *\n * @public\n * @return resource relationship object\n */\n getRemoteRelationship(key: ResourceKey, propertyName: string): ResourceRelationship | CollectionRelationship {\n return this.___cache.getRemoteRelationship(key, propertyName);\n }\n\n // Resource State\n // ===============\n\n /**\n * Update the cache state for the given resource to be marked as locally deleted,\n * or remove such a mark.\n *\n * @public\n */\n setIsDeleted(key: ResourceKey, isDeleted: boolean): void {\n this.___cache.setIsDeleted(key, isDeleted);\n }\n\n /**\n * Query the cache for any validation errors applicable to the given resource.\n *\n * @public\n */\n getErrors(key: ResourceKey): ApiError[] {\n return this.___cache.getErrors(key);\n }\n\n /**\n * Query the cache for whether a given resource has any available data\n *\n * @public\n */\n isEmpty(key: ResourceKey): boolean {\n return this.___cache.isEmpty(key);\n }\n\n /**\n * Query the cache for whether a given resource was created locally and not\n * yet persisted.\n *\n * @public\n */\n isNew(key: ResourceKey): boolean {\n return this.___cache.isNew(key);\n }\n\n /**\n * Query the cache for whether a given resource is marked as deleted (but not\n * necessarily persisted yet).\n *\n * @public\n */\n isDeleted(key: ResourceKey): boolean {\n return this.___cache.isDeleted(key);\n }\n\n /**\n * Query the cache for whether a given resource has been deleted and that deletion\n * has also been persisted.\n *\n * @public\n */\n isDeletionCommitted(key: ResourceKey): boolean {\n return this.___cache.isDeletionCommitted(key);\n }\n}\n","import { LOG_METRIC_COUNTS, LOG_NOTIFICATIONS } from '@warp-drive/core/build-config/debugging';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { willSyncFlushWatchers } from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport { log } from '../debug/utils.ts';\nimport type { Store } from '../store-service.ts';\nimport { isRequestKey, isResourceKey } from './cache-key-manager.ts';\n\nexport type UnsubscribeToken = object;\n\n/**\n * The kinds of change notifications the {@link NotificationManager} can emit for a resource.\n */\nexport type CacheOperation = 'added' | 'removed' | 'updated' | 'state';\n/**\n * The kinds of change notifications the {@link NotificationManager} can emit for a request document.\n */\nexport type DocumentCacheOperation = 'invalidated' | 'added' | 'removed' | 'updated' | 'state';\n\nfunction isCacheOperationValue(value: NotificationType | DocumentCacheOperation): value is DocumentCacheOperation {\n return (\n value === 'added' || value === 'state' || value === 'updated' || value === 'removed' || value === 'invalidated'\n );\n}\n\n/**\n * The full set of notification kinds the {@link NotificationManager} can emit for a resource,\n * including both {@link CacheOperation}s and finer-grained field-level change notifications.\n */\nexport type NotificationType = 'attributes' | 'relationships' | 'identity' | 'errors' | 'meta' | CacheOperation;\n\n/**\n * The shape accepted by {@link NotificationManager.notify} and\n * {@link CacheCapabilitiesManager.notifyChange} for delivering many keys for\n * the `'attributes'` or `'relationships'` namespaces in a single call\n * instead of once per key.\n *\n * @since 5.9.0\n * @public\n */\nexport type NotifyKeys = Set<string>;\n\n/**\n * A change to a resource's `attributes` or `relationships` can be relevant to\n * a \"local\" view of the resource (its mutable/editable state), a \"remote\" view\n * (its last-known-persisted state), or both.\n *\n * Each view subscribes to its own channel and, when notified, re-pulls its own\n * projection of the data: a remote-only reader (e.g. PolarisMode's default\n * immutable record) subscribes `'remote'` and re-reads remote state; an\n * editable/reconciled reader (a legacy record, or an editable checkout)\n * subscribes `'local'` (the same as omitting the channel) and re-reads local\n * state. A notifier that knows which projection changed tags the notification\n * with that channel; each tag is delivered only to that channel's subscribers.\n * A change affecting both projections is either notified unscoped or once per\n * channel. An unscoped notify cannot guarantee which view changed, so it\n * reaches every subscriber -- this keeps every pre-channel `notify` callsite\n * (and any custom cache that doesn't know about channels) fully compatible.\n *\n * The full delivery matrix:\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * Channel only applies to the `'attributes'` and `'relationships'`\n * notification types. All other types (`'errors'`,\n * `'identity'`, `'state'`, and the various `CacheOperation`/\n * `DocumentCacheOperation` values) are never filtered by channel since they\n * have no local/remote duality.\n *\n * @public\n */\nexport type NotificationChannel = 'local' | 'remote';\n\n/**\n * Well-known sentinel recorded in a {@link ChannelSet} for a touch that\n * carried no channel. An unscoped touch always reaches every subscriber\n * regardless of what channel(s) the same key was also touched with, so its\n * presence in the set short-circuits channel filtering.\n */\nconst UnscopedChannel: '___(unique) Symbol(UnscopedChannel)' = getOrSetGlobal('UnscopedChannel', Symbol('unscoped'));\n\n/**\n * The set of channels (if any) a given `'attributes'`/`'relationships'` touch\n * was tagged with while buffered. {@link UnscopedChannel} is included in this\n * set when at least one of the coalesced touches was itself unscoped (no\n * channel given).\n */\ntype ChannelSet = Set<NotificationChannel | typeof UnscopedChannel>;\n\nexport interface NotificationCallback {\n (cacheKey: ResourceKey, notificationType: 'attributes' | 'relationships', key?: string): void;\n (cacheKey: ResourceKey, notificationType: 'errors' | 'meta' | 'identity' | 'state'): void;\n (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n // (cacheKey: ResourceKey, notificationType: NotificationType, key?: string): void;\n}\n\nexport interface ResourceOperationCallback {\n // resource updates\n (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n}\n\nexport interface DocumentOperationCallback {\n // document updates\n (cacheKey: RequestKey, notificationType: DocumentCacheOperation): void;\n}\n\nfunction keyToString(key: string | NotifyKeys | null | undefined): string {\n return key instanceof Set ? Array.from(key).join(', ') : key || '';\n}\n\n/**\n * Merges an incoming `notify()` call for a single identifier into that\n * identifier's pending-notifications buffer, coalescing redundant work within\n * a single flush window.\n *\n * The buffer is a `Map` from namespace (`'attributes'`, `'relationships'`,\n * `'state'`, etc.) to a \"bucket\". Using a `Map` means the *first* time a\n * namespace is touched during this flush window fixes its position in\n * iteration order; every subsequent touch to that same namespace (regardless\n * of how much later, or how many other namespaces fired in between) updates\n * its value in place without moving it. This preserves the relative order in\n * which *different* namespaces first fired, while intentionally not tracking\n * the arrival order of repeated touches to the *same* namespace - those are\n * provably safe to coalesce because subscribers never receive anything about\n * a notification beyond `(cacheKey, type, key?)`.\n *\n * For every namespace other than `'attributes'`/`'relationships'`, subscriber\n * callbacks never receive a key at all (and channel never applies to them -\n * see {@link NotificationChannel}), so the bucket is simply `null`, used\n * purely as a \"this namespace fired at least once\" presence marker; multiple\n * firings within one flush all collapse to the same single marker.\n *\n * For `'attributes'`/`'relationships'`, a key (or channel) *does* matter, so\n * the bucket is one of:\n * - a `Map<string, ChannelSet>`: the normal case, mapping each specific key\n * touched to the set of channels it was touched with ({@link UnscopedChannel}\n * in that set means at least one of those touches was itself unscoped).\n * - a `ChannelSet` directly: a wildcard meaning \"an unspecified set of keys\n * changed\" - a strict superset of any specific key list, per the existing\n * contract of {@link CacheCapabilitiesManager.notifyChange} - tagged with\n * the set of channels any of the coalesced keyless (or post-wildcard\n * keyed) touches carried.\n *\n * A keyless call always upgrades the bucket to the wildcard form. When\n * upgrading away from a `Map`, every channel ever recorded against any of\n * its specific keys is folded into the new wildcard `ChannelSet` - the\n * wildcard must remain a superset not just key-wise but channel-wise too, or\n * a channel-scoped subscriber that would have heard about one of those\n * specific keys could silently stop hearing about it once the bucket flips\n * to wildcard. Once a bucket is a wildcard it can never downgrade back to a\n * `Map`; a keyed touch that arrives after that point still folds its channel\n * into the wildcard's `ChannelSet` (the specific key itself is discarded,\n * since the wildcard already covers it).\n */\nfunction mergeIntoBuffer(\n buffer: Map<NotificationType | DocumentCacheOperation, Map<string, ChannelSet> | ChannelSet | null>,\n value: NotificationType | CacheOperation | DocumentCacheOperation,\n key: string | NotifyKeys | null | undefined,\n channel: NotificationChannel | undefined\n): void {\n if (value !== 'attributes' && value !== 'relationships') {\n // presence-only namespaces: multiple firings within one flush are\n // lossless to coalesce into a single marker.\n buffer.set(value, null);\n return;\n }\n\n const existing = buffer.get(value) as Map<string, ChannelSet> | ChannelSet | undefined;\n\n if (key === null || key === undefined) {\n // a keyless call is a wildcard: fold this touch's channel (and, if\n // upgrading from a keyed Map, every channel ever recorded against any of\n // its specific keys) into the wildcard ChannelSet.\n const channels: ChannelSet = existing instanceof Set ? existing : new Set();\n if (existing instanceof Map) {\n for (const channelsForKey of existing.values()) {\n for (const ch of channelsForKey) channels.add(ch);\n }\n }\n channels.add(channel ?? UnscopedChannel);\n buffer.set(value, channels);\n return;\n }\n\n if (existing instanceof Set) {\n // already a wildcard: specific keys can never downgrade it back to a\n // Map, but this touch's channel still needs to be folded in.\n existing.add(channel ?? UnscopedChannel);\n return;\n }\n\n const map = existing ?? new Map<string, ChannelSet>();\n if (!existing) {\n buffer.set(value, map);\n }\n\n const keys = key instanceof Set ? key : [key];\n for (const k of keys) {\n let channels = map.get(k);\n if (!channels) {\n channels = new Set();\n map.set(k, channels);\n }\n channels.add(channel ?? UnscopedChannel);\n }\n}\n\n/**\n * Given the set of channels a touch (or coalesced group of touches) was\n * recorded with, determines whether a subscriber scoped to `subscriberChannel`\n * should be delivered to (see the delivery matrix on\n * {@link NotificationChannel}): a subscriber hears a touch-set if any of its\n * touches was unscoped or tagged with the subscriber's own channel; a\n * touch-set exclusively tagged with the *other* channel is skipped.\n */\nfunction shouldDeliverToChannel(channels: ChannelSet, subscriberChannel: NotificationChannel): boolean {\n return channels.has(UnscopedChannel) || channels.has(subscriberChannel);\n}\n\nfunction count(label: string) {\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[label] = (globalThis.__WarpDriveMetricCountData[label] || 0) + 1;\n}\n\nfunction asInternalToken(token: unknown): asserts token is {\n for: RequestKey | ResourceKey | 'resource' | 'document';\n} & (NotificationCallback | ResourceOperationCallback | DocumentOperationCallback) {\n assert(`Expected a token with a 'for' property`, token && typeof token === 'function' && 'for' in token);\n}\n\nfunction _unsubscribe(\n token: UnsubscribeToken,\n cache: Map<\n 'resource' | 'document' | RequestKey | ResourceKey,\n Array<NotificationCallback | ResourceOperationCallback | DocumentOperationCallback>\n >\n) {\n asInternalToken(token);\n const cacheKey = token.for;\n if (LOG_NOTIFICATIONS) {\n if (!cacheKey) {\n // oxlint-disable-next-line no-console\n console.log('Passed unknown unsubscribe token to unsubscribe', cacheKey);\n }\n }\n if (cacheKey) {\n const callbacks = cache.get(cacheKey);\n if (!callbacks) {\n return;\n }\n\n const index = callbacks.indexOf(token);\n if (index === -1) {\n assert(`Cannot unsubscribe a token that is not subscribed`, index !== -1);\n return;\n }\n\n callbacks.splice(index, 1);\n }\n}\n\n/**\n * The NotificationManager provides the ability to subscribe to\n * changes to Cache state.\n *\n * This Feature is what allows WarpDrive to create subscriptions that\n * work with any framework or change-notification system.\n *\n * @hideconstructor\n * @public\n */\nexport class NotificationManager {\n /** @internal */\n declare private store: Store;\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _buffered: Map<\n RequestKey | ResourceKey,\n Map<NotificationType | DocumentCacheOperation, Map<string, ChannelSet> | ChannelSet | null>\n >;\n /** @internal */\n declare private _cache: Map<\n RequestKey | ResourceKey | 'resource' | 'document',\n Array<NotificationCallback | ResourceOperationCallback | DocumentOperationCallback>\n >;\n /** @internal */\n declare private _hasFlush: boolean;\n /** @internal */\n declare private _onFlushCB?: () => void;\n\n constructor(store: Store) {\n this.store = store;\n this.isDestroyed = false;\n this._buffered = new Map();\n this._hasFlush = false;\n this._cache = new Map();\n }\n\n /**\n * Subscribe to changes for a given ResourceKey, RequestKey, or addition/removal of any resource\n * or document.\n *\n * ```ts\n * export type CacheOperation = 'added' | 'removed' | 'updated' | 'state';\n *\n * export interface NotificationCallback {\n * (cacheKey: ResourceKey, notificationType: 'attributes' | 'relationships', key?: string): void;\n * (cacheKey: ResourceKey, notificationType: 'errors' | 'meta' | 'identity' | 'state'): void;\n * (cacheKey: ResourceKey, notificationType: NotificationType, key?: string): void;\n * }\n * export interface ResourceOperationCallback {\n * // resource updates\n * (cacheKey: ResourceKey, notificationType: CacheOperation): void;\n * }\n * export interface DocumentOperationCallback {\n * // document updates\n * (cacheKey: RequestKey, notificationType: CacheOperation): void;\n * }\n * ```\n *\n * A `channel` may be provided when subscribing to a `ResourceKey`. Its\n * effect is that the subscription skips `'attributes'`/`'relationships'`\n * notifications explicitly tagged with the *other* channel; unscoped\n * notifications, and notifications for all other notification types, always\n * reach the subscriber. Subscribing `'local'` and omitting the channel are\n * the same thing. See {@link NotificationChannel}.\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * @public\n * @return an opaque token to be used with unsubscribe\n */\n subscribe(cacheKey: ResourceKey, callback: NotificationCallback, channel?: NotificationChannel): UnsubscribeToken;\n subscribe(cacheKey: 'resource', callback: ResourceOperationCallback): UnsubscribeToken;\n subscribe(cacheKey: 'document' | RequestKey, callback: DocumentOperationCallback): UnsubscribeToken;\n subscribe(\n cacheKey: RequestKey | ResourceKey | 'resource' | 'document',\n callback: NotificationCallback | ResourceOperationCallback | DocumentOperationCallback,\n channel?: NotificationChannel\n ): UnsubscribeToken {\n assert(`Expected not to be destroyed`, !this.isDestroyed);\n assert(\n `Expected to receive a stable Identifier to subscribe to`,\n cacheKey === 'resource' || cacheKey === 'document' || isResourceKey(cacheKey) || isRequestKey(cacheKey)\n );\n let callbacks = this._cache.get(cacheKey);\n assert(`expected to receive a valid callback`, typeof callback === 'function');\n assert(`cannot subscribe with the same callback twice`, !callbacks || !callbacks.includes(callback));\n // we use the callback as the cancellation token\n //@ts-expect-error\n callback.for = cacheKey;\n //@ts-expect-error stashed only for ResourceKey subscriptions; see shouldDeliverToChannel.\n // Defaults to 'local' rather than leaving it unscoped -- see NotificationChannel.\n callback.channel = channel ?? 'local';\n\n if (!callbacks) {\n callbacks = [];\n this._cache.set(cacheKey, callbacks);\n }\n\n callbacks.push(callback);\n return callback;\n }\n\n /**\n * remove a previous subscription\n *\n * @public\n */\n unsubscribe(token: UnsubscribeToken): void {\n if (!this.isDestroyed) {\n _unsubscribe(token, this._cache);\n }\n }\n\n /**\n * Custom Caches and Application Code should not call this method directly.\n *\n * When notifying `'attributes'` or `'relationships'` for many keys on the\n * same `cacheKey` at once (for instance, when a bulk update to a single\n * record touches many fields) `key` may be supplied as a `Set<string>`\n * instead of being called once per key. The `Set` is iterated as-is (it is\n * never converted to or from an array internally). This delivers the\n * exact same sequence of individual notifications to subscribers (each\n * subscriber callback is still invoked once per key, in order) while\n * paying the per-call overhead (validity checks, subscriber lookups,\n * buffer/flush scheduling) only once for the whole batch instead of once\n * per key.\n *\n * A `channel` may be supplied for the `'attributes'`/`'relationships'`\n * namespaces. Tagging a notification `'local'` declares \"only the local\n * (reconciled/editable) view changed\"; tagging it `'remote'` declares \"only\n * the remote view changed\". Each tag is delivered only to that channel's\n * subscribers. Omitting the channel reaches every subscriber regardless of\n * its channel. See {@link NotificationChannel}.\n *\n * | notify ↓ subscribe → | `'local'` | `'remote'` | omitted (= `'local'`) |\n * | -------------------- | --------- | ---------- | --------------------- |\n * | `'local'` | ✅ | ❌ | ✅ |\n * | `'remote'` | ❌ | ✅ | ❌ |\n * | omitted | ✅ | ✅ | ✅ |\n *\n * @private\n */\n notify(\n cacheKey: ResourceKey,\n value: 'attributes' | 'relationships',\n key?: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): boolean;\n notify(cacheKey: ResourceKey, value: 'errors' | 'meta' | 'identity' | 'state', key?: null): boolean;\n notify(cacheKey: ResourceKey, value: CacheOperation, key?: null): boolean;\n notify(cacheKey: RequestKey, value: DocumentCacheOperation, key?: null): boolean;\n notify(\n cacheKey: ResourceKey | RequestKey,\n value: NotificationType | CacheOperation | DocumentCacheOperation,\n key?: string | NotifyKeys | null,\n channel?: NotificationChannel\n ): boolean {\n if (this.isDestroyed) {\n return false;\n }\n assert(\n `Notify does not accept a key argument for the namespace '${value}'. Received key '${keyToString(key)}'.`,\n !key || value === 'attributes' || value === 'relationships'\n );\n assert(\n `Notify does not accept a channel argument for the namespace '${value}'. Received channel '${channel || ''}'.`,\n !channel || value === 'attributes' || value === 'relationships'\n );\n if (!isResourceKey(cacheKey) && !isRequestKey(cacheKey)) {\n if (LOG_NOTIFICATIONS) {\n // oxlint-disable-next-line no-console\n console.log(\n `Notifying: Expected to receive a stable Identifier to notify '${value}' '${keyToString(\n key\n )}' with, but ${String(cacheKey)} is not in the cache`,\n cacheKey\n );\n }\n return false;\n }\n\n const _hasSubscribers = hasSubscribers(this._cache, cacheKey, value);\n if (_hasSubscribers) {\n let buffer = this._buffered.get(cacheKey);\n if (!buffer) {\n buffer = new Map();\n this._buffered.set(cacheKey, buffer);\n }\n\n mergeIntoBuffer(buffer, value, key, channel);\n\n if (LOG_METRIC_COUNTS) {\n count(`notify ${'type' in cacheKey ? cacheKey.type : '<document>'} ${value} ${keyToString(key)}`);\n }\n\n if (!this._scheduleNotify()) {\n if (LOG_NOTIFICATIONS) {\n log(\n 'notify',\n 'buffered',\n `${'type' in cacheKey ? cacheKey.type : 'document'}`,\n cacheKey.lid,\n `${value}`,\n keyToString(key)\n );\n }\n }\n } else {\n if (LOG_NOTIFICATIONS) {\n log(\n 'notify',\n 'discarded',\n `${'type' in cacheKey ? cacheKey.type : 'document'}`,\n cacheKey.lid,\n `${value}`,\n keyToString(key)\n );\n }\n if (LOG_METRIC_COUNTS) {\n count(`DISCARDED notify ${'type' in cacheKey ? cacheKey.type : '<document>'} ${value} ${keyToString(key)}`);\n }\n }\n\n return _hasSubscribers;\n }\n\n /** @internal */\n _onNextFlush(cb: () => void): void {\n this._onFlushCB = cb;\n }\n\n /** @internal */\n private _scheduleNotify(): boolean {\n const asyncFlush = this.store._enableAsyncFlush;\n\n if (this._hasFlush) {\n if (asyncFlush !== false && !willSyncFlushWatchers()) {\n return false;\n }\n }\n\n if (asyncFlush && !willSyncFlushWatchers()) {\n this._hasFlush = true;\n return false;\n }\n\n this._flush();\n return true;\n }\n\n /** @internal */\n _flush(): void {\n const buffered = this._buffered;\n if (buffered.size) {\n this._buffered = new Map();\n for (const [cacheKey, states] of buffered) {\n // `states` iterates in the order each namespace first fired during\n // this flush window (see `mergeIntoBuffer`).\n for (const [value, bucket] of states) {\n if (bucket === null) {\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, null);\n } else if (bucket instanceof Set) {\n // wildcard: one notification, key `null`, filtered by the union\n // of channels any of the coalesced keyless touches carried.\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, null, bucket);\n } else {\n for (const [key, channels] of bucket) {\n // @ts-expect-error overload doesn't narrow within body\n _flushNotification(this._cache, cacheKey, value, key, channels);\n }\n }\n }\n }\n }\n\n this._hasFlush = false;\n this._onFlushCB?.();\n this._onFlushCB = undefined;\n }\n\n /** @internal */\n destroy(): void {\n this.isDestroyed = true;\n this._cache.clear();\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateNotificationManager extends NotificationManager {\n _flush(): void;\n}\n\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey,\n value: 'attributes' | 'relationships',\n key: string | null,\n channels?: ChannelSet\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey,\n value: 'errors' | 'meta' | 'identity' | 'state',\n key: null\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey | RequestKey,\n value: CacheOperation,\n key: null\n): boolean;\nfunction _flushNotification(\n cache: NotificationManager['_cache'],\n cacheKey: ResourceKey | RequestKey,\n value: NotificationType | CacheOperation,\n key: string | null,\n channels?: ChannelSet\n): boolean {\n if (LOG_NOTIFICATIONS) {\n log('notify', '', `${'type' in cacheKey ? cacheKey.type : 'document'}`, cacheKey.lid, `${value}`, key || '');\n }\n\n // TODO for documents this will need to switch based on Identifier kind\n if (isCacheOperationValue(value)) {\n const callbackMap = cache.get(isRequestKey(cacheKey) ? 'document' : 'resource') as Array<\n ResourceOperationCallback | DocumentOperationCallback\n >;\n\n if (callbackMap) {\n callbackMap.forEach((cb: ResourceOperationCallback | DocumentOperationCallback) => {\n (cb as ResourceOperationCallback)(cacheKey as ResourceKey, value);\n });\n }\n }\n\n const callbacks = cache.get(cacheKey);\n if (!callbacks || !callbacks.length) {\n return false;\n }\n callbacks.forEach((cb) => {\n if (channels) {\n // @ts-expect-error channel is stashed on the callback only for ResourceKey subscriptions;\n // always concrete since `subscribe` defaults it to 'local'.\n const subscriberChannel = cb.channel as NotificationChannel;\n if (!shouldDeliverToChannel(channels, subscriberChannel)) {\n return;\n }\n }\n // @ts-expect-error overload doesn't narrow within body\n cb(cacheKey, value, key);\n });\n return true;\n}\n\nfunction hasSubscribers(\n cache: NotificationManager['_cache'],\n cacheKey: RequestKey | ResourceKey,\n value: NotificationType | CacheOperation | DocumentCacheOperation\n): boolean {\n const hasSubscriber = Boolean(cache.get(cacheKey)?.length);\n\n if (hasSubscriber || !isCacheOperationValue(value)) {\n return hasSubscriber;\n }\n\n const callbackMap = cache.get(isRequestKey(cacheKey) ? 'document' : 'resource') as Array<\n ResourceOperationCallback | DocumentOperationCallback\n >;\n return Boolean(callbackMap?.length);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { Context } from '../../../reactive/-private';\nimport type { BaseFinderOptions } from '../../../types';\nimport type { LocalRelationshipOperation } from '../../../types/graph';\nimport type { ResourceKey } from '../../../types/identifier';\nimport type { Store } from '../store-service';\nimport type { NativeProxy } from './native-proxy-type-fix';\nimport type { ReactiveResourceArray } from './resource-array';\n\n/**\n * LegacyArrays have the capability of updating via `array.update()`\n * and saving each contained record individually via `array.save()`\n */\nexport interface LegacyArray<T = unknown> extends ReactiveResourceArray<T> {\n /**\n The flag to signal a `RecordArray` is currently loading data.\n Example\n ```javascript\n let people = store.peekAll('person');\n people.isUpdating; // false\n people.update();\n people.isUpdating; // true\n ```\n */\n isUpdating: boolean;\n /** @internal */\n _updatingPromise: Promise<LegacyArray<T>> | null;\n\n /**\n Used to get the latest version of all of the records in this array\n from the adapter.\n\n Example\n\n ```javascript\n let people = store.peekAll('person');\n people.isUpdating; // false\n\n people.update().then(function() {\n people.isUpdating; // false\n });\n\n people.isUpdating; // true\n ```\n\n @public\n */\n update(this: LegacyArray<T>): Promise<LegacyArray<T>>;\n\n /**\n Saves all of the records in the `RecordArray`.\n\n Example\n\n ```js\n let messages = store.peekAll('message');\n messages.forEach(function(message) {\n message.hasBeenSeen = true;\n });\n messages.save();\n ```\n\n @public\n */\n save(this: LegacyArray<T>): Promise<LegacyArray<T>>;\n}\n\nexport function upgradeThis(obj: unknown): asserts obj is LegacyArray {}\n\nexport function update(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n if (this.isUpdating) {\n return this._updatingPromise!;\n }\n\n this.isUpdating = true;\n\n // @ts-expect-error\n // oxlint-disable-next-line typescript/no-unsafe-call\n const updatingPromise = this._update() as Promise<IdentifierArray>;\n void updatingPromise.finally(() => {\n this._updatingPromise = null;\n if (this.isDestroying || this.isDestroyed) {\n return;\n }\n this.isUpdating = false;\n });\n\n this._updatingPromise = updatingPromise;\n\n return updatingPromise;\n}\n\nexport function save(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n\n const context = this[Context];\n const promise = Promise.all(this.map((record) => context.store.saveRecord(record))).then(() => this);\n\n return promise;\n}\n\nexport type KeyType = string | symbol | number;\nconst ARRAY_GETTER_METHODS = new Set<KeyType>([\n Symbol.iterator,\n 'concat',\n 'entries',\n 'every',\n 'fill',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'forEach',\n 'includes',\n 'indexOf',\n 'join',\n 'keys',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'values',\n]);\nconst ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\nexport function isArrayGetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_GETTER_METHODS.has(prop);\n}\nexport function isArraySetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_SETTER_METHODS.has(prop);\n}\n\nexport function convertToInt(prop: KeyType): number | null {\n if (typeof prop === 'symbol') return null;\n\n const num = Number(prop);\n\n if (isNaN(num)) return null;\n\n return num % 1 === 0 ? num : null;\n}\n\nexport type ForEachCB<T> = (record: T, index: number, context: typeof NativeProxy<ResourceKey[], T[]>) => void;\nexport function safeForEach<T>(\n instance: typeof NativeProxy<ResourceKey[], T[]>,\n arr: ResourceKey[],\n store: Store,\n callback: ForEachCB<T>,\n target: unknown\n): typeof NativeProxy<ResourceKey[], T[]> {\n if (target === undefined) {\n target = null;\n }\n // clone to prevent mutation\n arr = arr.slice();\n assert('`forEach` expects a function as first argument.', typeof callback === 'function');\n\n // because we retrieveLatest above we need not worry if array is mutated during iteration\n // by unloadRecord/rollbackAttributes\n // push/add/removeObject may still be problematic\n // but this is a more traditionally expected forEach bug.\n const length = arr.length; // we need to access length to ensure we are consumed\n\n for (let index = 0; index < length; index++) {\n callback.call(target, store._instanceCache.getRecord(arr[index]) as T, index, instance);\n }\n\n return instance;\n}\n\ntype PromiseTo<T> = Omit<Promise<T>, typeof Symbol.toStringTag>;\ntype PromiseManyArray<T> = {\n length: number;\n content: ReactiveResourceArray<T> | null;\n promise: Promise<ReactiveResourceArray<T>> | null;\n} & PromiseTo<ReactiveResourceArray<T>>;\nexport interface MinimumManager {\n _syncArray(array: ReactiveResourceArray): void;\n mutate?(mutation: LocalRelationshipOperation): void;\n reloadHasMany?<T>(key: string, options?: BaseFinderOptions): Promise<ReactiveResourceArray> | PromiseManyArray<T>;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { SignalStore, WarpDriveSignal } from '../../../signals/-private';\nimport { consumeInternalSignal, getOrCreateInternalSignal } from '../../../signals/-private';\nimport type { ExtensionDef } from '../schema';\n\nexport type ProxiedMethod = (...args: unknown[]) => unknown;\nexport function expectNever(value: never): void {}\n\nexport function isExtensionProp(\n extensions: Map<string | symbol, ExtensionDef> | null,\n prop: string | number | symbol\n): prop is string | symbol {\n return Boolean(extensions && typeof prop !== 'number' && extensions.has(prop));\n}\n\nexport function performObjectExtensionGet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol\n): unknown {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method': {\n return desc.fn;\n }\n case 'readonly-value': {\n return desc.value;\n }\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n // we don't consume this signal, since its not a true local.\n return signal.value;\n }\n case 'readonly-field':\n case 'mutable-field': {\n return desc.get.call(receiver);\n }\n case 'writeonly-field': {\n assert(`Cannot get extended field ${String(prop)} as its definition has only a setter`);\n return undefined;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return undefined;\n }\n }\n}\n\nexport function performExtensionSet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol,\n value: unknown\n): boolean {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method':\n case 'readonly-value':\n case 'readonly-field':\n assert(`Cannot set extension field ${String(prop)} as it is a ${desc.kind}`);\n return false;\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n if (signal.value !== value) {\n // we don't notify this signal, since its not a true local.\n signal.value = value;\n }\n return true;\n }\n case 'writeonly-field':\n case 'mutable-field': {\n desc.set.call(receiver, value);\n return true;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return false;\n }\n }\n}\n\nexport function performArrayExtensionGet(\n receiver: object,\n extensions: Map<string | symbol, ExtensionDef>,\n signals: SignalStore,\n prop: string | symbol,\n _SIGNAL: WarpDriveSignal,\n boundFns: Map<string | symbol | number, ProxiedMethod>,\n transaction: (v: boolean) => void\n): unknown {\n const desc = extensions.get(prop)!;\n switch (desc.kind) {\n case 'method': {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n transaction(true);\n const result = Reflect.apply(desc.fn, receiver, arguments) as unknown;\n transaction(false);\n return result;\n };\n\n boundFns.set(prop, fn);\n }\n\n return fn;\n }\n case 'mutable-field':\n case 'readonly-field': {\n return desc.get.call(receiver);\n }\n case 'readonly-value': {\n return desc.value;\n }\n case 'mutable-value': {\n const signal = getOrCreateInternalSignal(signals, receiver, prop, desc.value);\n // we don't consume this signal, since its not a true local.\n return signal.value;\n }\n case 'writeonly-field': {\n assert(`Cannot get extended field ${String(prop)} as its definition has only a setter`);\n return undefined;\n }\n default: {\n expectNever(desc);\n assert(`Unhandled extension kind ${(desc as { kind: string }).kind}`);\n return undefined;\n }\n }\n}\n","/* oxlint-disable typescript/no-explicit-any */\n/*\n We redefine Proxy because the native Proxy type treats the `target` and\n `receiver` as the same type incorrectly.\n\n We ported this from Typescript's own Proxy types on 3/10/2024.\n*/\ninterface ProxyHandler<T extends object> {\n /**\n * A trap method for a function call.\n * @param target The original callable object which is being proxied.\n * @internal\n */\n apply?(target: T, thisArg: any, argArray: any[]): any;\n\n /**\n * A trap for the `new` operator.\n * @param target The original object which is being proxied.\n * @param newTarget The constructor that was originally called.\n * @internal\n */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n construct?(target: T, argArray: any[], newTarget: Function): object;\n\n /**\n * A trap for `Object.defineProperty()`.\n * @param target The original object which is being proxied.\n * @return A `Boolean` indicating whether or not the property has been defined.\n * @internal\n */\n defineProperty?(target: T, property: string | symbol, attributes: PropertyDescriptor): boolean;\n\n /**\n * A trap for the `delete` operator.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to delete.\n * @return A `Boolean` indicating whether or not the property was deleted.\n * @internal\n */\n deleteProperty?(target: T, p: string | symbol): boolean;\n\n /**\n * A trap for getting a property value.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to get.\n * @param receiver The proxy or an object that inherits from the proxy.\n * @internal\n */\n get?(target: T, p: string | symbol, receiver: any): any;\n\n /**\n * A trap for `Object.getOwnPropertyDescriptor()`.\n * @param target The original object which is being proxied.\n * @param p The name of the property whose description should be retrieved.\n * @internal\n */\n getOwnPropertyDescriptor?(target: T, p: string | symbol): PropertyDescriptor | undefined;\n\n /**\n * A trap for the `[[GetPrototypeOf]]` internal method.\n * @param target The original object which is being proxied.\n * @internal\n */\n getPrototypeOf?(target: T): object | null;\n\n /**\n * A trap for the `in` operator.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to check for existence.\n * @internal\n */\n has?(target: T, p: string | symbol): boolean;\n\n /**\n * A trap for `Object.isExtensible()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n isExtensible?(target: T): boolean;\n\n /**\n * A trap for `Reflect.ownKeys()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n ownKeys?(target: T): ArrayLike<string | symbol>;\n\n /**\n * A trap for `Object.preventExtensions()`.\n * @param target The original object which is being proxied.\n * @internal\n */\n preventExtensions?(target: T): boolean;\n\n /**\n * A trap for setting a property value.\n * @param target The original object which is being proxied.\n * @param p The name or `Symbol` of the property to set.\n * @param receiver The object to which the assignment was originally directed.\n * @return A `Boolean` indicating whether or not the property was set.\n * @internal\n */\n set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean;\n\n /**\n * A trap for `Object.setPrototypeOf()`.\n * @param target The original object which is being proxied.\n * @param newPrototype The object's new prototype or `null`.\n * @internal\n */\n setPrototypeOf?(target: T, v: object | null): boolean;\n}\n\ninterface ProxyConstructor {\n /**\n * Creates a revocable Proxy object.\n * @param target A target object to wrap with Proxy.\n * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.\n * @internal\n */\n revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void };\n\n /**\n * Creates a Proxy object. The Proxy object allows you to create an object that can be used in place of the\n * original object, but which may redefine fundamental Object operations like getting, setting, and defining\n * properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs.\n * @param target A target object to wrap with Proxy.\n * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.\n * @internal\n */\n new <TSource extends object, TTarget extends object>(target: TSource, handler: ProxyHandler<TSource>): TTarget;\n}\n\n/**\n * The global `Proxy` constructor, retyped with the corrected\n * {@link ProxyConstructor} signature above so that `target` and `receiver`\n * may differ.\n *\n * @private\n */\nexport const NativeProxy: ProxyConstructor = Proxy as unknown as ProxyConstructor;\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { DEPRECATE_COMPUTED_CHAINS } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { OpaqueRecordInstance } from '../../-types/q/record-instance.ts';\nimport type { ExtensionDef } from '../../../reactive.ts';\nimport { Context } from '../../../reactive/-private.ts';\nimport {\n isExtensionProp,\n performArrayExtensionGet,\n performExtensionSet,\n} from '../../../reactive/-private/fields/extension.ts';\nimport type { SignalStore, WarpDriveSignal } from '../../../signals/-private.ts';\nimport {\n ARRAY_SIGNAL,\n consumeInternalSignal,\n createInternalSignal,\n createSignalDescriptor,\n notifyInternalSignal,\n Signals,\n withSignalStore,\n} from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { CollectionField } from '../../../types/schema/fields.ts';\nimport { recordIdentifierFor } from '../caches/instance-cache.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport type { Store } from '../store-service.ts';\nimport type { ForEachCB, KeyType, MinimumManager } from './-utils.ts';\nimport { convertToInt, isArrayGetter, isArraySetter, safeForEach } from './-utils.ts';\nimport { NativeProxy } from './native-proxy-type-fix.ts';\n\nconst IS_COLLECTION: '___(unique) Symbol(IS_COLLECTION)' = getOrSetGlobal('IS_COLLECTION', Symbol.for('Collection'));\nfunction isContextProp(prop: string | symbol | number): prop is keyof ReactiveResourceArrayContext {\n return prop === 'destroy' || prop === 'isDestroying' || prop === 'isDestroyed';\n}\ntype ProxiedMethod = (...args: unknown[]) => unknown;\n\n// these are \"internally\" mutable, they should not be mutated by consumers\n// though this is not currently enforced.\n//\n// all of these should become gated by field-type as they shouldn't be available\n// on request results or non-legacy relationships.\nconst MUTABLE_PROPS = [\n '_updatingPromise',\n 'isDestroying',\n 'isDestroyed',\n 'query',\n 'isUpdating',\n 'isLoaded',\n 'meta',\n 'links',\n 'isAsync',\n 'isPolymorphic',\n 'identifier',\n 'cache',\n 'key',\n 'DEPRECATED_CLASS_NAME',\n];\n\ninterface ReactiveResourceArrayCreateOptions {\n // passed in\n store: Store;\n manager: MinimumManager;\n editable: boolean;\n source: ResourceKey[];\n\n // reactive, passed in\n data: ObjectValue | null;\n\n // non-reactive, passed in\n features: Record<string | symbol, unknown> | null;\n extensions: Map<string | symbol, ExtensionDef> | null;\n\n // not-accessible except by the context\n options: Record<string, unknown> | null;\n\n destroy: null | ((this: ReactiveResourceArray, clear: boolean) => void);\n mutate:\n | null\n | ((\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n ) => unknown);\n}\n\ninterface ReactiveResourceArrayContext extends ReactiveResourceArrayCreateOptions {\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n mutate: (\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n ) => unknown;\n\n // generated\n signals: SignalStore;\n signal: WarpDriveSignal;\n isDestroying: boolean;\n isDestroyed: boolean;\n transaction: boolean;\n boundFns: Map<KeyType, ProxiedMethod>;\n}\n\n/**\n * A reactive Array of records, backed by a {@link ResourceKey} array in the\n * cache. Returned by {@link Store.request} for collection responses and used\n * as the base for relationship and legacy record-array types such as\n * {@link LegacyLiveArray}, {@link LegacyQueryArray} and {@link LegacyManyArray}.\n *\n * Behaves like a native Array: `Array.isArray(arr)` and `arr instanceof Array`\n * both report `true`. The array stays in sync with the cache, updating\n * reactively as the underlying {@link ResourceKey}s change.\n *\n * @public\n */\nexport interface ReactiveResourceArray<T = unknown> extends Omit<Array<T>, '[]'> {\n /** @internal */\n isDestroying: boolean;\n /** @internal */\n isDestroyed: boolean;\n /** @internal */\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n /** @internal */\n [IS_COLLECTION]: boolean;\n /** @internal */\n [Context]: ReactiveResourceArrayContext;\n}\n\n/**\n * A variant of {@link ReactiveResourceArray} that exposes its otherwise\n * internal-only members (including the `Context` symbol used to reach the\n * array's private bookkeeping). Used to upgrade a {@link ReactiveResourceArray}\n * for intimate access by `@warp-drive/legacy`.\n *\n * @private\n */\nexport interface PrivateReactiveResourceArray<T = unknown> extends Omit<Array<T>, '[]'> {\n /** @private */\n isDestroying: boolean;\n /** @private */\n isDestroyed: boolean;\n /** @private */\n destroy: (this: ReactiveResourceArray, clear: boolean) => void;\n /** @private */\n [IS_COLLECTION]: boolean;\n /** @private */\n [Context]: ReactiveResourceArrayContext;\n}\n\nexport interface TargetArray extends Array<ResourceKey> {\n /** @internal */\n [Context]: ReactiveResourceArrayContext;\n}\n\n// this will error if someone tries to call\n// A(identifierArray) since it is not configurable\n// which is preferable to the `meta` override we used\n// before which required importing all of Ember\nconst ARR_BRACKET_DESC = {\n enumerable: true,\n configurable: false,\n get: function () {\n // here to support computed chains\n // and {{#each}}\n if (DEPRECATE_COMPUTED_CHAINS) {\n return this;\n }\n },\n};\n\nconst IS_UPDATING_DESC = createSignalDescriptor('isUpdating', false);\nconst ArrayHandler: ProxyHandler<ResourceKey[]> = {\n getOwnPropertyDescriptor<R extends typeof NativeProxy<ResourceKey[], unknown[]>>(target: TargetArray, prop: keyof R) {\n if (prop === '[]') {\n // proxies do not allow you to report a descriptor as non-configurable\n // if there is no descriptor or the underlying descriptor is configurable\n const underlying = Reflect.getOwnPropertyDescriptor(target, prop);\n if (!underlying) {\n Object.defineProperty(target, prop, ARR_BRACKET_DESC);\n }\n return ARR_BRACKET_DESC;\n }\n if (prop === 'isUpdating') {\n return IS_UPDATING_DESC;\n }\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n\n get<R extends typeof NativeProxy<ResourceKey[], unknown[]>>(\n target: TargetArray,\n prop: keyof R,\n receiver: R\n ): unknown {\n const CONTEXT = target[Context];\n\n // we place this prop first as it needs initialized\n // prior to the signal check below\n if (prop === Signals) return CONTEXT.signals;\n\n const index = convertToInt(prop);\n if (\n // prettier-ignore\n CONTEXT.signal.isStale &&\n (\n index !== null ||\n prop === 'length' ||\n prop === '[]' ||\n (CONTEXT.data && prop in CONTEXT.data) ||\n isArrayGetter(prop)\n )\n ) {\n CONTEXT.manager._syncArray(receiver as unknown as ReactiveResourceArray);\n CONTEXT.signal.isStale = false;\n }\n\n if (index !== null) {\n const identifier = target[index];\n if (!CONTEXT.transaction) {\n consumeInternalSignal(CONTEXT.signal);\n }\n return identifier && CONTEXT.store._instanceCache.getRecord(identifier);\n }\n\n if (prop === 'length') return (consumeInternalSignal(CONTEXT.signal), target.length);\n if (prop === '[]') return (consumeInternalSignal(CONTEXT.signal), receiver);\n // TODO move this to ?? so its only on subclasses\n if (prop === 'isUpdating') return IS_UPDATING_DESC.get!.call(receiver);\n if (prop === IS_COLLECTION) return true;\n if (prop === Context) return CONTEXT;\n if (isContextProp(prop)) {\n return CONTEXT[prop];\n }\n\n if (CONTEXT.data && prop in CONTEXT.data) {\n // all props in data are reactive props.\n return (consumeInternalSignal(CONTEXT.signal), CONTEXT.data[prop]);\n }\n\n if (isArrayGetter(prop)) {\n let fn = CONTEXT.boundFns.get(prop);\n\n if (fn === undefined) {\n if (prop === 'forEach') {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n CONTEXT.transaction = true;\n const result = safeForEach(\n receiver,\n target,\n CONTEXT.store,\n arguments[0] as ForEachCB<unknown>,\n arguments[1]\n );\n CONTEXT.transaction = false;\n return result;\n };\n } else {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n CONTEXT.transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n CONTEXT.transaction = false;\n return result;\n };\n }\n\n CONTEXT.boundFns.set(prop, fn);\n }\n\n return fn;\n }\n\n if (isArraySetter(prop)) {\n let fn = CONTEXT.boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n if (!CONTEXT.editable) {\n assert(`Mutating this array of records via ${String(prop)} is not allowed.`, CONTEXT.editable);\n return;\n }\n const args: unknown[] = Array.prototype.slice.call(arguments);\n assert(`Cannot start a new array transaction while a previous transaction is underway`, !CONTEXT.transaction);\n CONTEXT.transaction = true;\n const result = CONTEXT.mutate(target, receiver, prop as string, args, CONTEXT.signal);\n CONTEXT.transaction = false;\n return result;\n };\n\n CONTEXT.boundFns.set(prop, fn);\n }\n\n return fn;\n }\n\n if (CONTEXT.features && prop in CONTEXT.features) {\n let fn = CONTEXT.boundFns.get(prop);\n if (fn) return fn;\n\n // @ts-expect-error\n const outcome: unknown = CONTEXT.features[prop];\n\n if (typeof outcome === 'function') {\n fn = function () {\n consumeInternalSignal(CONTEXT.signal);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n return Reflect.apply(outcome as ProxiedMethod, receiver, arguments) as unknown;\n };\n\n CONTEXT.boundFns.set(prop, fn);\n return fn;\n }\n\n return (consumeInternalSignal(CONTEXT.signal), outcome);\n }\n\n if (isExtensionProp(CONTEXT.extensions, prop)) {\n return performArrayExtensionGet(\n receiver,\n CONTEXT.extensions!,\n CONTEXT.signals,\n prop,\n CONTEXT.signal,\n CONTEXT.boundFns,\n (v: boolean) => void (CONTEXT.transaction = v)\n );\n }\n\n // this Proxy get trap must return raw property values, including methods, unbound\n // oxlint-disable-next-line typescript/unbound-method\n return target[prop as keyof ResourceKey[]];\n },\n\n set(\n target: TargetArray,\n prop: KeyType,\n value: unknown,\n receiver: typeof NativeProxy<ResourceKey[], unknown[]>\n ): boolean {\n const CONTEXT = target[Context];\n if (prop === Signals) {\n CONTEXT.signals = value as SignalStore;\n return true;\n }\n\n if (!CONTEXT.editable && !MUTABLE_PROPS.includes(prop as string)) {\n assert(`Mutating ${String(prop)} on this Array is not allowed.`, CONTEXT.editable);\n return false;\n }\n if (prop === 'length') {\n if (!CONTEXT.transaction && value === 0) {\n CONTEXT.transaction = true;\n CONTEXT.mutate(target, receiver, 'length 0', [], CONTEXT.signal);\n CONTEXT.transaction = false;\n return true;\n } else if (CONTEXT.transaction) {\n return Reflect.set(target, prop, value);\n } else {\n assert(`unexpected length set`);\n }\n }\n\n if (isContextProp(prop)) {\n // @ts-expect-error\n CONTEXT[prop] = value;\n return true;\n }\n\n if (CONTEXT.data && prop in CONTEXT.data) {\n CONTEXT.data[prop as string] = (value || null) as Value;\n return true;\n }\n\n // TODO move this to subclass\n if (prop === 'isUpdating') {\n IS_UPDATING_DESC.set!.call(receiver, value);\n return true;\n }\n\n if (isExtensionProp(CONTEXT.extensions, prop)) {\n return performExtensionSet(receiver, CONTEXT.extensions!, CONTEXT.signals, prop, value);\n }\n\n const index = convertToInt(prop);\n\n // we do not allow \"holey\" arrays and so if the index is\n // greater than length then we will disallow setting it.\n // however, there is a special case for \"unshift\" with more than\n // one item being inserted since current items will be moved to the\n // new indices first.\n // we \"loosely\" detect this by just checking whether we are in\n // a transaction.\n if (index === null || index > target.length) {\n if (index !== null && CONTEXT.transaction) {\n const identifier = recordIdentifierFor(value);\n assert(`Cannot set index ${index} past the end of the array.`, isResourceKey(identifier));\n target[index] = identifier;\n return true;\n } else if (CONTEXT.features && prop in CONTEXT.features) {\n CONTEXT.features[prop] = value;\n return true;\n }\n return false;\n }\n\n const original: ResourceKey | undefined = target[index];\n const newIdentifier = extractIdentifierFromRecord(value);\n assert(`Expected a record`, newIdentifier && isResourceKey(newIdentifier));\n // We generate \"transactions\" whenever a setter method on the array\n // is called and might bulk update multiple array cells. Fundamentally,\n // all array operations decompose into individual cell replacements.\n // e.g. a push is really a \"replace cell at next index with new value\"\n // or a splice is \"shift all values left/right by X and set out of new\n // bounds cells to undefined\"\n //\n // so, if we are in a transaction, then this is not a user generated change\n // but one generated by a setter method. In this case we want to only apply\n // the change to the target array and not call the MUTATE method.\n // If there is no transaction though, then this means the user themselves has\n // directly changed the value of a specific index and we need to thus generate\n // a mutation for that change.\n // e.g. \"arr.push(newVal)\" is handled by a \"addToRelatedRecords\" mutation within\n // a transaction.\n // while \"arr[arr.length] = newVal;\" is handled by this replace cell code path.\n if (!CONTEXT.transaction) {\n CONTEXT.mutate(target, receiver, 'replace cell', [index, original, newIdentifier], CONTEXT.signal);\n } else {\n target[index] = newIdentifier;\n }\n\n return true;\n },\n\n deleteProperty(target: TargetArray, prop: string | symbol): boolean {\n const CONTEXT = target[Context];\n assert(`Deleting keys on managed arrays is disallowed`, CONTEXT.transaction);\n if (!CONTEXT.transaction) {\n return false;\n }\n return Reflect.deleteProperty(target, prop);\n },\n\n getPrototypeOf() {\n return Array.prototype as ReactiveResourceArray;\n },\n};\n\nconst ILLEGAL_MUTATION = () => {\n assert(`ILLEGAL OPERATION: This ReactiveResourceArray is immutable`);\n};\n\nexport function createReactiveResourceArray<T>(options: ReactiveResourceArrayCreateOptions): ReactiveResourceArray<T> {\n const TARGET = options.source as TargetArray;\n const context = {\n store: options.store,\n manager: options.manager,\n editable: options.editable,\n source: options.source,\n data: options.data,\n features: options.features,\n extensions: options.extensions,\n options: options.options,\n destroy: options.destroy || destroy,\n mutate: options.mutate || ILLEGAL_MUTATION,\n signals: null as unknown as SignalStore,\n signal: null as unknown as WarpDriveSignal,\n isDestroying: false,\n isDestroyed: false,\n transaction: false,\n boundFns: new Map(),\n } satisfies ReactiveResourceArrayContext;\n TARGET[Context] = context;\n\n const proxy = new NativeProxy<ResourceKey[], T[]>(TARGET, ArrayHandler) as ReactiveResourceArray<T>;\n if (DEBUG) {\n Object.defineProperty(TARGET, '__SHOW_ME_THE_DATA_(debug mode only)__', {\n enumerable: false,\n configurable: true,\n get() {\n return proxy.slice();\n },\n });\n }\n\n // we entangle the signal on the returned proxy since that is\n // the object that other code will be interfacing with.\n // when a mutation occurs\n // we track all mutations within the call\n // and forward them as one\n withSignalStore(proxy);\n context.signal = createInternalSignal(context.signals, proxy, ARRAY_SIGNAL, undefined);\n\n return proxy;\n}\n\n// Ensure instanceof works correctly\n// Object.setPrototypeOf(IdentifierArray.prototype, Array.prototype);\n\nfunction extractIdentifierFromRecord(record: OpaqueRecordInstance | null) {\n if (!record) {\n return null;\n }\n\n assert(\n `All elements of a ReactiveResourceArray must be instances of a ReactiveResource, you passed $${typeof record}`,\n (function () {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n })()\n );\n\n return recordIdentifierFor(record);\n}\n\nexport function destroy(this: ReactiveResourceArray, clear: boolean): void {\n const context = this[Context];\n this.isDestroying = !clear;\n // changing the reference breaks the Proxy\n // this[SOURCE] = [];\n context.source.length = 0;\n notifyInternalSignal(context.signal);\n this.isDestroyed = !clear;\n}\n\nexport interface ReactiveRequestCollectionCreateArgs {\n // passed in\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n\n options: {\n requestKey: RequestKey;\n } | null;\n}\n\nexport function createRequestCollection(config: ReactiveRequestCollectionCreateArgs): ReactiveResourceArray {\n return createReactiveResourceArray({\n store: config.store,\n manager: config.manager,\n editable: false,\n source: config.source,\n data: null,\n features: null,\n extensions: null,\n options: config.options,\n destroy: null,\n mutate: null,\n });\n}\n\nexport interface ReactiveRelatedCollectionCreateArgs {\n // passed in\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n\n // not-accessible except by the context\n options: {\n resourceKey: ResourceKey;\n path: string[];\n field: CollectionField;\n };\n\n editable: boolean;\n extensions: Map<string | symbol, ExtensionDef> | null;\n}\n\nexport function createRelatedCollection(config: ReactiveRelatedCollectionCreateArgs): ReactiveResourceArray {\n return createReactiveResourceArray({\n store: config.store,\n manager: config.manager,\n editable: config.editable,\n source: config.source,\n data: null,\n features: null,\n extensions: config.extensions,\n options: config.options,\n destroy: null,\n mutate: null,\n });\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { TypeFromInstanceOrString } from '../../../types/record.ts';\nimport type { Store } from '../store-service.ts';\nimport type { LegacyArray, MinimumManager } from './-utils.ts';\nimport { save, update } from './-utils.ts';\nimport type { ReactiveResourceArray } from './resource-array.ts';\nimport { createReactiveResourceArray } from './resource-array.ts';\n\n/**\n * LiveArrays contain all the known records for a given `ResourceType`.\n *\n * ### Basic Example\n *\n * For instance, if an application were to have a `'user'` type:\n *\n * ```ts\n * const usersLiveArray = store.peekAll('user');\n * ```\n *\n * ---\n *\n * \n *\n * ### LiveArrays are Arrays\n *\n * LiveArrays have all array APIs, and will report `true`\n * for both `liveArray instanceof Array` and `Array.isArray(liveArray)`\n *\n * ---\n *\n * \n *\n * ### Reactive\n *\n * The array is \"live\" as it will reactively update any time new\n * users are added to the store's cache.\n *\n * There is only one LiveArray instance per ResourceType, and it\n * can be accessed either via {@link Store.peekAll} or {@link Store.findAll}\n *\n * ```ts\n * const users = await store.findAll('user');\n * const peekedUsers = store.peekAll('user');\n * peekedUsers === users; // true\n * ```\n *\n * ---\n *\n * \n *\n * ### New Records\n *\n * Records in the `\"new\"` state (created locally on the client\n * but not yet saved) appear in LiveArrays if they are in LegacyMode.\n *\n * PolarisMode records in the `\"new\"` state do not appear in LiveArrays.\n *\n * ---\n *\n * \n *\n * ### Polymorphism\n *\n * LiveArrays are not polymorphic. If your application has an abstract\n * type \"car\" with concrete types \"ferrari\" and \"bmw\", then \"ferrari\"\n * and \"bmw\" will have populated LiveArrays, but the LiveArray for \"car\"\n * would be empty.\n *\n * @legacy we recommend againt using LiveArrays. Use {@link Store.request} instead\n */\nexport interface LegacyLiveArray<T = unknown> extends LegacyArray<T> {\n /**\n * Whether this LiveArray has loaded. LiveArrays are always considered\n * loaded once created.\n */\n isLoaded: boolean;\n\n /** @internal */\n DEPRECATED_CLASS_NAME: string;\n\n /**\n * The resource type (`ResourceType`) whose records this LiveArray contains.\n */\n modelName: TypeFromInstanceOrString<T>;\n}\n\n/**\n * The options for {@link createLegacyLiveArray}\n *\n * @private\n */\nexport interface LegacyLiveArrayCreateOptions {\n store: Store;\n manager: MinimumManager;\n source: ResourceKey[];\n type: string;\n}\n\n/**\n * Creates a {@link LegacyLiveArray}\n *\n * @internal\n */\nexport function createLegacyLiveArray(options: LegacyLiveArrayCreateOptions): LegacyLiveArray {\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: false,\n source: options.source,\n data: null,\n features: {\n modelName: options.type,\n update,\n _update: _updateLiveArray,\n save,\n DEPRECATED_CLASS_NAME: 'LiveArray',\n isUpdating: false,\n isLoaded: true,\n _updatingPromise: null,\n },\n extensions: null,\n options: null,\n destroy: null,\n mutate: null,\n }) as LegacyLiveArray;\n}\n\nfunction upgradeThis(obj: unknown): asserts obj is LegacyLiveArray {}\n\nfunction _updateLiveArray(this: ReactiveResourceArray): Promise<ReactiveResourceArray> {\n upgradeThis(this);\n const context = this[Context];\n assert(`_update cannot be used with this array`, this.modelName);\n // @ts-expect-error typescript is unable to handle the complexity of\n // T = unknown, modelName = string\n // T extends TypedRecordInstance, modelName = TypeFromInstance<T>\n // both being valid options to pass through here.\n return context.store.findAll<T>(this.modelName, { reload: true });\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport type { ObjectValue } from '../../../types/json/raw.ts';\nimport type { ImmutableRequestInfo } from '../../../types/request.ts';\nimport type { Links, Meta, PaginationLinks } from '../../../types/spec/json-api-raw.ts';\nimport type { RecordArrayManager } from '../managers/record-array-manager.ts';\nimport { type MinimumManager, save, update } from './-utils.ts';\nimport type { LegacyLiveArray, LegacyLiveArrayCreateOptions } from './legacy-live-array.ts';\nimport { createReactiveResourceArray, destroy, type ReactiveResourceArray } from './resource-array.ts';\n\n/**\n * QueryArrays contain the primary records returned when querying\n * for records by `ResourceType`.\n *\n * ### Basic Example\n *\n * For instance, if an application were to have a `'user'` type:\n *\n * ```ts\n * const users = await store.query('user', { name: 'Chris' });\n * ```\n *\n * ---\n *\n * \n *\n * ### QueryArrays are Arrays\n *\n * QueryArrays have all array APIs, and will report `true`\n * for both `queryArray instanceof Array` and `Array.isArray(queryArray)`\n *\n * However, any mutation of the array will throw an error.\n *\n * ---\n *\n * \n *\n * ### Reactive\n *\n * If a record in a QueryArray is deleted and unloaded, it will be\n * automatically removed from the array.\n *\n * ---\n *\n * \n *\n * ### Immutable\n *\n * Records cannot be directly added to or removed from a QueryArray.\n *\n * ---\n *\n * \n *\n * ### Polymorphism\n *\n * QueryArrays are not intended to be polymorphic. If your application has\n * an abstract type \"car\" with concrete types \"ferrari\" and \"bmw\", a query\n * which returns primary data containing both ferraris and bmws will *likely*\n * work, but it is not guaranteed.\n *\n * In contrast, the {@link ReactiveResourceArray} returned when using {@link Store.request}\n * is guaranteed to work with polymorphic responses.\n *\n * ---\n *\n * \n *\n * ### Memory Leaks\n *\n * QueryArrays are meant to be long lived. They can be refreshed using\n * `array.update()`, and destroyed via `array.destroy()`.\n *\n * Unlike most Reactive state in WarpDrive, applications must choose to call\n * `destroy` when the `QueryArray` is no longer needed, else the array instance\n * will be retained until either the application or the store which created it\n * are destroyed. Destroying a QueryArray does not remove its records\n * from the cache, but it does remove the array as well as the overhead it requires\n * from the store for book-keeping.\n *\n * @legacy we recommend againt using QueryArrays. Use {@link Store.request} instead\n */\nexport interface LegacyQueryArray<T = unknown> extends LegacyLiveArray<T> {\n /**\n * The query originally passed to `store.query()` that produced this\n * QueryArray. Used by `update()` to re-run the query.\n */\n query: ImmutableRequestInfo | Record<string, unknown> | null;\n destroy(): void;\n\n /**\n * The JSON:API `links` included in the response that produced this\n * QueryArray, if any.\n */\n links: PaginationLinks | Links | null;\n\n /**\n * The JSON:API `meta` included in the response that produced this\n * QueryArray, if any.\n */\n meta: Meta | null;\n}\n\n/**\n * The options for {@link createLegacyQueryArray}\n *\n * See also {@link LegacyLiveArrayCreateOptions} which\n * this extends.\n *\n * @internal\n */\nexport interface LegacyQueryArrayCreateOptions extends LegacyLiveArrayCreateOptions {\n query: ImmutableRequestInfo | Record<string, unknown> | null;\n isLoaded: boolean;\n links: PaginationLinks | Links | null;\n meta: Meta | null;\n}\n\n/**\n * Creates a {@link LegacyQueryArray}\n *\n * Options: {@link LegacyQueryArrayCreateOptions}\n *\n * @internal\n */\nexport function createLegacyQueryArray<T = unknown>(options: LegacyQueryArrayCreateOptions): LegacyQueryArray<T> {\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: false,\n source: options.source,\n data: {\n links: options.links,\n meta: options.meta,\n } as ObjectValue,\n features: {\n query: options.query,\n modelName: options.type,\n update,\n _update: _updateCollection,\n save,\n DEPRECATED_CLASS_NAME: 'LegacyQueryArray',\n isUpdating: false,\n isLoaded: options.isLoaded,\n _updatingPromise: null,\n },\n extensions: null,\n options: null,\n destroy: destroyCollection,\n mutate: null,\n }) as LegacyQueryArray<T>;\n}\n\nfunction _updateCollection(this: LegacyQueryArray): Promise<LegacyQueryArray> {\n const context = this[Context];\n const { query } = this;\n\n assert(`update cannot be used with this array`, this.modelName);\n assert(`update cannot be used with no query`, query);\n // @ts-expect-error typescript is unable to handle the complexity of\n // T = unknown, modelName = string\n // T extends TypedRecordInstance, modelName = TypeFromInstance<T>\n // both being valid options to pass through here.\n const promise = context.store.query<T>(this.modelName, query as Record<string, unknown>, { _recordArray: this });\n\n return promise;\n}\n\nfunction upgradeManager(obj: MinimumManager): asserts obj is RecordArrayManager {}\n\nfunction destroyCollection(this: ReactiveResourceArray, clear: boolean): void {\n destroy.call(this, clear ?? false);\n const { manager } = this[Context];\n upgradeManager(manager);\n manager._managed.delete(this);\n manager._pending.delete(this);\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport { notifyInternalSignal } from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { RequestKey, ResourceKey } from '../../../types/identifier.ts';\nimport type { ImmutableRequestInfo } from '../../../types/request.ts';\nimport type { CollectionResourceDocument } from '../../../types/spec/json-api-raw.ts';\nimport type { LegacyLiveArray } from '../record-arrays/legacy-live-array.ts';\nimport { createLegacyLiveArray } from '../record-arrays/legacy-live-array.ts';\nimport {\n createLegacyQueryArray,\n type LegacyQueryArray,\n type LegacyQueryArrayCreateOptions,\n} from '../record-arrays/legacy-query.ts';\nimport {\n createRequestCollection,\n type ReactiveRequestCollectionCreateArgs,\n type ReactiveResourceArray,\n} from '../record-arrays/resource-array.ts';\nimport type { Store } from '../store-service.ts';\nimport type { CacheOperation, DocumentCacheOperation, UnsubscribeToken } from './notification-manager.ts';\n\nconst FAKE_ARR = getOrSetGlobal('FAKE_ARR', {});\nconst SLICE_BATCH_SIZE = 4761;\n/**\n * This is a clever optimization.\n *\n * clever optimizations rarely stand the test of time, so if you're\n * ever curious or think something better is possible please benchmark\n * and discuss. The benchmark for this at the time of writing is in\n * `scripts/benchmark-push.js`\n *\n * This approach turns out to be 150x faster in Chrome and node than\n * simply using push or concat. It's highly susceptible to the specifics\n * of the batch size, and may require tuning.\n *\n * Clever optimizations should always come with a `why`. This optimization\n * exists for two reasons.\n *\n * 1) array.push(...objects) and Array.prototype.push.apply(arr, objects)\n * are susceptible to stack overflows. The size of objects at which this\n * occurs varies by environment, browser, and current stack depth and memory\n * pressure; however, it occurs in all browsers in fairly pristine conditions\n * somewhere around 125k to 200k elements. Since WarpDrive regularly encounters\n * arrays larger than this in size, we cannot use push.\n *\n * 2) `array.concat` or simply setting the array to a new reference is often an\n * easier approach; however, native Proxy to an array cannot swap it's target array\n * and attempts at juggling multiple array sources have proven to be victim to a number\n * of browser implementation bugs. Should these bugs be addressed then we could\n * simplify to using `concat`, however, do note this is currently 150x faster\n * than concat, and due to the overloaded signature of concat will likely always\n * be faster.\n *\n * Sincerely,\n * - runspired (Chris Thoburn) 08/21/2022\n *\n * @private\n * @param target the array to push into\n * @param source the items to push into target\n */\nexport function fastPush<T>(target: T[], source: T[]): void {\n let batch;\n while (source.length > SLICE_BATCH_SIZE) {\n batch = source.splice(0, SLICE_BATCH_SIZE);\n target.push(...batch);\n }\n target.push(...source);\n}\n\ninterface LegacyQueryInit {\n type: string;\n query: ImmutableRequestInfo | Record<string, unknown>;\n}\ninterface AnonymousRequestCollectionInit {\n source: ResourceKey[];\n}\ninterface RequestCollectionInit {\n source: ResourceKey[];\n requestKey: RequestKey;\n}\n\ntype CollectionInit = LegacyQueryInit | AnonymousRequestCollectionInit | RequestCollectionInit;\n\ntype ChangeSet = Map<ResourceKey, 'add' | 'del'>;\n\n/**\n @hideconstructor\n @private\n*/\nexport class RecordArrayManager {\n /** @internal */\n declare private store: Store;\n\n /** @internal */\n declare private isDestroying: boolean;\n\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _set: Map<ReactiveResourceArray, Set<ResourceKey>>;\n /**\n * LiveArray (peekAll/findAll) array instances\n * keyed by their ResourceType.\n *\n * @internal\n */\n declare _live: Map<string, LegacyLiveArray>;\n /** @internal */\n declare _managed: Set<ReactiveResourceArray>;\n /**\n * Buffered changes to apply keyed by the array to\n * which to apply them to.\n *\n * @internal\n */\n declare _pending: Map<ReactiveResourceArray, ChangeSet>;\n /**\n * An inverse map from ResourceKey to the list\n * of arrays it can be found in, useful for fast updates\n * when state changes to a resource occur.\n *\n * @internal\n */\n declare private _identifiers: Map<ResourceKey, Set<ReactiveResourceArray>>;\n /**\n * When we do not yet have a LiveArray, this keeps track of\n * the added/removed identifiers to enable us to more efficiently\n * produce the LiveArray later.\n *\n * It's possible that using a Set and only storing additions instead of\n * additions and deletes would be more efficient.\n *\n * @internal\n */\n declare private _staged: Map<string, ChangeSet>;\n /** @internal */\n declare private _subscription: UnsubscribeToken;\n /** @internal */\n declare private _documentSubscription: UnsubscribeToken;\n /**\n * KeyedArrays are arrays associated to a specific RequestKey.\n * @internal\n */\n declare private _keyedArrays: Map<string, ReactiveResourceArray>;\n /**\n * The visibility set tracks whether a given identifier should\n * be shown in RecordArrays. It is used to dedupe added/removed\n * and state change events.\n *\n * As a Map, it grows to be very large - there may be ways to\n * reduce its size by instead migrating to it functioning as\n * an exclusion list. Any entry not in the list would be considered\n * visible.\n * @internal\n */\n declare private _visibilitySet: Map<ResourceKey, boolean>;\n\n constructor(options: { store: Store }) {\n this.store = options.store;\n this.isDestroying = false;\n this.isDestroyed = false;\n this._live = new Map();\n this._managed = new Set();\n this._pending = new Map();\n this._staged = new Map();\n this._keyedArrays = new Map();\n this._identifiers = new Map();\n this._set = new Map();\n this._visibilitySet = new Map();\n\n this._documentSubscription = this.store.notifications.subscribe(\n 'document',\n (identifier: RequestKey, type: DocumentCacheOperation) => {\n if (type === 'updated' && this._keyedArrays.has(identifier.lid)) {\n const array = this._keyedArrays.get(identifier.lid)!;\n this.dirtyArray(array, 0, true);\n }\n }\n );\n\n this._subscribeToResourceChanges();\n }\n\n /** @internal */\n private _subscribeToResourceChanges() {\n this._subscription = this.store.notifications.subscribe(\n 'resource',\n (identifier: ResourceKey, type: CacheOperation) => {\n const schema = this.store.schema.resource?.(identifier);\n // If we are a polaris mode schema\n // and we are in the `isNew` state, we are kept hidden from\n // record arrays.\n if (schema && (!('legacy' in schema) || !schema.legacy)) {\n if (this.store.cache.isNew(identifier)) {\n return;\n }\n }\n\n if (type === 'added') {\n this._visibilitySet.set(identifier, true);\n this.identifierAdded(identifier);\n } else if (type === 'removed') {\n this._visibilitySet.set(identifier, false);\n this.identifierRemoved(identifier);\n } else if (type === 'state') {\n this.identifierChanged(identifier);\n }\n }\n );\n }\n\n /** @internal */\n _syncArray(array: ReactiveResourceArray): void {\n const pending = this._pending.get(array);\n const isLegacyQuery = isLegacyQueryArray(array);\n\n if ((isLegacyQuery && !pending) || this.isDestroying || this.isDestroyed) {\n return;\n }\n\n // first flush any staged changes\n if (pending) {\n sync(array, pending, this._set.get(array)!);\n this._pending.delete(array);\n }\n\n // then pull new state if required\n if (!isLegacyQuery && !isLegacyLiveArray(array)) {\n const context = array[Context];\n const signal = context.signal;\n const identifier = context.options!.requestKey as RequestKey;\n\n // we only need to rebuild the array from cache if a full sync is required\n // due to notification that the cache has changed\n if (signal.value === 'cache-sync') {\n const doc = this.store.cache.peek(identifier);\n assert(`Expected to find a document for ${identifier.lid} but found none`, doc);\n const data = !('data' in doc) || !Array.isArray(doc.data) ? [] : doc.data;\n // TODO technically we should destroy here if\n // !('data' in doc) || !Array.isArray(doc.data)\n // is true.\n this.populateManagedArray(array, data, null);\n }\n }\n }\n\n mutate(mutation: LocalRelationshipOperation): void {\n this.store.cache.mutate(mutation);\n }\n\n /**\n Get the `RecordArray` for a modelName, which contains all loaded records of\n given modelName.\n\n @private\n */\n liveArrayFor(type: string): LegacyLiveArray {\n let array = this._live.get(type);\n const identifiers: ResourceKey[] = [];\n const staged = this._staged.get(type);\n if (staged) {\n staged.forEach((value, key) => {\n if (value === 'add') {\n identifiers.push(key);\n }\n });\n this._staged.delete(type);\n }\n\n if (!array) {\n array = createLegacyLiveArray({\n store: this.store,\n manager: this,\n source: identifiers,\n type,\n });\n this._live.set(type, array);\n this._set.set(array, new Set(identifiers));\n }\n\n return array;\n }\n\n getCollection(config: LegacyQueryInit): LegacyQueryArray;\n getCollection(config: AnonymousRequestCollectionInit): ReactiveResourceArray;\n getCollection(config: RequestCollectionInit): ReactiveResourceArray;\n getCollection(config: CollectionInit): ReactiveResourceArray {\n if ('requestKey' in config && this._keyedArrays.has(config.requestKey.lid)) {\n return this._keyedArrays.get(config.requestKey.lid)!;\n }\n\n let array: ReactiveResourceArray;\n if ('requestKey' in config) {\n const options: ReactiveRequestCollectionCreateArgs = {\n store: this.store,\n manager: this,\n source: config.source,\n options: {\n requestKey: config.requestKey,\n },\n };\n array = createRequestCollection(options);\n this._keyedArrays.set(config.requestKey.lid, array);\n this._set.set(array, new Set(config.source));\n associate(this._identifiers, array, config.source);\n } else if ('query' in config) {\n const options: LegacyQueryArrayCreateOptions = {\n store: this.store,\n manager: this,\n source: [],\n type: config.type,\n query: config.query,\n isLoaded: false,\n links: null,\n meta: null,\n };\n array = createLegacyQueryArray(options);\n this._set.set(array, new Set());\n } else {\n const options: ReactiveRequestCollectionCreateArgs = {\n store: this.store,\n manager: this,\n source: config.source,\n options: null,\n };\n array = createRequestCollection(options);\n this._set.set(array, new Set(config.source));\n associate(this._identifiers, array, config.source);\n }\n\n this._managed.add(array);\n return array;\n }\n\n /** @internal */\n private dirtyArray(array: ReactiveResourceArray, delta: number, shouldSyncFromCache: boolean): void {\n if (array === FAKE_ARR) {\n return;\n }\n const signal = array[Context].signal;\n if (!signal.isStale || delta > 0) {\n notifyInternalSignal(signal);\n\n // when the cache has updated for our array, we need to\n // do a full rebuild of the array\n signal.value = shouldSyncFromCache ? 'cache-sync' : 'patch';\n }\n }\n\n /** @internal */\n private _getPendingFor(\n identifier: ResourceKey,\n includeManaged: boolean,\n isRemove?: boolean\n ): Map<ReactiveResourceArray, ChangeSet> | void {\n if (this.isDestroying || this.isDestroyed) {\n return;\n }\n\n const liveArray = this._live.get(identifier.type);\n const allPending = this._pending;\n const pending: Map<ReactiveResourceArray, ChangeSet> = new Map();\n\n if (includeManaged) {\n const managed = this._identifiers.get(identifier);\n if (managed) {\n managed.forEach((arr) => {\n let changes = allPending.get(arr);\n if (!changes) {\n changes = new Map();\n allPending.set(arr, changes);\n }\n pending.set(arr, changes);\n });\n }\n }\n\n // during unloadAll we can ignore removes since we've already\n // cleared the array.\n if (liveArray && liveArray[Context].source.length === 0 && isRemove) {\n const pendingLive = allPending.get(liveArray);\n if (!pendingLive || pendingLive.size === 0) {\n return pending;\n }\n }\n\n if (!liveArray) {\n // start building a changeset for when we eventually\n // do have a live array\n let changes = this._staged.get(identifier.type);\n if (!changes) {\n changes = new Map();\n this._staged.set(identifier.type, changes);\n }\n pending.set(FAKE_ARR as ReactiveResourceArray, changes);\n } else {\n let changes = allPending.get(liveArray);\n if (!changes) {\n changes = new Map();\n allPending.set(liveArray, changes);\n }\n pending.set(liveArray, changes);\n }\n\n return pending;\n }\n\n /**\n * @private\n */\n populateManagedArray(\n array: ReactiveResourceArray,\n identifiers: ResourceKey[],\n payload: CollectionResourceDocument | null\n ): void {\n this._pending.delete(array);\n const source = array[Context].source;\n assert(\n `The new state of the collection should not be using the same array reference as the original state.`,\n source !== identifiers\n );\n const old = source.slice();\n source.length = 0;\n fastPush(source, identifiers);\n this._set.set(array, new Set(identifiers));\n\n if (isLegacyQueryArray(array)) {\n notifyInternalSignal(array[Context].signal);\n array.meta = payload?.meta || null;\n array.links = payload?.links || null;\n array.isLoaded = true;\n }\n\n disassociate(this._identifiers, array, old);\n associate(this._identifiers, array, identifiers);\n }\n\n /** @internal */\n private identifierAdded(identifier: ResourceKey): void {\n const changeSets = this._getPendingFor(identifier, false);\n if (changeSets) {\n changeSets.forEach((changes, array) => {\n const existing = changes.get(identifier);\n if (existing === 'del') {\n changes.delete(identifier);\n } else {\n changes.set(identifier, 'add');\n\n this.dirtyArray(array, changes.size, false);\n }\n });\n }\n }\n\n /** @internal */\n private identifierRemoved(identifier: ResourceKey): void {\n const changeSets = this._getPendingFor(identifier, true, true);\n if (changeSets) {\n changeSets.forEach((changes, array) => {\n const existing = changes.get(identifier);\n if (existing === 'add') {\n changes.delete(identifier);\n } else {\n changes.set(identifier, 'del');\n\n this.dirtyArray(array, changes.size, false);\n }\n });\n }\n }\n\n /** @internal */\n private identifierChanged(identifier: ResourceKey): void {\n const newState = this.store._instanceCache.recordIsLoaded(identifier, true);\n\n // if the change matches the most recent direct added/removed\n // state, then we can ignore it\n if (this._visibilitySet.get(identifier) === newState) {\n return;\n }\n\n if (newState) {\n this.identifierAdded(identifier);\n } else {\n this.identifierRemoved(identifier);\n }\n }\n\n pause(): void {\n this.store.notifications.unsubscribe(this._subscription);\n }\n resume(): void {\n this._subscribeToResourceChanges();\n }\n\n /**\n * @internal\n */\n clear(isClear = true): void {\n for (const array of this._live.values()) {\n array.destroy(isClear);\n }\n for (const array of this._managed.values()) {\n array.destroy(isClear);\n }\n this._managed.clear();\n this._identifiers.clear();\n this._pending.clear();\n for (const set of this._set.values()) {\n set.clear();\n }\n this._visibilitySet.clear();\n }\n\n destroy(): void {\n this.isDestroying = true;\n this.clear(false);\n this._live.clear();\n this.store.notifications.unsubscribe(this._subscription);\n this.store.notifications.unsubscribe(this._documentSubscription);\n this.isDestroyed = true;\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRecordArrayManager extends RecordArrayManager {\n _live: Map<string, LegacyLiveArray>;\n _pending: Map<ReactiveResourceArray, ChangeSet>;\n _managed: Set<ReactiveResourceArray>;\n clear(isClear?: boolean): void;\n}\n\nfunction associate(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifiers: ResourceKey[]\n) {\n for (let i = 0; i < identifiers.length; i++) {\n const identifier = identifiers[i];\n let cache = ArraysCache.get(identifier);\n if (!cache) {\n cache = new Set();\n ArraysCache.set(identifier, cache);\n }\n cache.add(array);\n }\n}\n\nfunction disassociate(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifiers: ResourceKey[]\n) {\n for (let i = 0; i < identifiers.length; i++) {\n disassociateIdentifier(ArraysCache, array, identifiers[i]);\n }\n}\n\nexport function disassociateIdentifier(\n ArraysCache: Map<ResourceKey, Set<ReactiveResourceArray>>,\n array: ReactiveResourceArray,\n identifier: ResourceKey\n): void {\n const cache = ArraysCache.get(identifier);\n if (cache) {\n cache.delete(array);\n }\n}\n\nfunction sync(array: ReactiveResourceArray, changes: Map<ResourceKey, 'add' | 'del'>, arraySet: Set<ResourceKey>) {\n const state = array[Context].source;\n const adds: ResourceKey[] = [];\n const removes: ResourceKey[] = [];\n changes.forEach((value, key) => {\n if (value === 'add') {\n // likely we want to keep a Set along-side\n if (arraySet.has(key)) {\n return;\n }\n adds.push(key);\n arraySet.add(key);\n } else {\n if (arraySet.has(key)) {\n removes.push(key);\n arraySet.delete(key);\n }\n }\n });\n if (removes.length) {\n if (removes.length === state.length) {\n state.length = 0;\n // changing the reference breaks the Proxy\n // state = array[SOURCE] = [];\n } else {\n removes.forEach((i) => {\n const index = state.indexOf(i);\n if (index !== -1) {\n state.splice(index, 1);\n arraySet.delete(i);\n }\n });\n }\n }\n\n if (adds.length) {\n fastPush(state, adds);\n // changing the reference breaks the Proxy\n // else we could do this\n /*\n if (state.length === 0) {\n array[SOURCE] = adds;\n } else {\n array[SOURCE] = state.concat(adds);\n }\n */\n }\n}\n\nfunction isLegacyQueryArray(array: ReactiveResourceArray): array is LegacyQueryArray {\n const context = array[Context];\n return context.features !== null && context.features.DEPRECATED_CLASS_NAME === 'LegacyQueryArray';\n}\n\nfunction isLegacyLiveArray(array: ReactiveResourceArray): array is LegacyLiveArray {\n const context = array[Context];\n return context.features !== null && context.features.DEPRECATED_CLASS_NAME === 'LiveArray';\n}\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { FindRecordOptions } from '../../-types/q/store.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { Store } from '../store-service.ts';\n\nconst Touching: '___(unique) Symbol(Touching)' = getOrSetGlobal('Touching', Symbol('touching'));\nexport const RequestPromise: '___(unique) Symbol(RequestPromise)' = getOrSetGlobal('RequestPromise', Symbol('promise'));\nconst EMPTY_ARR: RequestCacheRequestState[] = DEBUG ? (Object.freeze([]) as unknown as RequestCacheRequestState[]) : [];\n\n/**\n * The base shape for a query or mutation operation tracked by the\n * {@link RequestStateService} for a given resource.\n */\nexport interface Operation {\n /** the name of the operation being performed, e.g. `'findRecord'` or `'saveRecord'`. */\n op: string;\n /** the options supplied for the operation, if any. */\n options: FindRecordOptions | undefined;\n /** the resource identifier the operation is being performed for. */\n recordIdentifier: ResourceKey;\n}\n\n/**\n * A {@link Operation} tracked by the {@link RequestStateService} representing\n * a `findRecord` query for a resource.\n */\nexport interface FindRecordQuery extends Operation {\n /** identifies this operation as a `findRecord` query. */\n op: 'findRecord';\n}\n\n/**\n * A {@link Operation} tracked by the {@link RequestStateService} representing\n * a `saveRecord` mutation for a resource.\n */\nexport interface SaveRecordMutation extends Operation {\n /** identifies this operation as a `saveRecord` mutation. */\n op: 'saveRecord';\n}\n\n/**\n * Describes the request associated with a {@link RequestCacheRequestState},\n * as tracked by the {@link RequestStateService}.\n */\nexport interface Request {\n /** the operation(s) being performed by this request. */\n data: Operation[];\n /** options supplied for the request, if any. */\n options?: Record<string, unknown>;\n}\n\nexport type RequestStates = 'pending' | 'fulfilled' | 'rejected';\n\n/**\n * The tracked state of a request as reported by the {@link RequestStateService},\n * e.g. via {@link RequestStateService.subscribeForRecord} or\n * {@link RequestStateService.getPendingRequestsForRecord}.\n */\nexport interface RequestCacheRequestState {\n /** the current lifecycle state of the request. */\n state: RequestStates;\n /** whether the request is a `query` (find) or a `mutation` (save). */\n type: 'query' | 'mutation';\n /** the {@link Request} describing the operation(s) this state is for. */\n request: Request;\n /** the response for the request, present once it has settled. */\n response?: Response;\n}\n\nexport interface Response {\n // rawData: unknown;\n data: unknown;\n}\n\ninterface InternalRequest extends RequestCacheRequestState {\n [Touching]: ResourceKey[];\n [RequestPromise]?: Promise<unknown>;\n}\n\ntype RecordOperation = FindRecordQuery | SaveRecordMutation;\nexport type RequestSubscription = (requestState: RequestCacheRequestState) => void;\n\nfunction hasRecordIdentifier(op: Operation): op is RecordOperation {\n return 'recordIdentifier' in op;\n}\n\n/**\n * The RequestStateService is used to track the state of requests\n * for fetching or updating known resource identifies that are inflight.\n *\n * @hideconstructor\n * @public\n */\nexport class RequestStateService {\n /** @internal */\n _pending: Map<ResourceKey, InternalRequest[]> = new Map();\n /** @internal */\n private _done: Map<ResourceKey, InternalRequest[]> = new Map();\n /** @internal */\n private _subscriptions: Map<ResourceKey, RequestSubscription[]> = new Map();\n /** @internal */\n private _toFlush: InternalRequest[] = [];\n /** @internal */\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n /** @internal */\n _clearEntries(identifier: ResourceKey): void {\n this._done.delete(identifier);\n }\n /** @internal */\n _enqueue<T>(promise: Promise<T>, queryRequest: Request): Promise<T> {\n const query = queryRequest.data[0];\n if (hasRecordIdentifier(query)) {\n const identifier = query.recordIdentifier;\n const type = query.op === 'saveRecord' ? ('mutation' as const) : ('query' as const);\n if (!this._pending.has(identifier)) {\n this._pending.set(identifier, []);\n }\n const request: InternalRequest = {\n state: 'pending',\n request: queryRequest,\n type,\n } as InternalRequest;\n request[Touching] = [query.recordIdentifier];\n request[RequestPromise] = promise;\n this._pending.get(identifier)!.push(request);\n this._triggerSubscriptions(request);\n return promise.then(\n (result) => {\n this._dequeue(identifier, request);\n const finalizedRequest = {\n state: 'fulfilled',\n request: queryRequest,\n type,\n response: { data: result },\n } as InternalRequest;\n finalizedRequest[Touching] = request[Touching];\n this._addDone(finalizedRequest);\n this._triggerSubscriptions(finalizedRequest);\n return result;\n },\n (error) => {\n this._dequeue(identifier, request);\n const finalizedRequest = {\n state: 'rejected',\n request: queryRequest,\n type,\n response: { data: error },\n } as InternalRequest;\n finalizedRequest[Touching] = request[Touching];\n this._addDone(finalizedRequest);\n this._triggerSubscriptions(finalizedRequest);\n throw error;\n }\n );\n }\n assert(`Expected a well formed query`);\n }\n\n /** @internal */\n private _triggerSubscriptions(req: InternalRequest): void {\n if (req.state === 'pending') {\n this._flushRequest(req);\n return;\n }\n this._toFlush.push(req);\n\n if (this._toFlush.length === 1) {\n this._store.notifications._onNextFlush(() => {\n this._flush();\n });\n }\n }\n\n /** @internal */\n private _flush(): void {\n this._toFlush.forEach((req) => {\n this._flushRequest(req);\n });\n this._toFlush = [];\n }\n\n /** @internal */\n private _flushRequest(req: InternalRequest): void {\n req[Touching].forEach((identifier: ResourceKey) => {\n const subscriptions = this._subscriptions.get(identifier);\n if (subscriptions) {\n subscriptions.forEach((callback) => callback(req));\n }\n });\n }\n\n /** @internal */\n private _dequeue(identifier: ResourceKey, request: InternalRequest): void {\n const pending = this._pending.get(identifier)!;\n this._pending.set(\n identifier,\n pending.filter((req) => req !== request)\n );\n }\n\n /** @internal */\n private _addDone(request: InternalRequest): void {\n request[Touching].forEach((identifier) => {\n // TODO add support for multiple\n const requestDataOp = request.request.data[0].op;\n let requests = this._done.get(identifier);\n\n if (requests) {\n requests = requests.filter((req) => {\n // TODO add support for multiple\n let data: Operation;\n if (Array.isArray(req.request.data)) {\n data = req.request.data[0];\n } else {\n data = req.request.data;\n }\n return data.op !== requestDataOp;\n });\n }\n requests = requests || [];\n requests.push(request);\n this._done.set(identifier, requests);\n });\n }\n\n /**\n * Subscribe to requests for a given resource identity.\n *\n * The callback will receive the current state of the request.\n *\n * ```ts\n * interface RequestState {\n * state: 'pending' | 'fulfilled' | 'rejected';\n * type: 'query' | 'mutation';\n * request: Request;\n * response?: { data: unknown };\n * }\n * ```\n *\n * Note: It should be considered dangerous to use this API for more than simple\n * state derivation or debugging. The `request` and `response` properties are poorly\n * spec'd and may change unexpectedly when shifting what Handlers are in use or how\n * requests are issued from the Store.\n *\n * We expect to revisit this API in the near future as we continue to refine the\n * RequestManager ergonomics, as a simpler but more powerful direct integration\n * with the RequestManager for these purposes is likely to be a better long-term\n * design.\n *\n * @public\n * @param {ResourceKey} identifier\n * @param {(state: RequestCacheRequestState) => void} callback\n */\n subscribeForRecord(identifier: ResourceKey, callback: RequestSubscription): void {\n let subscriptions = this._subscriptions.get(identifier);\n if (!subscriptions) {\n subscriptions = [];\n this._subscriptions.set(identifier, subscriptions);\n }\n subscriptions.push(callback);\n }\n\n /**\n * Retrieve all active requests for a given resource identity.\n *\n * @public\n * @param {ResourceKey} identifier\n * @return {RequestCacheRequestState[]} an array of request states for any pending requests for the given identifier\n */\n getPendingRequestsForRecord(identifier: ResourceKey): RequestCacheRequestState[] {\n return this._pending.get(identifier) || EMPTY_ARR;\n }\n\n /**\n * Retrieve the last completed request for a given resource identity.\n *\n * @public\n * @param {ResourceKey} identifier\n * @return {RequestCacheRequestState | null} the state of the most recent request for the given identifier\n */\n getLastRequestForRecord(identifier: ResourceKey): RequestCacheRequestState | null {\n const requests = this._done.get(identifier);\n if (requests) {\n return requests[requests.length - 1];\n }\n return null;\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRequestStateService extends RequestStateService {\n _pending: Map<ResourceKey, InternalRequest[]>;\n _clearEntries(identifier: ResourceKey): void;\n _enqueue<T>(promise: Promise<T>, queryRequest: Request): Promise<T>;\n}\n","export default function esCompat(m) {\n return m?.__esModule ? m : { default: m, ...m };\n}\n","// this import location is deprecated but breaks in 4.8 and older\nimport { deprecate } from '@ember/debug';\n\nimport { dependencySatisfies, importSync, macroCondition } from '@embroider/macros';\n\nimport {\n __INTERNAL_LOG_NATIVE_MAP_SET_COUNTS,\n LOG_METRIC_COUNTS,\n LOG_REQUESTS,\n} from '@warp-drive/core/build-config/debugging';\nimport {\n DEPRECATE_STORE_EXTENDS_EMBER_OBJECT,\n ENABLE_LEGACY_SCHEMA_SERVICE,\n} from '@warp-drive/core/build-config/deprecations';\nimport { DEBUG, TESTING } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { CacheCapabilitiesManager } from '../-types/q/cache-capabilities-manager.ts';\nimport type { OpaqueRecordInstance } from '../-types/q/record-instance.ts';\nimport type { Graph } from '../../graph/-private.ts';\n// oxlint-disable-next-line no-unused-vars\nimport { ReactiveResource } from '../../reactive.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { ReactiveDocument } from '../../reactive/-private/document.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheHandler as CacheHandlerInterface, Future } from '../../request.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { Fetch } from '../../request/-private/fetch.ts';\nimport type { PrivateRequestManager, RequestManager } from '../../request/-private/manager.ts';\nimport type { Cache } from '../../types/cache.ts';\nimport type { PersistedResourceKey, ResourceKey } from '../../types/identifier.ts';\nimport type { TypedRecordInstance, TypeFromInstance } from '../../types/record.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheOptions, RequestInfo } from '../../types/request.ts';\nimport { EnableHydration } from '../../types/request.ts';\nimport { getRuntimeConfig, setLogging } from '../../types/runtime.ts';\nimport type { SchemaService } from '../../types/schema/schema-service.ts';\nimport type { ResourceDocument } from '../../types/spec/document.ts';\nimport type {\n CollectionResourceDocument,\n EmptyResourceDocument,\n JsonApiDocument,\n ResourceIdentifierObject,\n SingleResourceDocument,\n} from '../../types/spec/json-api-raw.ts';\nimport type { Type } from '../../types/symbols.ts';\n// DEPRECATED STORE METHODS -- see the second `Store` interface below\nimport type {\n FindAllOptions,\n FindRecordOptions,\n LegacyResourceQuery,\n ModelSchema,\n QueryOptions,\n RecordReference,\n} from '../deprecated/-private.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { CacheHandler, StoreRequestInput } from './cache-handler/handler.ts';\nimport type { CachePolicy } from './cache-handler/types.ts';\nimport {\n getNewRecord,\n InstanceCache,\n peekResourceKey,\n recordIdentifierFor,\n storeFor,\n} from './caches/instance-cache.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { PrivateCacheKeyManager, setIdentifierGenerationMethod } from './managers/cache-key-manager.ts';\nimport { CacheKeyManager } from './managers/cache-key-manager.ts';\nimport { CacheManager } from './managers/cache-manager.ts';\nimport type { PrivateNotificationManager } from './managers/notification-manager.ts';\nimport { NotificationManager } from './managers/notification-manager.ts';\nimport type { PrivateRecordArrayManager } from './managers/record-array-manager.ts';\nimport { RecordArrayManager } from './managers/record-array-manager.ts';\nimport type { PrivateRequestStateService } from './network/request-cache.ts';\nimport { RequestPromise, RequestStateService } from './network/request-cache.ts';\nimport type { LegacyLiveArray } from './record-arrays/legacy-live-array.ts';\nimport type { LegacyQueryArray } from './record-arrays/legacy-query.ts';\nimport { coerceId, ensureStringId } from './utils/coerce-id.ts';\nimport { normalizeModelName } from './utils/normalize-model-name.ts';\n\nif (TESTING) {\n // @ts-expect-error adding to globalThis\n globalThis.setWarpDriveLogging = setLogging;\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveRuntimeConfig = getRuntimeConfig;\n}\n\nif (LOG_METRIC_COUNTS) {\n // @ts-expect-error adding to globalThis\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData = globalThis.__WarpDriveMetricCountData || {};\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveMetricCounts = () => {\n // @ts-expect-error\n // oxlint-disable-next-line\n return structuredClone(globalThis.__WarpDriveMetricCountData);\n };\n\n // @ts-expect-error adding to globalThis\n globalThis.resetWarpDriveMetricCounts = () => {\n // @ts-expect-error\n globalThis.__WarpDriveMetricCountData = {};\n };\n\n if (__INTERNAL_LOG_NATIVE_MAP_SET_COUNTS) {\n // @ts-expect-error adding to globalThis\n globalThis.__primitiveInstanceId = 0;\n\n function interceptAndLog(\n klassName: 'Set' | 'Map' | 'WeakSet' | 'WeakMap',\n methodName: 'add' | 'set' | 'delete' | 'has' | 'get' | 'constructor'\n ) {\n const klass = globalThis[klassName];\n\n if (methodName === 'constructor') {\n const instantiationLabel = `new ${klassName}()`;\n // @ts-expect-error\n globalThis[klassName] = class extends klass {\n // @ts-expect-error\n constructor(...args) {\n // oxlint-disable-next-line\n super(...args);\n // @ts-expect-error\n\n const instanceId = globalThis.__primitiveInstanceId++;\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[instantiationLabel] =\n // @ts-expect-error\n // oxlint-disable-next-line\n (globalThis.__WarpDriveMetricCountData[instantiationLabel] || 0) + 1;\n // @ts-expect-error\n this.instanceName = `${klassName}:${instanceId} - ${new Error().stack?.split('\\n')[2]}`;\n }\n };\n } else {\n // @ts-expect-error\n // oxlint-disable-next-line\n const original = klass.prototype[methodName];\n const logName = `${klassName}.${methodName}`;\n\n // @ts-expect-error\n klass.prototype[methodName] = function (...args) {\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[logName] = (globalThis.__WarpDriveMetricCountData[logName] || 0) + 1;\n // @ts-expect-error\n const { instanceName } = this;\n if (!instanceName) {\n // @ts-expect-error\n const instanceId = globalThis.__primitiveInstanceId++;\n // @ts-expect-error\n this.instanceName = `${klassName}.${methodName}:${instanceId} - ${new Error().stack?.split('\\n')[2]}`;\n }\n const instanceLogName = `${logName} (${instanceName})`;\n // @ts-expect-error\n // oxlint-disable-next-line\n globalThis.__WarpDriveMetricCountData[instanceLogName] =\n // @ts-expect-error\n // oxlint-disable-next-line\n (globalThis.__WarpDriveMetricCountData[instanceLogName] || 0) + 1;\n // oxlint-disable-next-line\n return original.apply(this, args);\n };\n }\n }\n\n interceptAndLog('Set', 'constructor');\n interceptAndLog('Set', 'add');\n interceptAndLog('Set', 'delete');\n interceptAndLog('Set', 'has');\n interceptAndLog('Set', 'set');\n interceptAndLog('Set', 'get');\n\n interceptAndLog('Map', 'constructor');\n interceptAndLog('Map', 'set');\n interceptAndLog('Map', 'delete');\n interceptAndLog('Map', 'has');\n interceptAndLog('Map', 'add');\n interceptAndLog('Map', 'get');\n\n interceptAndLog('WeakSet', 'constructor');\n interceptAndLog('WeakSet', 'add');\n interceptAndLog('WeakSet', 'delete');\n interceptAndLog('WeakSet', 'has');\n interceptAndLog('WeakSet', 'set');\n interceptAndLog('WeakSet', 'get');\n\n interceptAndLog('WeakMap', 'constructor');\n interceptAndLog('WeakMap', 'set');\n interceptAndLog('WeakMap', 'delete');\n interceptAndLog('WeakMap', 'has');\n interceptAndLog('WeakMap', 'add');\n interceptAndLog('WeakMap', 'get');\n }\n}\n\nexport { storeFor };\n\n// We inline this list of methods to avoid importing EmberObject\ntype EmberObjectKey =\n | '_debugContainerKey'\n | '_super'\n | 'addObserver'\n | 'cacheFor'\n | 'concatenatedProperties'\n | 'decrementProperty'\n | 'destroy'\n | 'get'\n | 'getProperties'\n | 'incrementProperty'\n | 'init'\n | 'isDestroyed'\n | 'isDestroying'\n | 'mergedProperties'\n | 'notifyPropertyChange'\n | 'removeObserver'\n | 'reopen'\n | 'set'\n | 'setProperties'\n | 'toggleProperty'\n | 'toString'\n | 'willDestroy';\n\ntype DSModelKeys =\n | '___(unique) Symbol(Store)'\n | '___private_notifications'\n | '___recordState'\n | '_createSnapshot'\n | 'adapterError'\n | 'attr'\n | 'belongsTo'\n | 'changedAttributes'\n | 'currentState'\n | 'deleteRecord'\n | 'destroyRecord'\n | 'dirtyType'\n | 'eachAttribute'\n | 'eachRelationship'\n | 'errors'\n | 'hasDirtyAttributes'\n | 'hasMany'\n | 'inverseFor'\n | 'isDeleted'\n | 'isEmpty'\n | 'isError'\n | 'isLoaded'\n | 'isLoading'\n | 'isNew'\n | 'isReloading'\n | 'isSaving'\n | 'isValid'\n | 'relationshipFor'\n | 'reload'\n | 'rollbackAttributes'\n | 'save'\n | 'serialize'\n | 'store'\n | 'unloadRecord';\n\ntype CompatStore = Store & {\n adapterFor?: (\n type: string,\n _allowMissing?: boolean\n ) => undefined | { generateIdForRecord?(store: Store, type: string, properties: object): string };\n};\nfunction upgradeStore(store: Store): asserts store is CompatStore {}\n\ntype DownlevelArrays<T> = T extends Array<infer U> ? U[] : T;\ntype AwaitedKeys<T> = { [K in keyof T & string]: DownlevelArrays<Awaited<T[K]>> };\n\n// `AwaitedKeys` is needed here to resolve any promise types like `PromiseBelongsTo`.\ntype FilteredKeys<T> = AwaitedKeys<Omit<T, typeof Type | EmberObjectKey | DSModelKeys | 'constructor'>>;\n\ntype MaybeHasId = { id?: string | null };\n/**\n * Currently only records that extend object can be created via\n * store.createRecord. This is a limitation of the current API,\n * but can be worked around by creating a new identifier, running\n * the cache.clientDidCreate method, and then peeking the record\n * for the identifier.\n *\n * To assign primary key to a record during creation, only `id` will\n * work correctly for `store.createRecord`, other primary key may be\n * handled by updating the record after creation or using the flow\n * described above.\n *\n * TODO: These are limitations we want to (and can) address. If you\n * have need of lifting these limitations, please open an issue.\n *\n */\nexport type CreateRecordProperties<T = MaybeHasId & Record<string, unknown>> = T extends TypedRecordInstance\n ? Partial<FilteredKeys<T>>\n : T extends MaybeHasId\n ? MaybeHasId & Partial<FilteredKeys<T>>\n : MaybeHasId & Record<string, unknown>;\n\nexport interface CreateContext {\n lid?: string;\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype ConstructorFunction = new (...args: any[]) => any;\n// oxlint-disable-next-line typescript/no-extraneous-class\nconst EmptyClass: ConstructorFunction = class {\n // oxlint-disable-next-line no-useless-constructor\n constructor(args?: unknown) {}\n};\nconst _BaseClass = macroCondition(dependencySatisfies('ember-source', '*'))\n ? DEPRECATE_STORE_EXTENDS_EMBER_OBJECT\n ? (importSync('@ember/object') as typeof EmptyClass)\n : EmptyClass\n : EmptyClass;\n\nconst BaseClass: typeof EmptyClass = (_BaseClass as unknown as { default?: typeof EmptyClass }).default\n ? ((_BaseClass as unknown as { default?: typeof EmptyClass }).default as typeof EmptyClass)\n : _BaseClass;\n\nif (BaseClass !== EmptyClass) {\n deprecate(\n `The Store class extending from EmberObject is deprecated.\nPlease remove usage of EmberObject APIs and mark your class as not requiring it.\n\nTo mark the class as no longer extending from EmberObject, in ember-cli-build.js\nset the following config:\n\n\\`\\`\\`js\nconst app = new EmberApp(defaults, {\n emberData: {\n deprecations: {\n DEPRECATE_STORE_EXTENDS_EMBER_OBJECT: false\n }\n }\n});\n\\`\\`\\`\n`,\n false,\n {\n id: 'ember-data:deprecate-store-extends-ember-object',\n until: '6.0',\n for: 'ember-data',\n url: 'https://deprecations.emberjs.com/id/ember-data-deprecate-store-extends-ember-object',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n }\n );\n}\n\nexport interface Store {\n /**\n * Instantiation hook allowing applications or addons to configure the store\n * to utilize a custom Cache implementation.\n *\n * This hook should not be called directly by consuming applications or libraries.\n * Use `Store.cache` to access the Cache instance.\n *\n * @public\n */\n createCache(capabilities: CacheCapabilitiesManager): Cache;\n\n /**\n * A hook which an app or addon may implement. Called when\n * the Store is attempting to create a Record Instance for\n * a resource.\n *\n * This hook can be used to select or instantiate any desired\n * mechanism of presenting cache data to the ui for access\n * mutation, and interaction.\n *\n * @param identifier - The Resource CacheKey\n * @param createRecordArgs - An object containing any properties passed to `store.createRecord`\n * @return A record instance\n * @public\n */\n // oxlint-disable-next-line no-unused-vars\n instantiateRecord<T>(identifier: ResourceKey, createRecordArgs: { [key: string]: unknown }): OpaqueRecordInstance;\n\n /**\n * A hook which an app or addon may implement. Called when\n * the Store is destroying a Record Instance. This hook should\n * be used to teardown any custom record instances instantiated\n * with `instantiateRecord`.\n *\n * @public\n * @param record\n */\n teardownRecord(record: OpaqueRecordInstance): void;\n\n /**\n * This hook enables an app to supply a SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method will only be called once to instantiate the singleton\n * service, which can then be accessed via `store.schema`.\n *\n * For Example, to use the default SchemaService for ReactiveResource\n *\n * ```ts\n * import { SchemaService } from '@warp-drive/core/reactive';\n *\n * class extends Store {\n * createSchemaService() {\n * return new SchemaService();\n * }\n * }\n * ```\n *\n * Or to use the SchemaService for @warp-drive/legacy/model\n *\n * ```ts\n * import { buildSchema } from '@warp-drive/legacy/model';\n *\n * class extends Store {\n * createSchemaService() {\n * return buildSchema(this);\n * }\n * }\n * ```\n *\n * If you wish to chain services, you must either\n * instantiate each schema source directly or super to retrieve\n * an existing service. For convenience, when migrating from\n * `@warp-drive/legacy/model` to {@link ReactiveResource} a\n * SchemaService is provided that handles this transition\n * for you:\n *\n * ```ts\n * import { DelegatingSchemaService } from '@warp-drive/legacy/model/migration-support';\n * import { SchemaService } from '@warp-drive/core/reactive';\n *\n * class extends Store {\n * createSchemaService() {\n * const schema = new SchemaService();\n * return new DelegatingSchemaService(this, schema);\n * }\n * }\n * ```\n *\n * When using the DelegateSchemaService, the schema will first\n * be sourced from directly registered schemas, then will fallback\n * to sourcing a schema from available models if no schema is found.\n *\n * @public\n */\n createSchemaService(): SchemaService;\n\n /**\n * DEPRECATED - Use the property `store.schema` instead.\n *\n * Provides access to the SchemaDefinitionService instance\n * for this Store instance.\n *\n * The SchemaDefinitionService can be used to query for\n * information about the schema of a resource.\n *\n * @deprecated\n * @public\n */\n getSchemaDefinitionService(): SchemaService;\n\n /**\n * DEPRECATED - Use `createSchemaService` instead.\n *\n * Allows an app to register a custom SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method can only be called more than once, but only one schema\n * definition service may exist. Therefore if you wish to chain services\n * you must lookup the existing service and close over it with the new\n * service by accessing `store.schema` prior to registration.\n *\n * For Example:\n *\n * ```ts\n * import { Store } from '@warp-drive/core';\n *\n * class SchemaDelegator {\n * constructor(schema) {\n * this._schema = schema;\n * }\n *\n * hasResource(resource: { type: string }): boolean {\n * if (AbstractSchemas.has(resource.type)) {\n * return true;\n * }\n * return this._schema.hasResource(resource);\n * }\n *\n * attributesDefinitionFor(identifier: ResourceKey | { type: string }): AttributesSchema {\n * return this._schema.attributesDefinitionFor(identifier);\n * }\n *\n * relationshipsDefinitionFor(identifier: ResourceKey | { type: string }): RelationshipsSchema {\n * const schema = AbstractSchemas.get(identifier.type);\n * return schema || this._schema.relationshipsDefinitionFor(identifier);\n * }\n * }\n *\n * export default class extends Store {\n * constructor(...args) {\n * super(...args);\n *\n * const schema = this.createSchemaService();\n * this.registerSchemaDefinitionService(new SchemaDelegator(schema));\n * }\n * }\n * ```\n *\n * @deprecated\n * @public\n */\n registerSchemaDefinitionService(schema: SchemaService): void;\n\n /**\n * DEPRECATED - Use `createSchemaService` instead.\n *\n * Allows an app to register a custom SchemaService\n * for use when information about a resource's schema needs\n * to be queried.\n *\n * This method can only be called more than once, but only one schema\n * definition service may exist. Therefore if you wish to chain services\n * you must lookup the existing service and close over it with the new\n * service by accessing `store.schema` prior to registration.\n *\n * For Example:\n *\n * ```ts\n * import { Store } from '@warp-drive/core';\n *\n * class SchemaDelegator {\n * constructor(schema) {\n * this._schema = schema;\n * }\n *\n * hasResource(resource: { type: string }): boolean {\n * if (AbstractSchemas.has(resource.type)) {\n * return true;\n * }\n * return this._schema.hasResource(resource);\n * }\n *\n * attributesDefinitionFor(identifier: ResourceKey | { type: string }): AttributesSchema {\n * return this._schema.attributesDefinitionFor(identifier);\n * }\n *\n * relationshipsDefinitionFor(identifier: ResourceKey | { type: string }): RelationshipsSchema {\n * const schema = AbstractSchemas.get(identifier.type);\n * return schema || this._schema.relationshipsDefinitionFor(identifier);\n * }\n * }\n *\n * export default class extends Store {\n * constructor(...args) {\n * super(...args);\n *\n * const schema = this.schema;\n * this.registerSchema(new SchemaDelegator(schema));\n * }\n * }\n * ```\n *\n * @deprecated\n * @public\n */\n registerSchema(schema: SchemaService): void;\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// DEPRECATED STORE METHODS\n//\n// A second, separate `export interface Store {}` (TypeScript merges\n// same-named interfaces declared within a module) rather than a single\n// merged block with the interface above, so this can be found and removed\n// as its own unit.\n//\n// These signatures used to live in `../deprecated/store.ts` as a cross-file\n// `declare module '../-private/store-service' { interface Store {...} }`\n// augmentation. That stopped working once `Store` began being emitted\n// through an entry-based, rolled-up `.d.ts` build (tsdown/rolldown-plugin-dts):\n// `Store` gets hoisted into a shared, hash-named chunk whenever 2+ entries\n// reference it (which is always), and a cross-file module augmentation can't\n// target an unstable chunk name -- it silently fails to attach for any\n// consumer not importing through the exact one path the augmentation happened\n// to specify, which in practice is every real consumer. Same-module interface\n// merging has no such problem, since it's resolved before any bundling happens.\n//\n// The runtime implementations of these methods still live in\n// `../deprecated/store.ts`, gated behind the `ENABLE_LEGACY_REQUEST_METHODS`\n// deprecation flag. Delete this interface (and the `Store` import it drops\n// from `../deprecated/store.ts`'s `declare module` block) once those methods\n// are fully removed.\n/////////////////////////////////////////////////////////////////////////////\nexport interface Store {\n /**\n This method returns a record for a given identifier or type and id combination.\n\n The `findRecord` method will always resolve its promise with the same\n object for a given identifier or type and `id`.\n\n The `findRecord` method will always return a **promise** that will be\n resolved with the record.\n\n **Example 1**\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model({ post_id }) {\n return this.store.findRecord('post', post_id);\n }\n }\n ```\n\n **Example 2**\n\n `findRecord` can be called with a single identifier argument instead of the combination\n of `type` (modelName) and `id` as separate arguments. You may recognize this combo as\n the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model({ post_id: id }) {\n return this.store.findRecord({ type: 'post', id });\n }\n }\n ```\n\n **Example 3**\n\n If you have previously received an lid via an Identifier for this record, and the record\n has already been assigned an id, you can find the record again using just the lid.\n\n ```js [app/routes/post.js]\n store.findRecord({ lid });\n ```\n\n If the record is not yet available, the store will ask the adapter's `findRecord`\n method to retrieve and supply the necessary data. If the record is already present\n in the store, it depends on the reload behavior _when_ the returned promise\n resolves.\n\n ### Preloading\n\n You can optionally `preload` specific attributes and relationships that you know of\n by passing them via the passed `options`.\n\n For example, if your Ember route looks like `/posts/1/comments/2` and your API route\n for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment\n without also fetching the post you can pass in the post to the `findRecord` call:\n\n ```js [app/routes/post-comments.js]\n export default class PostRoute extends Route {\n model({ post_id, comment_id: id }) {\n return this.store.findRecord({ type: 'comment', id, { preload: { post: post_id }} });\n }\n }\n ```\n\n In your adapter you can then access this id without triggering a network request via the\n snapshot:\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'comment')\n let postId = snapshot.belongsTo('post', { id: true });\n\n return fetch(`./posts/${postId}/comments/${id}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n This could also be achieved by supplying the post id to the adapter via the adapterOptions\n property on the options hash.\n\n ```js [app/routes/post-comments.js]\n export default class PostRoute extends Route {\n model({ post_id, comment_id: id }) {\n return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });\n }\n }\n ```\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'comment')\n let postId = snapshot.adapterOptions.post;\n\n return fetch(`./posts/${postId}/comments/${id}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n If you have access to the post model you can also pass the model itself to preload:\n\n ```javascript\n let post = await store.findRecord('post', '1');\n let comment = await store.findRecord('comment', '2', { post: myPostModel });\n ```\n\n ### Reloading\n\n The reload behavior is configured either via the passed `options` hash or\n the result of the adapter's `shouldReloadRecord`.\n\n If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates\n to `true`, then the returned promise resolves once the adapter returns\n data, regardless if the requested record is already in the store:\n\n ```js\n store.push({\n data: {\n id: 1,\n type: 'post',\n revision: 1\n }\n });\n\n // adapter#findRecord resolves with\n // [\n // {\n // id: 1,\n // type: 'post',\n // revision: 2\n // }\n // ]\n store.findRecord('post', '1', { reload: true }).then(function(post) {\n post.revision; // 2\n });\n ```\n\n If no reload is indicated via the above mentioned ways, then the promise\n immediately resolves with the cached version in the store.\n\n ### Background Reloading\n\n Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,\n then a background reload is started, which updates the records' data, once\n it is available:\n\n ```js\n // app/adapters/post.js\n import ApplicationAdapter from \"./application\";\n\n export default class PostAdapter extends ApplicationAdapter {\n shouldReloadRecord(store, snapshot) {\n return false;\n },\n\n shouldBackgroundReloadRecord(store, snapshot) {\n return true;\n }\n });\n\n // ...\n\n store.push({\n data: {\n id: 1,\n type: 'post',\n revision: 1\n }\n });\n\n let blogPost = store.findRecord('post', '1').then(function(post) {\n post.revision; // 1\n });\n\n // later, once adapter#findRecord resolved with\n // [\n // {\n // id: 1,\n // type: 'post',\n // revision: 2\n // }\n // ]\n\n blogPost.revision; // 2\n ```\n\n If you would like to force or prevent background reloading, you can set a\n boolean value for `backgroundReload` in the options object for\n `findRecord`.\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { backgroundReload: false });\n }\n }\n ```\n\n If you pass an object on the `adapterOptions` property of the options\n argument it will be passed to your adapter via the snapshot\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, {\n adapterOptions: { subscribe: false }\n });\n }\n }\n ```\n\n ```js [app/adapters/post.js]\n import MyCustomAdapter from './custom-adapter';\n\n export default class PostAdapter extends MyCustomAdapter {\n findRecord(store, type, id, snapshot) {\n if (snapshot.adapterOptions.subscribe) {\n // ...\n }\n // ...\n }\n }\n ```\n\n See {@link Store.peekRecord | peekRecord} to get the cached version of a record.\n\n ### Retrieving Related Model Records\n\n If you use an adapter such as the\n [JSONAPIAdapter](/api/@warp-drive/legacy/adapter/json-api/classes/JSONAPIAdapter)\n which supports the [{json:api} specification](http://jsonapi.org/) and if your server\n endpoint supports the use of an\n ['include' query parameter](http://jsonapi.org/format/#fetching-includes),\n you can use `findRecord()` or `findAll()` to automatically retrieve additional records related to\n the one you request by supplying an `include` parameter in the `options` object.\n\n For example, given a `post` model that has a `hasMany` relationship with a `comment`\n model, when we retrieve a specific post we can have the server also return that post's\n comments in the same request:\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { include: ['comments'] });\n }\n }\n ```\n\n ```js [app/adapters/application.js]\n export default class Adapter {\n findRecord(store, schema, id, snapshot) {\n let type = schema.modelName;\n\n if (type === 'post')\n let includes = snapshot.adapterOptions.include;\n\n return fetch(`./posts/${postId}?include=${includes}`)\n .then(response => response.json())\n }\n }\n\n static create() {\n return new this();\n }\n }\n ```\n\n In this case, the post's comments would then be available in your template as\n `model.comments`.\n\n Multiple relationships can be requested using an `include` parameter consisting of a\n list of relationship names, while nested relationships can be specified\n using a dot-separated sequence of relationship names. So to request both the post's\n comments and the authors of those comments the request would look like this:\n\n ```js [app/routes/post.js]\n export default class PostRoute extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });\n }\n }\n ```\n\n ### Retrieving Specific Fields by Type\n\n If your server endpoint supports the use of a ['fields' query parameter](https://jsonapi.org/format/#fetching-sparse-fieldsets),\n you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.\n\n 1. Implement `buildQuery` in your adapter.\n\n ```js [app/adapters/application.js]\n buildQuery(snapshot) {\n let query = super.buildQuery(...arguments);\n\n let { fields } = snapshot.adapterOptions;\n\n if (fields) {\n query.fields = fields;\n }\n\n return query;\n }\n ```\n\n 2. Then pass through the applicable fields to your `findRecord` request.\n\n Given a `post` model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.\n\n ```js [app/routes/post.js]\n export default class extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });\n }\n }\n ```\n\n Moreover, you can filter attributes on related models as well. If a `post` has a `belongsTo` relationship to a user,\n just include the relationship key and attributes.\n\n ```js [app/routes/post.js]\n export default class extends Route {\n model(params) {\n return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });\n }\n }\n ```\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type - either a string representing the name of the resource or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record\n @param id - optional object with options for the request only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved\n @param options - if the first param is a string this will be the optional options for the request. See examples for available options.\n */\n findRecord<T>(type: TypeFromInstance<T>, id: string | number, options?: FindRecordOptions): Promise<T>;\n /** @deprecated */\n findRecord(type: string, id: string | number, options?: FindRecordOptions): Promise<unknown>;\n /** @deprecated */\n findRecord<T>(resource: ResourceIdentifierObject<TypeFromInstance<T>>, options?: FindRecordOptions): Promise<T>;\n /** @deprecated */\n findRecord(resource: ResourceIdentifierObject, options?: FindRecordOptions): Promise<unknown>;\n\n /**\n `findAll` asks the adapter's `findAll` method to find the records for the\n given type, and returns a promise which will resolve with all records of\n this type present in the store, even if the adapter only returns a subset\n of them.\n\n ```js [app/routes/authors.js]\n export default class AuthorsRoute extends Route {\n model(params) {\n return this.store.findAll('author');\n }\n }\n ```\n\n _When_ the returned promise resolves depends on the reload behavior,\n configured via the passed `options` hash and the result of the adapter's\n `shouldReloadAll` method.\n\n ### Reloading\n\n If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to\n `true`, then the returned promise resolves once the adapter returns data,\n regardless if there are already records in the store:\n\n ```js\n store.push({\n data: {\n id: 'first',\n type: 'author'\n }\n });\n\n // adapter#findAll resolves with\n // [\n // {\n // id: 'second',\n // type: 'author'\n // }\n // ]\n store.findAll('author', { reload: true }).then(function(authors) {\n authors.getEach('id'); // ['first', 'second']\n });\n ```\n\n If no reload is indicated via the above mentioned ways, then the promise\n immediately resolves with all the records currently loaded in the store.\n\n ### Background Reloading\n\n Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,\n then a background reload is started. Once this resolves, the array with\n which the promise resolves, is updated automatically so it contains all the\n records in the store:\n\n ```js [app/adapters/application.js]\n import { Adapter } from '@warp-drive/legacy/adapter';\n\n export default class ApplicationAdapter extends Adapter {\n shouldReloadAll(store, snapshotsArray) {\n return false;\n },\n\n shouldBackgroundReloadAll(store, snapshotsArray) {\n return true;\n }\n });\n\n // ...\n\n store.push({\n data: {\n id: 'first',\n type: 'author'\n }\n });\n\n let allAuthors;\n store.findAll('author').then(function(authors) {\n authors.getEach('id'); // ['first']\n\n allAuthors = authors;\n });\n\n // later, once adapter#findAll resolved with\n // [\n // {\n // id: 'second',\n // type: 'author'\n // }\n // ]\n\n allAuthors.getEach('id'); // ['first', 'second']\n ```\n\n If you would like to force or prevent background reloading, you can set a\n boolean value for `backgroundReload` in the options object for\n `findAll`.\n\n ```js [app/routes/post/edit.js]\n export default class PostEditRoute extends Route {\n model() {\n return this.store.findAll('post', { backgroundReload: false });\n }\n }\n ```\n\n If you pass an object on the `adapterOptions` property of the options\n argument it will be passed to you adapter via the `snapshotRecordArray`\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model(params) {\n return this.store.findAll('post', {\n adapterOptions: { subscribe: false }\n });\n }\n }\n ```\n\n ```js [app/adapters/post.js]\n import MyCustomAdapter from './custom-adapter';\n\n export default class UserAdapter extends MyCustomAdapter {\n findAll(store, type, sinceToken, snapshotRecordArray) {\n if (snapshotRecordArray.adapterOptions.subscribe) {\n // ...\n }\n // ...\n }\n }\n ```\n\n See {@link Store.peekAll | peekAll} to get an array of current records in the\n store, without waiting until a reload is finished.\n\n ### Retrieving Related Model Records\n\n If you use an adapter such as the default\n [JSONAPIAdapter](/api/@warp-drive/legacy/adapter/json-api/classes/JSONAPIAdapter)\n that supports the [JSON API specification](http://jsonapi.org/) and if your server\n endpoint supports the use of an\n ['include' query parameter](http://jsonapi.org/format/#fetching-includes),\n you can use `findAll()` to automatically retrieve additional records related to\n those requested by supplying an `include` parameter in the `options` object.\n\n For example, given a `post` model that has a `hasMany` relationship with a `comment`\n model, when we retrieve all of the post records we can have the server also return\n all of the posts' comments in the same request:\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model() {\n return this.store.findAll('post', { include: ['comments'] });\n }\n }\n ```\n Multiple relationships can be requested using an `include` parameter consisting of a\n list or relationship names, while nested relationships can be specified\n using a dot-separated sequence of relationship names. So to request both the posts'\n comments and the authors of those comments the request would look like this:\n\n ```js [app/routes/posts.js]\n export default class PostsRoute extends Route {\n model() {\n return this.store.findAll('post', { include: ['comments','comments.author'] });\n }\n }\n ```\n\n See {@link Store.query | query} to only get a subset of records from the server.\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type the name of the resource\n @param options\n */\n findAll<T>(type: TypeFromInstance<T>, options?: FindAllOptions): Promise<LegacyLiveArray<T>>;\n /** @deprecated */\n findAll(type: string, options?: FindAllOptions): Promise<LegacyLiveArray>;\n\n /**\n This method delegates a query to the adapter. This is the one place where\n adapter-level semantics are exposed to the application.\n\n Each time this method is called a new request is made through the adapter.\n\n Exposing queries this way seems preferable to creating an abstract query\n language for all server-side queries, and then require all adapters to\n implement them.\n\n ---\n\n If you do something like this:\n\n ```js\n store.query('person', { page: 1 });\n ```\n\n The request made to the server will look something like this:\n\n ```http\n GET \"/api/v1/person?page=1\"\n ```\n\n ---\n\n If you do something like this:\n\n ```js\n store.query('person', { ids: ['1', '2', '3'] });\n ```\n\n The request made to the server will look something like this:\n\n ```\n GET \"/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3\"\n decoded: \"/api/v1/person?ids[]=1&ids[]=2&ids[]=3\"\n ```\n\n This method returns a promise, which is resolved with a\n {@link LegacyQueryArray} once the server returns.\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type the name of the resource\n @param query a query to be used by the adapter\n @param options optional, may include `adapterOptions` hash which will be passed to adapter.query\n */\n query<T>(type: TypeFromInstance<T>, query: LegacyResourceQuery, options?: QueryOptions): Promise<LegacyQueryArray<T>>;\n /** @deprecated */\n query(type: string, query: LegacyResourceQuery, options?: QueryOptions): Promise<LegacyQueryArray>;\n\n /**\n This method makes a request for one record, where the `id` is not known\n beforehand (if the `id` is known, use {@link Store.findRecord | findRecord}\n instead).\n\n This method can be used when it is certain that the server will return a\n single object for the primary data.\n\n Each time this method is called a new request is made through the adapter.\n\n Let's assume our API provides an endpoint for the currently logged in user\n\n ```ts\n // GET /api/user/me\n {\n data: {\n type: 'user',\n id: '1234',\n attributes: {\n username: 'admin'\n }\n }\n }\n ```\n\n Since the specific `id` of the `user` is not known beforehand, we can use\n `queryRecord` to get the user:\n\n ```ts\n const user = await store.queryRecord('user', { me: true });\n user.username; // admin\n ```\n\n The request is made through the adapters' `queryRecord`:\n\n ```ts [app/adapters/user.ts]\n import Adapter from '@warp-drive/legacy/adapter';\n\n export default class UserAdapter extends Adapter {\n async queryRecord(modelName, query) {\n if (query.me) {\n const response = await fetch('/api/me');\n return await response.json();\n }\n throw new Error('Unsupported query');\n }\n }\n ```\n\n Note: the primary use case for `store.queryRecord` is when a single record\n is queried and the `id` is not known beforehand. In all other cases\n `store.query` and using the first item of the array is likely the preferred\n way:\n\n ```\n // GET /users?username=unique\n {\n data: [{\n id: 1234,\n type: 'user',\n attributes: {\n username: \"unique\"\n }\n }]\n }\n ```\n\n ```js\n store.query('user', { username: 'unique' }).then(function(users) {\n return users.firstObject;\n }).then(function(user) {\n let id = user.id;\n });\n ```\n\n This method returns a promise, which resolves with the found record.\n\n If the adapter returns no data for the primary data of the payload, then\n `queryRecord` resolves with `null`:\n\n ```\n // GET /users?username=unique\n {\n data: null\n }\n ```\n\n ```js\n store.queryRecord('user', { username: 'unique' }).then(function(user) {\n // user is null\n });\n ```\n\n @public\n @deprecated use {@link Store.request} instead\n @until 6.0\n @since 1.13.0\n @param type\n @param query an opaque query to be used by the adapter\n @param options optional, may include `adapterOptions` hash which will be passed to adapter.queryRecord\n @return promise which resolves with the found record or `null`\n */\n queryRecord<T>(type: TypeFromInstance<T>, query: LegacyResourceQuery, options?: QueryOptions): Promise<T | null>;\n /** @deprecated */\n queryRecord(type: string, query: LegacyResourceQuery, options?: QueryOptions): Promise<unknown | null>;\n\n /**\n Get the reference for the specified record.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', '1');\n\n // check if the user is loaded\n let isLoaded = userRef.value() !== null;\n\n // get the record of the reference (null if not yet available)\n let user = userRef.value();\n\n // get the identifier of the reference\n if (userRef.remoteType() === 'id') {\n let id = userRef.id();\n }\n\n // load user (via store.find)\n userRef.load().then(...)\n\n // or trigger a reload\n userRef.reload().then(...)\n\n // provide data for reference\n userRef.push({ id: 1, username: '@user' }).then(function(user) {\n userRef.value() === user;\n });\n ```\n\n @public\n @deprecated use {@link Store.request} for loading and {@link Store.cache} for direct data insertion instead\n @until 6.0\n @since 2.5.0\n @param resource - modelName (string) or Identifier (object)\n @param id\n */\n getReference(resource: string | ResourceIdentifierObject, id: string | number): RecordReference;\n\n /**\n Returns the schema for a particular resource type (modelName).\n\n When used with [Model](/api/@warp-drive/legacy/model/classes/Model) the return is the model class,\n but this is not guaranteed.\n\n If looking to query attribute or relationship information it is\n recommended to use `getSchemaDefinitionService` instead. This method\n should be considered legacy and exists primarily to continue to support\n Adapter/Serializer APIs which expect it's return value in their method\n signatures.\n\n The class of a model might be useful if you want to get a list of all the\n relationship names of the model.\n\n @public\n @deprecated use {@link Store.schema} instead\n @until 6.0\n @param type\n */\n modelFor<T>(type: TypeFromInstance<T>): ModelSchema<T>;\n /** @deprecated */\n modelFor(type: string): ModelSchema;\n\n /**\n * Trigger a save for a Record.\n *\n * Returns a promise resolving with the same record when the save is complete.\n *\n * @deprecated use {@link Store.request} instead\n * @until 6.0\n * @public\n * @param record\n * @param options\n */\n saveRecord<T>(record: T, options?: Record<string, unknown>): Promise<T>;\n}\n\n/**\n * ```ts\n * import { Store } from '@warp-drive/core';\n * ```\n *\n * The `Store` is the central piece of the ***Warp*Drive** experience. It connects\n * requests for data with schemas, caching and reactivity.\n *\n * While it's easy to use ***just*** ***Warp*Drive**'s request management, most projects will find they\n * require far more than basic fetch management. For this reason it's often best to start with a `Store`\n * even when you aren't sure yet.\n *\n * Most projects will only have a single `Store`, though using multiple distinct stores\n * is possible.\n *\n * @public\n * @hideconstructor\n */\nexport class Store extends BaseClass {\n /** @internal */\n declare readonly recordArrayManager: RecordArrayManager;\n\n /**\n * Provides access to the {@link NotificationManager} associated\n * with this Store instance.\n *\n * The NotificationManager can be used to subscribe to\n * changes to the cache.\n *\n * @public\n */\n declare readonly notifications: NotificationManager;\n\n /**\n * Provides access to the SchemaService instance\n * for this Store instance.\n *\n * The SchemaService can be used to query for\n * information about the schema of a resource.\n *\n * @public\n */\n get schema(): ReturnType<this['createSchemaService']> {\n if (!this._schema) {\n this._schema = this.createSchemaService();\n }\n return this._schema as ReturnType<this['createSchemaService']>;\n }\n /** @internal */\n declare _schema: SchemaService;\n\n /**\n * Provides access to the CacheKeyManager\n * for this store.\n *\n * The CacheKeyManager can be used to generate or\n * retrieve a stable unique CacheKey for any resource\n * or request.\n *\n * @public\n */\n declare readonly cacheKeyManager: CacheKeyManager;\n /**\n * Provides access to the {@link RequestManager} instance associated\n * with this Store instance.\n *\n * See also:\n * - {@link Fetch}\n * - {@link CacheHandlerInterface | CacheHandler (Interface)}\n * - {@link CacheHandler | CacheHandler (Class)}\n *\n * ```ts\n * import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core';\n *\n * class AppStore extends Store {\n * requestManager = new RequestManager()\n * .use([Fetch])\n * .useCache(CacheHandler);\n * }\n * ```\n *\n * @public\n */\n declare requestManager: RequestManager;\n\n /**\n * A Property which an App may set to provide a CachePolicy\n * to control when a cached request becomes stale.\n *\n * Note, when defined, these methods will only be invoked if a\n * cache key exists for the request, either because the request\n * contains `cacheOptions.key` or because the {@link CacheKeyManager}\n * was able to generate a key for the request using the configured\n * {@link setIdentifierGenerationMethod | generation method}.\n *\n * `isSoftExpired` will only be invoked if `isHardExpired` returns `false`.\n *\n * ```ts\n * store.lifetimes = {\n * // make the request and ignore the current cache state\n * isHardExpired(key: RequestKey): boolean {\n * return false;\n * }\n *\n * // make the request in the background if true, return cache state\n * isSoftExpired(key: RequestKey): boolean {\n * return false;\n * }\n * }\n * ```\n *\n * @public\n */\n declare lifetimes?: CachePolicy;\n\n // Private\n /** @internal */\n declare _graph?: Graph;\n /** @internal */\n declare _requestCache: RequestStateService;\n /** @internal */\n declare _instanceCache: InstanceCache;\n /** @internal */\n declare _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;\n /** @internal */\n declare _forceShim: boolean;\n /**\n * Async flush buffers notifications until flushed\n * by finalization of a future configured by store.request\n *\n * This is useful for ensuring that notifications are delivered\n * prior to the promise resolving but without risk of promise\n * interleaving.\n *\n * @internal\n */\n declare _enableAsyncFlush: boolean | null;\n\n /**\n * Available in DEBUG Only\n * @internal\n */\n declare DISABLE_WAITER?: boolean;\n /** @internal */\n declare _isDestroying: boolean;\n /** @internal */\n declare _isDestroyed: boolean;\n\n /** @private */\n get isDestroying(): boolean {\n return this._isDestroying;\n }\n /** @internal */\n set isDestroying(value: boolean) {\n this._isDestroying = value;\n }\n /** @private */\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n /** @internal */\n set isDestroyed(value: boolean) {\n this._isDestroyed = value;\n }\n\n /** @deprecated use {@link Store.cacheKeyManager} */\n get identifierCache(): CacheKeyManager {\n return this.cacheKeyManager;\n }\n\n /**\n @private\n */\n constructor(createArgs?: unknown) {\n super(createArgs);\n Object.assign(this, createArgs);\n\n this.cacheKeyManager = new CacheKeyManager();\n\n this.notifications = new NotificationManager(this);\n\n // private but maybe useful to be here, somewhat intimate\n this.recordArrayManager = new RecordArrayManager({ store: this });\n\n // private\n this._requestCache = new RequestStateService(this);\n this._instanceCache = new InstanceCache(this);\n\n this.isDestroying = false;\n this.isDestroyed = false;\n }\n\n /** @internal */\n _run(cb: () => void): void {\n assert(`WarpDrive should never encounter a nested run`, !this._cbs);\n const _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } = (this._cbs = {});\n if (DEBUG) {\n try {\n cb();\n if (_cbs.coalesce) {\n _cbs.coalesce();\n }\n if (_cbs.sync) {\n _cbs.sync();\n }\n if (_cbs.notify) {\n _cbs.notify();\n }\n } finally {\n this._cbs = null;\n }\n } else {\n cb();\n if (_cbs.coalesce) {\n _cbs.coalesce();\n }\n if (_cbs.sync) {\n _cbs.sync();\n }\n if (_cbs.notify) {\n _cbs.notify();\n }\n this._cbs = null;\n }\n }\n\n /**\n * Executes the callback, ensurng that any work that calls\n * store._schedule is executed after in the right order.\n *\n * When queues already exist, scheduled callbacks will\n * join the existing queue.\n *\n * @internal\n */\n _join(cb: () => void): void {\n if (this._cbs) {\n cb();\n } else {\n this._run(cb);\n }\n }\n\n /** @internal */\n _schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void {\n assert(`WarpDrive expects to schedule only when there is an active run`, !!this._cbs);\n assert(`WarpDrive expects only one flush per queue name, cannot schedule ${name}`, !this._cbs[name]);\n\n this._cbs[name] = cb;\n }\n\n /**\n * Retrieve the RequestStateService instance\n * associated with this Store.\n *\n * This can be used to query the status of requests\n * that have been initiated for a given identifier.\n *\n * @return {RequestStateService}\n * @public\n */\n getRequestStateService(): RequestStateService {\n return this._requestCache;\n }\n\n /** @internal */\n _getAllPending(): (Promise<unknown[]> & { length: number }) | void {\n if (TESTING) {\n const all: Promise<unknown>[] = [];\n const pending = this._requestCache._pending;\n\n pending.forEach((requests) => {\n all.push(...requests.map((v) => v[RequestPromise]!));\n });\n this.requestManager._pending.forEach((v) => all.push(v));\n const promise: Promise<unknown[]> & { length: number } = Promise.allSettled(all) as Promise<unknown[]> & {\n length: number;\n };\n promise.length = all.length;\n return promise;\n }\n }\n\n /**\n * ::: tip 💡 For a more complete overview see the [Request Guide](/guides/2-requests/1-overview)\n * :::\n *\n * Issue a request via the configured {@link RequestManager},\n * inserting the response into the {@link Store.cache | cache} and handing\n * back a {@link Future} which resolves to a {@link ReactiveDocument | ReactiveDocument}\n *\n * #### Request Cache Keys\n *\n * Only {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/GET | GET} requests with a url or requests with an explicit\n * {@link CacheOptions.key | cache key} will have the request result\n * and document cached.\n *\n * The cache key used is {@link RequestInfo.cacheOptions.key | RequestInfo.cacheOptions.key}\n * if present, falling back to {@link RequestInfo.url}.\n *\n * Params are not serialized as part of the cache-key, so\n * either ensure they are already in the url or utilize\n * `requestConfig.cacheOptions.key`. For queries issued\n * via the {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/POST | POST} method `requestConfig.cacheOptions.key`\n * MUST be supplied for the document to be cached.\n *\n * #### Requesting Without a Cache Key\n *\n * Resource data within the request is always updated in the cache,\n * regardless of whether a cache key is present for the request.\n *\n * #### Fulfilling From Cache\n *\n * When a cache-key is determined, the request may fulfill\n * from cache provided the cache is not stale.\n *\n * Cache staleness is determined by the configured {@link CachePolicy}\n * with priority given to the {@link CacheOptions.reload} and\n * {@link CacheOptions.backgroundReload} on the request if present.\n *\n * If the cache data has soft expired or the request asks for a background\n * reload, the request will fulfill from cache if possible and\n * make a non-blocking request in the background to update the cache.\n *\n * If the cache data has hard expired or the request asks for a reload,\n * the request will not fulfill from cache and will make a blocking\n * request to update the cache.\n *\n * #### The Response\n *\n * The primary difference between {@link RequestManager.request} and `store.request`\n * is that `store.request` will convert the response into a {@link ReactiveDocument}\n * containing {@link Store.instantiateRecord | ReactiveResources}.\n *\n * @public\n */\n request<RT>(requestConfig: StoreRequestInput<RT>): Future<RT> {\n // we lazily set the cache handler when we issue the first request\n // because constructor doesn't allow for this to run after\n // the user has had the chance to set the prop.\n const opts: {\n store: Store;\n disableTestWaiter?: boolean;\n [EnableHydration]: boolean;\n records?: ResourceKey[];\n } = {\n store: this,\n [EnableHydration]: requestConfig[EnableHydration] ?? true,\n };\n\n if (requestConfig.records) {\n const cacheKeyManager = this.cacheKeyManager;\n opts.records = requestConfig.records.map((r) => cacheKeyManager.getOrCreateRecordIdentifier(r));\n }\n\n if (TESTING) {\n if (this.DISABLE_WAITER) {\n opts.disableTestWaiter =\n typeof requestConfig.disableTestWaiter === 'boolean' ? requestConfig.disableTestWaiter : true;\n }\n }\n\n if (LOG_REQUESTS) {\n let options: unknown;\n try {\n options = JSON.parse(JSON.stringify(requestConfig));\n } catch {\n options = requestConfig;\n }\n // oxlint-disable-next-line no-console\n console.log(\n `request: [[START]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${\n requestConfig.op || '<unknown operation>'\n } ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`,\n options\n );\n }\n\n const request = Object.assign({}, requestConfig, opts);\n const future = this.requestManager.request(request);\n\n future.onFinalize(() => {\n if (LOG_REQUESTS) {\n // oxlint-disable-next-line no-console\n console.log(\n `request: [[FINALIZE]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${\n requestConfig.op || '<unknown operation>'\n } ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`\n );\n }\n // skip flush for legacy belongsTo\n if (requestConfig.op === 'findBelongsTo' && !requestConfig.url) {\n return;\n }\n this.notifications._flush();\n });\n\n return future;\n }\n\n /**\n Creates a new record in the current store.\n\n > [!CAUTION]\n > This should not be used to mock records or to create\n > a record representing data that could be fetched from\n > the API.\n\n The properties passed to this method are set on\n the newly created record.\n\n For instance: to create a new `post`:\n\n ```js\n store.createRecord('post', {\n title: 'WarpDrive is Stellar!'\n });\n ```\n\n Relationships can be set during create. For instance,\n to create a new `post` that has an existing user as\n it's author:\n\n ```js\n const user = store.peekRecord('user', '1');\n\n store.createRecord('post', {\n title: 'WarpDrive is Stellar!',\n user: user\n });\n ```\n\n ### lid handling\n\n All new records are assigned an `lid` that can be used to handle\n transactional saves of multiple records, or to link the data to\n other data in scenarios involving eventual-consistency or remote\n syncing.\n\n ```ts\n const post = store.createRecord('post', {\n title: 'WarpDrive is Stellar!'\n });\n const { lid } = recordIdentifierFor(post);\n ```\n\n The `lid` defaults to a uuidv4 string.\n\n In order to support receiving knowledge about unpersisted creates\n from other sources (say a different tab in the same web-browser),\n createRecord allows for the `lid` to be provided as part of an\n optional third argument. **If this lid already exists in the store\n an error will be thrown.**\n\n ```ts\n const post = store.createRecord(\n 'post',\n { title: 'WarpDrive is Stellar!' },\n { lid: '4d47bb88-931f-496e-986d-c4888cef7373' }\n );\n ```\n\n @public\n @param type the name of the resource\n @param inputProperties a hash of properties to set on the\n newly created record.\n @return a record in the \"isNew\" state\n */\n createRecord<T>(type: TypeFromInstance<T>, inputProperties: CreateRecordProperties<T>, context?: CreateContext): T;\n createRecord(type: string, inputProperties: CreateRecordProperties, context?: CreateContext): OpaqueRecordInstance;\n createRecord(type: string, inputProperties: CreateRecordProperties, context?: CreateContext): OpaqueRecordInstance {\n if (DEBUG) {\n assertDestroyingStore(this, 'createRecord');\n }\n assert(`You need to pass a model name to the store's createRecord method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n // This is wrapped in a `run.join` so that in test environments users do not need to manually wrap\n // calls to `createRecord`. The run loop usage here is because we batch the joining and updating\n // of record-arrays via ember's run loop, not our own.\n //\n // to remove this, we would need to move to a new `async` API.\n let record!: OpaqueRecordInstance;\n this._join(() => {\n const normalizedModelName = normalizeModelName(type);\n const properties = { ...inputProperties };\n\n // If the passed properties do not include a primary key,\n // give the adapter an opportunity to generate one. Typically,\n // client-side ID generators will use something like uuid.js\n // to avoid conflicts.\n let id: string | null;\n\n if (properties.id === null || properties.id === undefined) {\n upgradeStore(this);\n const adapter = this.adapterFor?.(normalizedModelName, true);\n\n if (adapter && adapter.generateIdForRecord) {\n id = properties.id = coerceId(adapter.generateIdForRecord(this, normalizedModelName, properties));\n } else {\n id = properties.id = null;\n }\n } else {\n id = properties.id = coerceId(properties.id);\n }\n\n const resource: { type: string; id: string | null; lid?: string } = { type: normalizedModelName, id };\n\n if (resource.id) {\n const identifier = this.cacheKeyManager.peekResourceKey(resource as ResourceIdentifierObject);\n\n assert(\n `The id ${String(properties.id)} has already been used with another '${normalizedModelName}' record.`,\n !identifier\n );\n }\n\n if (context?.lid) {\n const identifier = this.cacheKeyManager.peekResourceKey({ lid: context?.lid });\n resource.lid = context.lid;\n assert(`The lid ${context.lid} has already been used with another '${identifier?.type}' record.`, !identifier);\n }\n\n const identifier = this.cacheKeyManager.createIdentifierForNewRecord(resource);\n const cache = this.cache;\n\n const createOptions = normalizeProperties(this, identifier, properties);\n const resultProps = cache.clientDidCreate(identifier, createOptions);\n\n record = getNewRecord(this._instanceCache, identifier, resultProps);\n });\n return record;\n }\n\n /**\n For symmetry, a record can be deleted via the store.\n\n Example\n\n ```javascript\n let post = store.createRecord('post', {\n title: 'Ember is awesome!'\n });\n\n store.deleteRecord(post);\n ```\n\n @public\n @param {unknown} record\n */\n deleteRecord<T>(record: T): void {\n if (DEBUG) {\n assertDestroyingStore(this, 'deleteRecord');\n }\n\n const identifier = peekResourceKey(record);\n const cache = this.cache;\n assert(`expected the record to be connected to a cache`, identifier);\n this._join(() => {\n cache.setIsDeleted(identifier, true);\n\n if (cache.isNew(identifier)) {\n this._instanceCache.unloadRecord(identifier);\n }\n });\n }\n\n /**\n For symmetry, a record can be unloaded via the store.\n This will cause the record to be destroyed and freed up for garbage collection.\n\n Example\n\n ```javascript\n const { content: { data: post } } = await store.request(findRecord({ type: 'post', id: '1' }));\n store.unloadRecord(post);\n ```\n\n @public\n @param {Model} record\n */\n unloadRecord<T>(record: T): void {\n if (DEBUG) {\n assertDestroyingStore(this, 'unloadRecord');\n }\n const identifier = peekResourceKey(record);\n if (identifier) {\n this._instanceCache.unloadRecord(identifier);\n }\n }\n\n /**\n Get a record by a given type and ID without triggering a fetch.\n\n This method will synchronously return the record if it is available in the store,\n otherwise it will return `null`. A record is available if it has been fetched earlier, or\n pushed manually into the store.\n\n **Example 1**\n\n ```ts\n const post = store.peekRecord('post', '1');\n\n post.id; // '1'\n ```\n\n `peekRecord` can be called with a single identifier argument instead of the combination\n of `type` (modelName) and `id` as separate arguments. You may recognize this combo as\n the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)\n\n **Example 2**\n\n ```ts\n const post = store.peekRecord({ type: 'post', id: '1' });\n post.id; // '1'\n ```\n\n If you have previously received an lid from an Identifier for this record, you can lookup the record again using\n just the lid.\n\n **Example 3**\n\n ```js\n let post = store.peekRecord({ lid });\n post.id; // '1'\n ```\n\n @since 1.13.0\n @public\n @param type - either a string representing the modelName or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record\n @param id - optional only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved.\n */\n peekRecord<T>(type: TypeFromInstance<T>, id: string | number): T | null;\n peekRecord(type: string, id: string | number): unknown | null;\n peekRecord<T>(identifier: ResourceIdentifierObject<TypeFromInstance<T>>): T | null;\n peekRecord(identifier: ResourceIdentifierObject): unknown | null;\n peekRecord<T = OpaqueRecordInstance>(identifier: ResourceIdentifierObject | string, id?: string | number): T | null {\n if (arguments.length === 1 && isMaybeIdentifier(identifier)) {\n const stableIdentifier = this.cacheKeyManager.peekResourceKey(identifier);\n const isLoaded = stableIdentifier && this._instanceCache.recordIsLoaded(stableIdentifier);\n // TODO come up with a better mechanism for determining if we have data and could peek.\n // this is basically an \"are we not empty\" query.\n return isLoaded ? (this._instanceCache.getRecord(stableIdentifier) as T) : null;\n }\n\n if (DEBUG) {\n assertDestroyingStore(this, 'peekRecord');\n }\n\n assert(`You need to pass a model name to the store's peekRecord method`, identifier);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${String(\n identifier\n )}`,\n typeof identifier === 'string'\n );\n\n const type = normalizeModelName(identifier);\n const normalizedId = ensureStringId(id);\n const resource = { type, id: normalizedId };\n const stableIdentifier = this.cacheKeyManager.peekResourceKey(resource);\n const isLoaded = stableIdentifier && this._instanceCache.recordIsLoaded(stableIdentifier);\n\n return isLoaded ? (this._instanceCache.getRecord(stableIdentifier) as T) : null;\n }\n\n /**\n This method returns the {@link LegacyLiveArray} that contains all of the\n known records for a given type in the store. Each ResourceType has only\n one LiveArray instance, so multiple calls to `peekAll` with the same type\n will always return the same instance.\n\n Note that because it's a LiveArray, the result will contain any\n locally created records of the type, however, it will not make a\n request to the backend to retrieve additional records.\n\n Example\n\n ```ts\n const allPosts = store.peekAll('post');\n ```\n\n @since 1.13.0\n @public\n @param type the name of the resource\n */\n peekAll<T>(type: TypeFromInstance<T>): LegacyLiveArray<T>;\n peekAll(type: string): LegacyLiveArray;\n peekAll(type: string): LegacyLiveArray {\n if (DEBUG) {\n assertDestroyingStore(this, 'peekAll');\n }\n assert(`You need to pass a model name to the store's peekAll method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n return this.recordArrayManager.liveArrayFor(normalizeModelName(type));\n }\n\n /**\n This method unloads all records in the store.\n It schedules unloading to happen during the next run loop.\n\n Optionally you can pass a type which unload all records for a given type.\n\n ```javascript\n store.unloadAll();\n store.unloadAll('post');\n ```\n\n @param {String} type the name of the resource\n @public\n */\n unloadAll<T>(type: TypeFromInstance<T>): void;\n unloadAll(type?: string): void;\n unloadAll(type?: string) {\n if (DEBUG) {\n assertDestroyedStoreOnly(this, 'unloadAll');\n }\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${String(type)}`,\n !type || typeof type === 'string'\n );\n assertPrivateStore(this);\n\n this._join(() => {\n this._enableAsyncFlush = true;\n if (type === undefined) {\n this.recordArrayManager.pause();\n // destroy the graph before unloadAll\n // since then we avoid churning relationships\n // during unload\n this._graph?.identifiers.clear();\n\n this.recordArrayManager.clear();\n this._instanceCache.clear();\n } else {\n this._instanceCache.clear(normalizeModelName(type));\n }\n this._enableAsyncFlush = null;\n this.notifications._flush();\n if (type === undefined) {\n this.recordArrayManager.resume();\n }\n });\n }\n\n /**\n Push some data for a given type into the store.\n\n This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments:\n - record's `type` should always be in singular, dasherized form\n - members (properties) should be camelCased\n\n [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level):\n\n ```js\n store.push({\n data: {\n // primary data for single record of type `Person`\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Daniel',\n lastName: 'Kmak'\n }\n }\n });\n ```\n\n [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7)\n\n `data` property can also hold an array (of records):\n\n ```js\n store.push({\n data: [\n // an array of records\n {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Daniel',\n lastName: 'Kmak'\n }\n },\n {\n id: '2',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n }\n }\n ]\n });\n ```\n\n [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355)\n\n There are some typical properties for `JSONAPI` payload:\n * `id` - mandatory, unique record's key\n * `type` - mandatory string which matches `model`'s dasherized name in singular form\n * `attributes` - object which holds data for record attributes - `attr`'s declared in model\n * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`):\n - [`links`](http://jsonapi.org/format/#document-links)\n - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data\n - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship\n\n For this model:\n\n ```js [app/models/person.js]\n import Model, { attr, hasMany } from '@warp-drive/legacy/model';\n\n export default class PersonRoute extends Route {\n @attr('string') firstName;\n @attr('string') lastName;\n\n @hasMany('person') children;\n }\n ```\n\n To represent the children as IDs:\n\n ```js\n {\n data: {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n },\n relationships: {\n children: {\n data: [\n {\n id: '2',\n type: 'person'\n },\n {\n id: '3',\n type: 'person'\n },\n {\n id: '4',\n type: 'person'\n }\n ]\n }\n }\n }\n }\n ```\n\n [Demo.](http://ember-twiddle.com/343e1735e034091f5bde)\n\n To represent the children relationship as a URL:\n\n ```js\n {\n data: {\n id: '1',\n type: 'person',\n attributes: {\n firstName: 'Tom',\n lastName: 'Dale'\n },\n relationships: {\n children: {\n links: {\n related: '/people/1/children'\n }\n }\n }\n }\n }\n ```\n\n If you're streaming data, or implementing response handling, make sure\n that you have converted the incoming data into this form.\n\n This method can be used both to push in brand new\n records, as well as to update existing records.\n\n See also {@link Cache.patch}\n\n @public\n @param data\n @return the primary record(s) that created or updated.\n */\n push(data: EmptyResourceDocument): null;\n push<T>(data: SingleResourceDocument<TypeFromInstance<T>>): T;\n push(data: SingleResourceDocument): OpaqueRecordInstance;\n push<T>(data: CollectionResourceDocument<TypeFromInstance<T>>): T[];\n push(data: CollectionResourceDocument): OpaqueRecordInstance[];\n push(data: JsonApiDocument): OpaqueRecordInstance | OpaqueRecordInstance[] | null {\n if (DEBUG) {\n assertDestroyingStore(this, 'push');\n }\n const pushed = this._push(data, false);\n\n if (Array.isArray(pushed)) {\n return pushed.map((identifier) => this._instanceCache.getRecord(identifier));\n }\n\n if (pushed === null) {\n return null;\n }\n\n return this._instanceCache.getRecord(pushed);\n }\n\n /**\n Push some data in the form of a json-api document into the store,\n without creating materialized records.\n\n @private\n @return identifiers for the primary records that had data loaded\n */\n _push(jsonApiDoc: JsonApiDocument, asyncFlush?: boolean): PersistedResourceKey | PersistedResourceKey[] | null {\n if (DEBUG) {\n assertDestroyingStore(this, '_push');\n }\n if (asyncFlush) {\n this._enableAsyncFlush = true;\n }\n\n let ret!: ResourceDocument;\n this._join(() => {\n ret = this.cache.put({ content: jsonApiDoc });\n });\n\n this._enableAsyncFlush = null;\n\n return 'data' in ret ? ret.data : null;\n }\n\n /**\n * Returns the cache instance associated to this Store, instantiates the Cache\n * if necessary via `Store.createCache`\n *\n * @public\n */\n get cache(): ReturnType<this['createCache']> {\n let { cache } = this._instanceCache;\n if (!cache) {\n cache = this._instanceCache.cache = this.createCache(this._instanceCache._storeWrapper);\n if (DEBUG) {\n cache = this._instanceCache.cache = new CacheManager(cache);\n }\n }\n\n return cache as ReturnType<this['createCache']>;\n }\n\n /** @private */\n destroy(): void {\n if (this.isDestroyed) {\n // @ember/test-helpers will call destroy multiple times\n return;\n }\n this.isDestroying = true;\n\n this._graph?.destroy();\n this._graph = undefined;\n\n this.notifications.destroy();\n this.recordArrayManager.destroy();\n this.cacheKeyManager.destroy();\n this._instanceCache.clear();\n this.isDestroyed = true;\n }\n\n /**\n * This method\n *\n * @private\n */\n static create(args?: Record<string, unknown>): Store {\n return new this(args);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateStore extends Store {\n readonly recordArrayManager: PrivateRecordArrayManager;\n notifications: PrivateNotificationManager;\n requestManager: PrivateRequestManager;\n cacheKeyManager: PrivateCacheKeyManager;\n _schema: SchemaService;\n _graph?: Graph;\n _requestCache: PrivateRequestStateService;\n getRequestStateService(): PrivateRequestStateService;\n _instanceCache: InstanceCache;\n _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;\n _forceShim: boolean;\n /**\n * Async flush buffers notifications until flushed\n * by finalization of a future configured by store.request\n *\n * This is useful for ensuring that notifications are delivered\n * prior to the promise resolving but without risk of promise\n * interleaving.\n */\n _enableAsyncFlush: boolean | null;\n\n /**\n * Available in DEBUG Only\n */\n DISABLE_WAITER?: boolean;\n _isDestroying: boolean;\n _isDestroyed: boolean;\n isDestroying: boolean;\n isDestroyed: boolean;\n _run(cb: () => void): void;\n /**\n * Executes the callback, ensurng that any work that calls\n * store._schedule is executed after in the right order.\n *\n * When queues already exist, scheduled callbacks will\n * join the existing queue.\n *\n */\n _join(cb: () => void): void;\n _schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void;\n _getAllPending(): (Promise<unknown[]> & { length: number }) | void;\n}\n\n/**\n * Upgrade the type for Store to PrivateStore, which will also\n * upgrade any associated types to their private equivalents.\n *\n * @private\n */\nexport function assertPrivateStore(store: unknown): asserts store is PrivateStore {}\n/**\n * Upgrade the type for Store to PrivateStore, which will also\n * upgrade any associated types to their private equivalents.\n *\n * @private\n */\nexport function isPrivateStore(store: unknown): PrivateStore {\n return store as PrivateStore;\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n Store.prototype.getSchemaDefinitionService = function (): SchemaService {\n assert(`You must registerSchemaDefinitionService with the store to use custom model classes`, this._schema);\n deprecate(`Use \\`store.schema\\` instead of \\`store.getSchemaDefinitionService()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n return this._schema;\n };\n Store.prototype.registerSchemaDefinitionService = function (schema: SchemaService) {\n deprecate(`Use \\`store.createSchemaService\\` instead of \\`store.registerSchemaDefinitionService()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n this._schema = schema;\n };\n Store.prototype.registerSchema = function (schema: SchemaService) {\n deprecate(`Use \\`store.createSchemaService\\` instead of \\`store.registerSchema()\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n this._schema = schema;\n };\n}\n\nlet assertDestroyingStore: (store: Store, method: string) => void;\nlet assertDestroyedStoreOnly: (store: Store, method: string) => void;\n\nif (DEBUG) {\n // oxlint-disable-next-line no-shadow\n assertDestroyingStore = function assertDestroyingStore(store: Store, method: string) {\n assert(\n `Attempted to call store.${method}(), but the store instance has already been destroyed.`,\n !(store.isDestroying || store.isDestroyed)\n );\n };\n // oxlint-disable-next-line no-shadow\n assertDestroyedStoreOnly = function assertDestroyedStoreOnly(store: Store, method: string) {\n assert(\n `Attempted to call store.${method}(), but the store instance has already been destroyed.`,\n !store.isDestroyed\n );\n };\n}\n\nexport function isMaybeIdentifier(\n maybeIdentifier: string | ResourceIdentifierObject\n): maybeIdentifier is ResourceIdentifierObject {\n return Boolean(\n maybeIdentifier !== null &&\n typeof maybeIdentifier === 'object' &&\n (('id' in maybeIdentifier && 'type' in maybeIdentifier && maybeIdentifier.id && maybeIdentifier.type) ||\n maybeIdentifier.lid)\n );\n}\n\nfunction normalizeProperties(\n store: Store,\n identifier: ResourceKey,\n properties?: { [key: string]: unknown }\n): { [key: string]: unknown } | undefined {\n // assert here\n if (properties !== undefined) {\n if ('id' in properties) {\n assert(`expected id to be a string or null`, properties.id !== undefined);\n }\n assert(\n `You passed '${typeof properties}' as properties for record creation instead of an object.`,\n typeof properties === 'object' && properties !== null\n );\n\n const { type } = identifier;\n\n // convert relationship Records to RecordDatas before passing to RecordData\n const defs = store.schema.fields({ type });\n\n if (defs.size) {\n const keys = Object.keys(properties);\n\n for (let i = 0; i < keys.length; i++) {\n const prop = keys[i];\n const field = defs.get(prop);\n\n if (!field) continue;\n\n if (field.kind === 'hasMany') {\n if (DEBUG) {\n assertRecordsPassedToHasMany(properties[prop] as OpaqueRecordInstance[]);\n }\n properties[prop] = extractIdentifiersFromRecords(properties[prop] as OpaqueRecordInstance[]);\n } else if (field.kind === 'belongsTo') {\n properties[prop] = extractIdentifierFromRecord(properties[prop]);\n }\n }\n }\n }\n return properties;\n}\n\nfunction assertRecordsPassedToHasMany(records: OpaqueRecordInstance[]) {\n assert(`You must pass an array of records to set a hasMany relationship`, Array.isArray(records));\n assert(\n `All elements of a hasMany relationship must be instances of Model, you passed ${records\n .map((r) => `${typeof r}`)\n .join(', ')}`,\n (function () {\n return records.every((record) => {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n });\n })()\n );\n}\n\nfunction extractIdentifiersFromRecords(records: OpaqueRecordInstance[]): ResourceKey[] {\n return records.map((record) => extractIdentifierFromRecord(record)) as ResourceKey[];\n}\n\ntype PromiseProxyRecord = { then(): void; content: OpaqueRecordInstance | null | undefined };\n\nfunction extractIdentifierFromRecord(recordOrPromiseRecord: PromiseProxyRecord | OpaqueRecordInstance | null) {\n if (!recordOrPromiseRecord) {\n return null;\n }\n const extract = recordIdentifierFor;\n\n return extract(recordOrPromiseRecord);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ensureStringId, type InstanceCache, recordIdentifierFor } from '../-private';\nimport type { NotificationType } from '../-private/managers/notification-manager.ts';\nimport { defineSignal } from '../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport type { Cache } from '../../types/cache.ts';\nimport type { NewResourceKey, ResourceKey } from '../../types/identifier.ts';\nimport type { Value } from '../../types/json/raw';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../types/record.ts';\nimport type {\n LegacyAttributeField,\n LegacyRelationshipField,\n LegacyRelationshipField as RelationshipSchema,\n} from '../../types/schema/fields.ts';\nimport type {\n ExistingResourceIdentifierObject,\n ExistingResourceObject,\n InnerRelationshipDocument,\n SingleResourceDocument,\n} from '../../types/spec/json-api-raw';\nimport type { Store } from './store.ts';\n\n/*\n When a find request is triggered on the store, the user can optionally pass in\n attributes and relationships to be preloaded. These are meant to behave as if they\n came back from the server, except the user obtained them out of band and is informing\n the store of their existence. The most common use case is for supporting client side\n nested URLs, such as `/posts/1/comments/2` so the user can do\n `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post.\n\n Preloaded data can be attributes and relationships passed in either as IDs or as actual\n models.\n */\ntype PreloadRelationshipValue = OpaqueRecordInstance | string;\nexport function preloadData(store: Store, identifier: NewResourceKey, preload: Record<string, Value>): void {\n const jsonPayload: Partial<ExistingResourceObject> = {};\n //TODO(Igor) consider the polymorphic case\n const schemas = store.schema;\n const fields = schemas.fields(identifier);\n Object.keys(preload).forEach((key) => {\n const preloadValue = preload[key];\n\n const field = fields.get(key);\n if (field && (field.kind === 'hasMany' || field.kind === 'belongsTo')) {\n if (!jsonPayload.relationships) {\n jsonPayload.relationships = {};\n }\n jsonPayload.relationships[key] = preloadRelationship(field, preloadValue);\n } else {\n if (!jsonPayload.attributes) {\n jsonPayload.attributes = {};\n }\n jsonPayload.attributes[key] = preloadValue;\n }\n });\n const cache = store.cache;\n const hasRecord = Boolean(store._instanceCache.peek(identifier));\n cache.upsert(identifier, jsonPayload, hasRecord);\n}\n\nfunction preloadRelationship(\n schema: RelationshipSchema,\n preloadValue: PreloadRelationshipValue | null | Array<PreloadRelationshipValue>\n): InnerRelationshipDocument<ExistingResourceIdentifierObject> {\n const relatedType = schema.type;\n\n if (schema.kind === 'hasMany') {\n assert('You need to pass in an array to set a hasMany property on a record', Array.isArray(preloadValue));\n return { data: preloadValue.map((value) => _convertPreloadRelationshipToJSON(value, relatedType)) };\n }\n\n assert('You should not pass in an array to set a belongsTo property on a record', !Array.isArray(preloadValue));\n return { data: preloadValue ? _convertPreloadRelationshipToJSON(preloadValue, relatedType) : null };\n}\n\n/*\n findRecord('user', '1', { preload: { friends: ['1'] }});\n findRecord('user', '1', { preload: { friends: [record] }});\n*/\nfunction _convertPreloadRelationshipToJSON(\n value: OpaqueRecordInstance | string,\n type: string\n): ExistingResourceIdentifierObject {\n if (typeof value === 'string' || typeof value === 'number') {\n return { type, id: ensureStringId(value) };\n }\n // TODO if not a record instance assert it's an identifier\n // and allow identifiers to be used\n return recordIdentifierFor(value) as ExistingResourceIdentifierObject;\n}\n\nexport interface BaseFinderOptions {\n reload?: boolean;\n backgroundReload?: boolean;\n include?: string | string[];\n adapterOptions?: Record<string, unknown>;\n}\nexport interface FindRecordOptions extends BaseFinderOptions {\n /**\n * Data to preload into the store before the request is made.\n * This feature is *highly* discouraged and has no corresponding\n * feature when using builders and handlers.\n *\n * Excepting relationships: the data should be in the form of a\n * JSON object where the keys are fields on the record and the value\n * is the raw value to be added to the cache.\n *\n * Relationships can either be provided as string IDs from which\n * an identifier will be built base upon the relationship's expected\n * resource type, or be record instances from which the identifier\n * will be extracted.\n *\n */\n preload?: Record<string, Value>;\n}\n\nexport type QueryOptions = {\n [K in string | 'adapterOptions']?: K extends 'adapterOptions' ? Record<string, unknown> : unknown;\n};\n\nexport type FindAllOptions = BaseFinderOptions;\nexport type LegacyResourceQuery = {\n include?: string | string[];\n [key: string]: Value | undefined;\n};\n\nexport type KeyOrString<T> = keyof T & string extends never ? string : keyof T & string;\n\n/**\n * Minimum subset of static schema methods and properties on the\n * \"model\" class.\n *\n * Only used when using the legacy schema-service implementation\n * for @warp-drive/legacy/model or when wrapping schema for legacy\n * Adapters/Serializers.\n *\n */\nexport interface ModelSchema<T = unknown> {\n /**\n * The resource type (model name) that this schema describes.\n */\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n\n /**\n * A map of every field defined on this resource type to its kind\n * (`'attribute'`, `'belongsTo'`, or `'hasMany'`).\n */\n fields: Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'>;\n\n /**\n * A map of every attribute field defined on this resource type, keyed by\n * attribute name.\n */\n attributes: Map<KeyOrString<T>, LegacyAttributeField>;\n\n /**\n * A map of every relationship (`belongsTo`/`hasMany`) field defined on this\n * resource type, keyed by relationship name.\n */\n relationshipsByName: Map<KeyOrString<T>, LegacyRelationshipField>;\n\n /**\n * Invokes `callback` once for each attribute field defined on this resource\n * type, passing the attribute's key and schema.\n */\n eachAttribute<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, attribute: LegacyAttributeField) => void,\n binding?: T\n ): void;\n\n /**\n * Invokes `callback` once for each relationship field defined on this\n * resource type, passing the relationship's key and schema.\n */\n eachRelationship<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, relationship: LegacyRelationshipField) => void,\n binding?: T\n ): void;\n\n /**\n * Invokes `callback` once for each attribute field defined on this resource\n * type that has a transform (a `type`), passing the attribute's key and the\n * name of the transform to apply.\n */\n eachTransformedAttribute<K extends KeyOrString<T>>(\n callback: (this: ModelSchema<T>, key: K, type: string | null) => void,\n binding?: T\n ): void;\n}\n\nfunction _resourceIsFullDeleted(identifier: ResourceKey, cache: Cache): boolean {\n return cache.isDeletionCommitted(identifier) || (cache.isNew(identifier) && cache.isDeleted(identifier));\n}\n\nexport function resourceIsFullyDeleted(instanceCache: InstanceCache, identifier: ResourceKey): boolean {\n const cache = instanceCache.cache;\n return !cache || _resourceIsFullDeleted(identifier, cache);\n}\n\n/**\n A `RecordReference` is a low-level API that allows users and\n addon authors to perform meta-operations on a record.\n\n @hideconstructor\n @public\n*/\nexport class RecordReference {\n /** @internal */\n declare private store: Store;\n // unsubscribe token given to us by the notification manager\n /** @internal */\n private ___token!: object;\n /** @internal */\n private ___identifier: ResourceKey;\n /** @internal */\n declare private _ref: number;\n\n constructor(store: Store, identifier: ResourceKey) {\n this.store = store;\n this.___identifier = identifier;\n this.___token = store.notifications.subscribe(\n identifier,\n (_: ResourceKey, bucket: NotificationType, notifiedKey?: string) => {\n if (bucket === 'identity' || (bucket === 'attributes' && notifiedKey === 'id')) {\n this._ref++;\n }\n }\n );\n }\n\n /** @internal */\n destroy(): void {\n this.store.notifications.unsubscribe(this.___token);\n }\n\n get type(): string {\n return this.identifier().type;\n }\n\n /**\n The `id` of the record that this reference refers to.\n\n Together, the `type` and `id` properties form a composite key for\n the identity map.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.id(); // '1'\n ```\n\n @public\n @return The id of the record.\n */\n id(): string | null {\n // oxlint-disable-next-line no-unused-expressions\n this._ref; // consume the tracked prop\n return this.___identifier.id;\n }\n\n /**\n The `identifier` of the record that this reference refers to.\n\n Together, the `type` and `id` properties form a composite key for\n the identity map.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.identifier(); // '1'\n ```\n\n @public\n @return The identifier of the record.\n */\n identifier(): ResourceKey {\n return this.___identifier;\n }\n\n /**\n How the reference will be looked up when it is loaded. Currently\n this always returns `identity` to signify that a record will be\n loaded by its `type` and `id`.\n\n Example\n\n ```javascript\n const userRef = store.getReference('user', 1);\n\n userRef.remoteType(); // 'identity'\n ```\n\n @public\n */\n remoteType(): 'identity' {\n return 'identity';\n }\n\n /**\n This API allows you to provide a reference with new data. The\n simplest usage of this API is similar to `store.push`: you provide a\n normalized hash of data and the object represented by the reference\n will update.\n\n If you pass a promise to `push`, WarpDrive will not ask the adapter\n for the data if another attempt to fetch it is made in the\n interim. When the promise resolves, the underlying object is updated\n with the new data, and the promise returned by *this function* is resolved\n with that object.\n\n For example, `recordReference.push(promise)` will be resolved with a\n record.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // provide data for reference\n userRef.push({\n data: {\n id: \"1\",\n type: \"user\",\n attributes: {\n username: \"@user\"\n }\n }\n }).then(function(user) {\n userRef.value() === user;\n });\n ```\n\n @public\n @param objectOrPromise a JSON:API ResourceDocument or a promise resolving to one\n @return a promise for the value (record or relationship)\n */\n push(objectOrPromise: SingleResourceDocument | Promise<SingleResourceDocument>): Promise<OpaqueRecordInstance> {\n // TODO @deprecate pushing unresolved payloads\n return Promise.resolve(objectOrPromise).then((data) => {\n return this.store.push(data);\n });\n }\n\n /**\n If the entity referred to by the reference is already loaded, it is\n present as `reference.value`. Otherwise the value returned by this function\n is `null`.\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n userRef.value(); // user\n ```\n\n @public\n @return the record for this RecordReference\n */\n value(): OpaqueRecordInstance | null {\n return this.store.peekRecord(this.___identifier);\n }\n\n /**\n Triggers a fetch for the backing entity based on its `remoteType`\n (see `remoteType` definitions per reference type).\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // load user (via store.find)\n userRef.load().then(...)\n ```\n\n @public\n @return the record for this RecordReference\n */\n load(): Promise<unknown> {\n const id = this.id();\n if (id !== null) {\n return this.store.findRecord(this.type, id);\n }\n assert(`Unable to fetch record of type ${this.type} without an id`);\n }\n\n /**\n Reloads the record if it is already loaded. If the record is not\n loaded it will load the record via `store.findRecord`\n\n Example\n\n ```javascript\n let userRef = store.getReference('user', 1);\n\n // or trigger a reload\n userRef.reload().then(...)\n ```\n\n @public\n @return the record for this RecordReference\n */\n reload(): Promise<unknown> {\n const id = this.id();\n if (id !== null) {\n return this.store.findRecord(this.type, id, { reload: true });\n }\n assert(`Unable to fetch record of type ${this.type} without an id`);\n }\n}\n\ndefineSignal(RecordReference.prototype, '_ref');\n\n// if modelFor turns out to be a bottleneck we should replace with a Map\n// and clear it during store teardown.\nconst AvailableShims = getOrSetGlobal('AvailableShims', new WeakMap<Store, Record<string, ShimModelClass>>());\n\nexport function getShimClass<T>(\n store: Store,\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string\n): ShimModelClass<T> {\n let shims = AvailableShims.get(store);\n\n if (!shims) {\n shims = Object.create(null) as Record<string, ShimModelClass>;\n AvailableShims.set(store, shims);\n }\n\n let shim = shims[modelName];\n if (shim === undefined) {\n shim = shims[modelName] = new ShimModelClass<unknown>(store, modelName);\n }\n\n return shim;\n}\n\n// Mimics the static apis of @warp-drive/legacy/model\nexport class ShimModelClass<T = unknown> implements ModelSchema<T> {\n declare __store: Store;\n declare modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n constructor(store: Store, modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string) {\n this.__store = store;\n this.modelName = modelName;\n }\n\n get fields(): Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'> {\n const fields = new Map<KeyOrString<T>, 'attribute' | 'belongsTo' | 'hasMany'>();\n const fieldSchemas = this.__store.schema.fields({ type: this.modelName });\n\n fieldSchemas.forEach((schema, key) => {\n if (schema.kind === 'attribute' || schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n fields.set(key as KeyOrString<T>, schema.kind);\n }\n });\n\n return fields;\n }\n\n get attributes(): Map<KeyOrString<T>, LegacyAttributeField> {\n const attrs = new Map<KeyOrString<T>, LegacyAttributeField>();\n const fields = this.__store.schema.fields({ type: this.modelName });\n\n fields.forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n attrs.set(key as KeyOrString<T>, schema);\n }\n });\n\n return attrs;\n }\n\n get relationshipsByName(): Map<KeyOrString<T>, LegacyRelationshipField> {\n const rels = new Map<KeyOrString<T>, LegacyRelationshipField>();\n const fields = this.__store.schema.fields({ type: this.modelName });\n\n fields.forEach((schema, key) => {\n if (schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n rels.set(key as KeyOrString<T>, schema);\n }\n });\n\n return rels;\n }\n\n eachAttribute<K extends KeyOrString<T>>(\n callback: (key: K, attribute: LegacyAttributeField) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n callback.call(binding, key as K, schema);\n }\n });\n }\n\n eachRelationship<K extends KeyOrString<T>>(\n callback: (key: K, relationship: LegacyRelationshipField) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'belongsTo' || schema.kind === 'hasMany') {\n callback.call(binding, key as K, schema);\n }\n });\n }\n\n eachTransformedAttribute<K extends KeyOrString<T>>(\n callback: (key: K, type: string | null) => void,\n binding?: T\n ): void {\n this.__store.schema.fields({ type: this.modelName }).forEach((schema, key) => {\n if (schema.kind === 'attribute') {\n const type = schema.type;\n if (type) callback.call(binding, key as K, type);\n }\n });\n }\n}\n","import { deprecate } from '@ember/debug';\n\nimport { ENABLE_LEGACY_REQUEST_METHODS } from '@warp-drive/build-config/deprecations';\nimport { assert } from '@warp-drive/build-config/macros';\n\nimport type { LegacyLiveArray, LegacyQueryArray } from '../-private';\nimport { constructResource, ensureStringId, recordIdentifierFor, storeFor } from '../-private';\nimport type { Caches } from '../-private/caches/instance-cache';\nimport { isMaybeIdentifier, Store } from '../-private/store-service';\nimport { normalizeModelName } from '../-private/utils/normalize-model-name';\nimport type { ResourceKey } from '../../types/identifier';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../types/record';\nimport { SkipCache } from '../../types/request';\nimport type { ResourceIdentifierObject } from '../../types/spec/json-api-raw';\nimport type { FindAllOptions, FindRecordOptions, LegacyResourceQuery, ModelSchema, QueryOptions } from './-private';\nimport { getShimClass, preloadData, RecordReference, resourceIsFullyDeleted } from './-private';\n\nif (ENABLE_LEGACY_REQUEST_METHODS) {\n Store.prototype.findRecord = function (\n resource: string | ResourceIdentifierObject,\n id?: string | number | FindRecordOptions,\n options?: FindRecordOptions\n ): Promise<unknown> {\n deprecate(`store.findRecord is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.findRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n\n assert(\n `You need to pass a modelName or resource identifier as the first argument to the store's findRecord method`,\n resource\n );\n if (isMaybeIdentifier(resource)) {\n options = id as FindRecordOptions | undefined;\n } else {\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${resource}`,\n typeof resource === 'string'\n );\n const type = normalizeModelName(resource);\n const normalizedId = ensureStringId(id as string | number);\n resource = constructResource(type, normalizedId);\n }\n\n const identifier = this.cacheKeyManager.getOrCreateRecordIdentifier(resource);\n options = options || {};\n\n if (options.preload) {\n // force reload if we preload to ensure we don't resolve the promise\n // until we are complete, else we will end up background-reloading\n // even for initial load.\n if (!this._instanceCache.recordIsLoaded(identifier)) {\n options.reload = true;\n }\n this._join(() => {\n preloadData(this, identifier, options.preload!);\n });\n }\n\n const promise = this.request<OpaqueRecordInstance>({\n op: 'findRecord',\n data: {\n record: identifier,\n options,\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => {\n return document.content;\n });\n };\n\n Store.prototype.findAll = function <T>(\n type: TypeFromInstance<T> | string,\n options: FindAllOptions = {}\n ): Promise<LegacyLiveArray<T>> {\n deprecate(`store.findAll is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.findAll(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's findAll method`, type);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<LegacyLiveArray<T>>({\n op: 'findAll',\n data: {\n type: normalizeModelName(type),\n options: options || {},\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.query = function (\n type: string,\n query: LegacyResourceQuery,\n options: QueryOptions = {}\n ): Promise<LegacyQueryArray> {\n deprecate(`store.query is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.query(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's query method`, type);\n assert(`You need to pass a query hash to the store's query method`, query);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<LegacyQueryArray>({\n op: 'query',\n data: {\n type: normalizeModelName(type),\n query,\n options: options,\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.queryRecord = function (\n type: string,\n query: Record<string, unknown>,\n options?: QueryOptions\n ): Promise<OpaqueRecordInstance | null> {\n deprecate(`store.queryRecord is deprecated. Use store.request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.queryRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`You need to pass a model name to the store's queryRecord method`, type);\n assert(`You need to pass a query hash to the store's queryRecord method`, query);\n assert(\n `Passing classes to store methods has been removed. Please pass a dasherized string instead of ${type}`,\n typeof type === 'string'\n );\n\n const promise = this.request<OpaqueRecordInstance | null>({\n op: 'queryRecord',\n data: {\n type: normalizeModelName(type),\n query,\n options: options || {},\n },\n cacheOptions: { [SkipCache]: true },\n });\n\n return promise.then((document) => document.content);\n };\n\n Store.prototype.getReference = function (\n resource: string | ResourceIdentifierObject,\n id: string | number\n ): RecordReference {\n deprecate(\n `store.getReference is deprecated. There is no direct replacement. For working with the cache and relationships, use the cache with the appropriate identifiers. To load, use store.request.`,\n false,\n {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n }\n );\n assert(\n `Attempted to call store.getReference(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n\n let resourceIdentifier: ResourceIdentifierObject;\n if (arguments.length === 1 && isMaybeIdentifier(resource)) {\n resourceIdentifier = resource;\n } else {\n const type = normalizeModelName(resource as string);\n const normalizedId = ensureStringId(id);\n resourceIdentifier = constructResource(type, normalizedId);\n }\n\n assert(\n 'getReference expected to receive either a resource identifier or type and id as arguments',\n isMaybeIdentifier(resourceIdentifier)\n );\n\n const identifier: ResourceKey = this.cacheKeyManager.getOrCreateRecordIdentifier(resourceIdentifier);\n\n const cache = upgradeInstanceCaches(this._instanceCache.__instances).reference;\n let reference = cache.get(identifier);\n\n if (!reference) {\n reference = new RecordReference(this, identifier);\n cache.set(identifier, reference);\n }\n return reference;\n };\n\n Store.prototype.modelFor = function <T>(\n type: T extends TypedRecordInstance ? TypeFromInstance<T> : string\n ): ModelSchema<T> {\n deprecate(\n `store.modelFor is deprecated, please use store.schema.fields({ type: '${type}' }) to access schema information instead.`,\n false,\n {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n }\n );\n assert(`Attempted to call store.modelFor(), but the store instance has already been destroyed.`, !this.isDestroyed);\n assert(`You need to pass <type> to the store's modelFor method`, typeof type === 'string' && type.length);\n assert(`No model was found for '${type}' and no schema handles the type`, this.schema.hasResource({ type }));\n\n return getShimClass<T>(this, type);\n };\n\n Store.prototype.saveRecord = function <T>(record: T, options: Record<string, unknown> = {}): Promise<T> {\n deprecate(`store.saveRecord is deprecated, please use store.request to initiate a save request instead.`, false, {\n id: 'warp-drive:deprecate-legacy-request-methods',\n until: '6.0',\n for: '@warp-drive/core',\n url: 'https://docs.warp-drive.io/api/@warp-drive/core/build-config/deprecations/variables/ENABLE_LEGACY_REQUEST_METHODS',\n since: {\n enabled: '5.7',\n available: '5.7',\n },\n });\n assert(\n `Attempted to call store.saveRecord(), but the store instance has already been destroyed.`,\n !(this.isDestroying || this.isDestroyed)\n );\n assert(`Unable to initiate save for a record in a disconnected state`, storeFor(record, true));\n const identifier = recordIdentifierFor(record);\n const cache = this.cache;\n\n if (!identifier) {\n // this commonly means we're disconnected\n // but just in case we reject here to prevent bad things.\n return Promise.reject(new Error(`Record Is Disconnected`));\n }\n assert(\n `Cannot initiate a save request for an unloaded record: ${identifier.lid}`,\n this._instanceCache.recordIsLoaded(identifier)\n );\n if (resourceIsFullyDeleted(this._instanceCache, identifier)) {\n return Promise.resolve(record);\n }\n\n if (!options) {\n options = {};\n }\n let operation: 'createRecord' | 'deleteRecord' | 'updateRecord' = 'updateRecord';\n\n if (cache.isNew(identifier)) {\n operation = 'createRecord';\n } else if (cache.isDeleted(identifier)) {\n operation = 'deleteRecord';\n }\n\n const request = {\n op: operation,\n data: {\n options,\n record: identifier,\n },\n records: [identifier],\n cacheOptions: { [SkipCache]: true },\n };\n\n return this.request<T>(request).then((document) => document.content);\n };\n}\n\nexport { Store };\n\nfunction upgradeInstanceCaches(cache: Caches): Caches & { reference: WeakMap<ResourceKey, RecordReference> } {\n const withReferences = cache as Caches & { reference: WeakMap<ResourceKey, RecordReference> };\n if (!withReferences.reference) {\n withReferences.reference = new WeakMap();\n }\n\n return withReferences;\n}\n","import type { RequestKey } from '../../../types/identifier.ts';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '../../../types/request.ts';\nimport type { ResourceDataDocument, ResourceErrorDocument } from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { Store } from '../store-service.ts';\n\nexport const MUTATION_OPS: Set<string> = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n !hasCachedValue ||\n (store.lifetimes && identifier ? store.lifetimes.isHardExpired(identifier, store) : false)\n );\n}\n\nexport function calcShouldBackgroundFetch(\n store: Store,\n request: ImmutableRequestInfo,\n willFetch: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n !willFetch &&\n (cacheOptions?.backgroundReload ||\n (store.lifetimes && identifier ? store.lifetimes.isSoftExpired(identifier, store) : false))\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nexport function isAggregateError(\n error: Error & { errors?: ApiError[] }\n): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\nexport type RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError): RobustError {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n\nexport function isErrorDocument(\n document: ResourceDataDocument | ResourceErrorDocument\n): document is ResourceErrorDocument {\n return 'errors' in document;\n}\n\nexport function getPriority(\n identifier: RequestKey | null,\n deduped: Map<RequestKey, { priority: { blocking: boolean } }>,\n priority: { blocking: boolean }\n): { blocking: boolean } {\n if (identifier) {\n const existing = deduped.get(identifier);\n if (existing) {\n return existing.priority;\n }\n }\n return priority;\n}\n","import { LOG_REQUESTS } from '@warp-drive/build-config/debugging';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { createReactiveDocument, type ReactiveDocument } from '../../../reactive/-private/document.ts';\nimport type { CacheHandler as CacheHandlerType, Future, ManagedRequestPriority, NextFn } from '../../../request.ts';\nimport type { RequestKey } from '../../../types/identifier.ts';\nimport type {\n ImmutableRequestInfo,\n RequestContext,\n StructuredDataDocument,\n StructuredErrorDocument,\n} from '../../../types/request.ts';\nimport { EnableHydration, SkipCache } from '../../../types/request.ts';\nimport type {\n CollectionResourceDataDocument,\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n SingleResourceDataDocument,\n} from '../../../types/spec/document.ts';\nimport type { ApiError } from '../../../types/spec/error.ts';\nimport type { ResourceIdentifierObject } from '../../../types/spec/json-api-raw.ts';\nimport type { RequestSignature } from '../../../types/symbols.ts';\nimport { log } from '../debug/utils.ts';\nimport type { Store } from '../store-service.ts';\nimport {\n calcShouldBackgroundFetch,\n calcShouldFetch,\n cloneError,\n getPriority,\n isCacheAffecting,\n isMutation,\n} from './utils.ts';\n\nexport type LooseStoreRequestInfo<RT = unknown> = Omit<\n ImmutableRequestInfo<RT>,\n 'records' | 'headers' | typeof RequestSignature\n> & {\n records?: ResourceIdentifierObject[];\n headers?: Headers;\n};\n\n/**\n * The request shape accepted by {@link Store.request}, either a fully-formed\n * {@link ImmutableRequestInfo} or the looser {@link LooseStoreRequestInfo}.\n */\nexport type StoreRequestInput<RT = unknown> = ImmutableRequestInfo<RT> | LooseStoreRequestInfo<RT>;\n\nexport interface StoreRequestContext extends RequestContext {\n request: ImmutableRequestInfo & {\n /** the store instance the request was issued through, used to enable store-aware cache handling. */\n store: Store;\n };\n}\n\n/**\n * A CacheHandler that adds support for using an WarpDrive Cache with a RequestManager.\n *\n * This handler will only run when a request has supplied a `store` instance. Requests\n * issued by the store via `store.request()` will automatically have the `store` instance\n * attached to the request.\n *\n * ```ts\n * requestManager.request({\n * store: store,\n * url: '/api/posts',\n * method: 'GET'\n * });\n * ```\n *\n * When this handler elects to handle a request, it will return the raw `StructuredDocument`\n * unless the request has `[EnableHydration]` set to `true`. In this case, the handler will\n * return a `Document` instance that will automatically update the UI when the cache is updated\n * in the future and will hydrate any identifiers in the StructuredDocument into Record instances.\n *\n * When issuing a request via the store, [EnableHydration] is automatically set to `true`. This\n * means that if desired you can issue requests that utilize the cache without needing to also\n * utilize Record instances if desired.\n *\n * Said differently, you could elect to issue all requests via a RequestManager, without ever using\n * the store directly, by setting [EnableHydration] to `true` and providing a store instance. Not\n * necessarily the most useful thing, but the decoupled nature of the RequestManager and incremental-feature\n * approach of WarpDrive allows for this flexibility.\n *\n * ```ts\n * import { EnableHydration } from '@warp-drive/core/types/request';\n *\n * requestManager.request({\n * store: store,\n * url: '/api/posts',\n * method: 'GET',\n * [EnableHydration]: true\n * });\n *\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(\n context: StoreRequestContext & { setIdentifier(identifier: RequestKey): void },\n next: NextFn<T>\n ): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(context.request);\n\n if (identifier) {\n context.setIdentifier(identifier);\n }\n\n // used to dedupe existing requests that match\n const DEDUPE = store.requestManager._deduped;\n const activeRequest = identifier && DEDUPE.get(identifier);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n // determine if we should skip cache\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n if (activeRequest) {\n activeRequest.priority = { blocking: true };\n if (LOG_REQUESTS) {\n log('request', '', 'DEDUPED', identifier.lid, 'blocking', '');\n }\n return activeRequest.promise as Promise<T>;\n }\n if (LOG_REQUESTS) {\n log(\n 'request',\n '',\n 'ISSUED',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'blocking',\n ''\n );\n }\n let promise = fetchContentAndHydrate(next, context, identifier, { blocking: true });\n if (identifier) {\n promise = promise.finally(() => {\n DEDUPE.delete(identifier);\n store.notifications.notify(identifier, 'state', null);\n });\n DEDUPE.set(identifier, { priority: { blocking: true }, promise });\n queueMicrotask(() => {\n store.notifications.notify(identifier, 'state', null);\n });\n }\n store.requestManager._pending.set(context.id, promise);\n return promise;\n }\n\n // if we have not skipped cache, determine if we should update behind the scenes\n if (calcShouldBackgroundFetch(store, context.request, false, identifier)) {\n let promise = activeRequest?.promise || fetchContentAndHydrate(next, context, identifier, { blocking: false });\n if (identifier && !activeRequest) {\n promise = promise.finally(() => {\n DEDUPE.delete(identifier);\n store.notifications.notify(identifier, 'state', null);\n });\n DEDUPE.set(identifier, { priority: { blocking: false }, promise });\n queueMicrotask(() => {\n store.notifications.notify(identifier, 'state', null);\n });\n }\n if (LOG_REQUESTS) {\n if (activeRequest && identifier) {\n log(\n 'request',\n '',\n 'DEDUPED',\n identifier.lid,\n activeRequest.priority.blocking ? 'blocking' : 'non-blocking',\n ''\n );\n } else {\n log(\n 'request',\n '',\n 'ISSUED',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'non-blocking',\n ''\n );\n }\n }\n store.requestManager._pending.set(context.id, promise);\n }\n\n if (LOG_REQUESTS) {\n log(\n 'request',\n '',\n 'CACHE-HIT',\n identifier?.lid ?? context.request.url ?? context.request.op ?? '<unknown request>',\n 'cached',\n ''\n );\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n\n const shouldHydrate: boolean = context.request[EnableHydration] || false;\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n const content = shouldHydrate\n ? maybeUpdateUiObjects<T>(store, context.request, { shouldHydrate, identifier }, peeked.content)\n : peeked.content;\n const newError = cloneError(peeked);\n newError.content = content;\n throw newError;\n }\n\n const result = shouldHydrate\n ? (maybeUpdateUiObjects<T>(store, context.request, { shouldHydrate, identifier }, peeked.content) as T)\n : (peeked.content as T);\n\n return result;\n },\n};\n\ntype HydrationOptions = {\n shouldHydrate?: boolean;\n identifier: RequestKey | null;\n};\n\ntype UpdateOptions = HydrationOptions & {\n priority: ManagedRequestPriority;\n};\n\nfunction maybeUpdateUiObjects<T>(\n store: Store,\n request: ImmutableRequestInfo,\n options: HydrationOptions,\n document: ResourceDocument | null | undefined\n): ReactiveDocument<T> | ResourceDocument | null {\n const { identifier } = options;\n\n if (!document || !options.shouldHydrate) {\n assert(`The CacheHandler expected response content but none was found`, !options.shouldHydrate);\n return document ?? null;\n }\n\n if (identifier) {\n return store._instanceCache.getDocument<T>(identifier);\n }\n\n // if we don't have an identifier, we give the document\n // its own local cache\n return createReactiveDocument<T>(store, null, {\n request,\n document,\n });\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n options: HydrationOptions,\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n if (Array.isArray(request.records)) {\n response = store.cache.didCommit(\n request.records,\n document as StructuredDataDocument<CollectionResourceDataDocument>\n );\n } else if (request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n response = store.cache.didCommit(\n request.data.record,\n document as StructuredDataDocument<SingleResourceDataDocument>\n );\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n }\n return maybeUpdateUiObjects(store, request, options, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n context: StoreRequestContext,\n options: UpdateOptions,\n document: StructuredDataDocument<T>\n): ResourceDataDocument | void {\n const { request } = context;\n store.requestManager._pending.delete(context.id);\n store._enableAsyncFlush = true;\n let response: ResourceDataDocument;\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, options, document) as ResourceDataDocument;\n });\n store._enableAsyncFlush = null;\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(context.request, document.response, options.identifier, store);\n }\n\n const finalPriority = getPriority(options.identifier, store.requestManager._deduped, options.priority);\n if (finalPriority.blocking) {\n return response!;\n } else {\n store.notifications._flush();\n }\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n context: StoreRequestContext,\n options: HydrationOptions,\n error: StructuredErrorDocument<T>\n) {\n let response: ResourceErrorDocument | undefined;\n if (isMutation(context.request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n if (Array.isArray(context.request.records)) {\n store.cache.commitWasRejected(context.request.records, errors);\n } else if (context.request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n store.cache.commitWasRejected(context.request.data.record, errors);\n } else {\n store.cache.put(error) as ResourceErrorDocument;\n }\n } else {\n response = store.cache.put(error) as ResourceErrorDocument;\n return maybeUpdateUiObjects(store, context.request, options, response);\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n context: StoreRequestContext,\n options: UpdateOptions,\n error: StructuredErrorDocument<T>\n): ResourceErrorDocument | void {\n store.requestManager._pending.delete(context.id);\n if (context.request.signal?.aborted) {\n throw error;\n }\n store._enableAsyncFlush = true;\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, context, options, error) as ResourceErrorDocument;\n });\n store._enableAsyncFlush = null;\n\n if (options.identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(context.request, error.response, options.identifier, store);\n }\n\n if (isMutation(context.request)) {\n throw error;\n }\n\n const finalPriority = getPriority(options.identifier, store.requestManager._deduped, options.priority);\n if (finalPriority.blocking) {\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n } else {\n store.notifications._flush();\n }\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: RequestKey | null,\n priority: { blocking: boolean }\n): Promise<T> {\n const { store } = context.request;\n const shouldHydrate: boolean = context.request[EnableHydration] || false;\n const options = { shouldHydrate, identifier, priority };\n\n let isMut = false;\n if (isMutation(context.request)) {\n isMut = true;\n\n if (Array.isArray(context.request.records)) {\n context.request.records.forEach((record) => {\n store.cache.willCommit(record, context);\n });\n } else if (context.request.data?.record) {\n // legacy fallback, the data option should no longer be used for this\n store.cache.willCommit(context.request.data.record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(context.request, identifier, store);\n }\n\n const promise = next(context.request).then(\n (document) => {\n return handleFetchSuccess(store, context, options, document);\n },\n (error: StructuredErrorDocument<T>) => {\n return handleFetchError(store, context, options, error);\n }\n ) as Promise<T>;\n\n if (!isMut) {\n return promise;\n }\n assert(`Expected a mutation`, isMutation(context.request));\n\n // for mutations we need to enqueue the promise with the requestStateService\n // TODO should we enque a request per record in records?\n const record = context.request.data?.record || context.request.records?.[0];\n\n return store._requestCache._enqueue(promise, {\n data: [{ op: 'saveRecord', recordIdentifier: record, options: undefined }],\n });\n}\n","export function isNonEmptyString(str: unknown): str is string {\n return Boolean(str && typeof str === 'string');\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { ExistingResourceIdentifierObject, ResourceIdentifierObject } from '../../../types/spec/json-api-raw.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport { coerceId } from './coerce-id.ts';\nimport { isNonEmptyString } from './is-non-empty-string.ts';\n\n/**\n * Given an existing resource identifier object (or a {@link ResourceKey}),\n * returns it unchanged aside from coercing its `id`, if present, to a string.\n *\n * @private\n */\nexport function constructResource(type: ResourceIdentifierObject): ResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type`, `id`, and `lid`, all of which\n * are known to be present, producing an {@link ExistingResourceIdentifierObject}.\n *\n * @private\n */\nexport function constructResource(type: string, id: string, lid: string): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `lid` alone, for the case where `type`\n * and `id` are not (yet) known.\n *\n * @private\n */\nexport function constructResource(\n type: string | undefined,\n id: null | undefined,\n lid: string\n): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type` and `id`, with an optional `lid`,\n * producing an {@link ExistingResourceIdentifierObject}.\n *\n * @private\n */\nexport function constructResource(type: string, id: string, lid?: string | null): ExistingResourceIdentifierObject;\n/**\n * Builds a resource identifier from a `type` and an optional `id`/`lid`. If no\n * usable `id` is provided, falls back to constructing a `lid`-only identifier.\n *\n * @private\n */\nexport function constructResource(\n type: string,\n id?: string | number | null,\n lid?: string | null\n): ResourceIdentifierObject;\n/**\n * Implementation for {@link constructResource}. Normalizes the supplied\n * `type`/`id`/`lid` (or existing resource identifier object) into a valid\n * {@link ResourceIdentifierObject}, coercing the id and asserting that enough\n * information was provided to identify the resource.\n *\n * @private\n */\nexport function constructResource(\n type: string | ResourceIdentifierObject | undefined,\n id?: string | number | null,\n lid?: string | null\n): ResourceIdentifierObject | ExistingResourceIdentifierObject {\n if (typeof type === 'object' && type !== null) {\n const resource = type;\n if (isResourceKey(resource)) {\n return resource;\n }\n if ('id' in resource) {\n resource.id = coerceId(resource.id);\n }\n\n assert(\n 'Expected either id or lid to be a valid string',\n ('id' in resource && isNonEmptyString(resource.id)) || isNonEmptyString(resource.lid)\n );\n assert('if id is present, the type must be a string', !('id' in resource) || typeof resource.type === 'string');\n\n return resource;\n } else {\n const trueId = coerceId(id);\n if (!isNonEmptyString(trueId)) {\n if (isNonEmptyString(lid)) {\n return { lid };\n }\n throw new Error('Expected either id or lid to be a valid string');\n }\n\n assert('type must be a string', typeof type === 'string');\n\n if (isNonEmptyString(lid)) {\n return { type, id: trueId, lid };\n }\n\n return { type, id: trueId };\n }\n}\n","// every `target[prop]` extraction below is immediately invoked via `Reflect.apply(fn, receiver, args)`,\n// which is the correct way to call an unbound method with an explicit `this` — the rule can't see that\n/* oxlint-disable typescript/unbound-method */\nimport { deprecate } from '@ember/debug';\n\nimport { DEPRECATE_MANY_ARRAY_DUPLICATES } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { Context } from '../../../reactive/-private.ts';\nimport { notifyInternalSignal, type WarpDriveSignal } from '../../../signals/-private.ts';\nimport type { BaseFinderOptions, ResourceKey } from '../../../types.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { ObjectValue } from '../../../types/json/raw.ts';\nimport type { OpaqueRecordInstance, TypedRecordInstance, TypeFromInstance } from '../../../types/record.ts';\nimport type { LegacyHasManyField, LinksModeHasManyField } from '../../../types/schema/fields.ts';\nimport type { Links, Meta, PaginationLinks } from '../../../types/spec/json-api-raw.ts';\nimport { recordIdentifierFor } from '../caches/instance-cache.ts';\nimport { isResourceKey } from '../managers/cache-key-manager.ts';\nimport type { CreateRecordProperties } from '../store-service.ts';\nimport { save } from './-utils.ts';\nimport type { LegacyLiveArrayCreateOptions } from './legacy-live-array.ts';\nimport type { NativeProxy } from './native-proxy-type-fix.ts';\nimport { createReactiveResourceArray, destroy, type ReactiveResourceArray } from './resource-array.ts';\n\n/**\n A `ManyArray` is a `MutableArray` that represents the contents of a has-many\n relationship.\n\n The `ManyArray` is instantiated lazily the first time the relationship is\n requested.\n\n This class is not intended to be directly instantiated by consuming applications.\n\n ### Inverses\n\n Often, the relationships in WarpDrive applications will have\n an inverse. For example, imagine the following models are\n defined:\n\n ```js [app/models/post.js]\n import Model, { hasMany } from '@ember-data/model';\n\n export default class PostModel extends Model {\n @hasMany('comment') comments;\n }\n ```\n\n ```js [app/models/comment.js]\n import { Model, belongsTo } from '@warp-drive/legacy/model';\n\n export default class CommentModel extends Model {\n @belongsTo('post') post;\n }\n ```\n\n If you created a new instance of `Post` and added\n a `Comment` record to its `comments` has-many\n relationship, you would expect the comment's `post`\n property to be set to the post that contained\n the has-many.\n\n We call the record to which a relationship belongs-to the\n relationship's _owner_.\n\n @public\n*/\nexport interface LegacyManyArray<T = unknown> extends ReactiveResourceArray<T> {\n /**\n The meta data for the has-many relationship, as returned in the\n relationship's payload from the server.\n\n @public\n */\n meta: Meta | null;\n\n /**\n The links for the has-many relationship, as returned in the\n relationship's payload from the server. Used to refetch the\n relationship when reloading.\n\n @public\n */\n links: Links | PaginationLinks | null;\n\n /** @internal */\n isPolymorphic: boolean;\n /** @internal */\n isAsync: boolean;\n\n /** @private */\n key: string;\n /** @private */\n modelName: T extends TypedRecordInstance ? TypeFromInstance<T> : string;\n\n /**\n The loading state of this array\n @public\n */\n isLoaded: boolean;\n\n /** @internal */\n notify(): void;\n\n /**\n Reloads all of the records in the manyArray. If the manyArray\n holds a relationship that was originally fetched using a links url\n WarpDrive will revisit the original links url to repopulate the\n relationship.\n\n If the ManyArray holds the result of a `store.query()` reload will\n re-run the original query.\n\n Example\n\n ```javascript\n let user = store.peekRecord('user', '1')\n await login(user);\n\n let permissions = await user.permissions;\n await permissions.reload();\n ```\n\n @public\n */\n reload(options?: BaseFinderOptions): Promise<LegacyManyArray<T>>;\n\n /**\n Create a child record and associated it to the collection\n\n @public\n */\n createRecord(hash: CreateRecordProperties<T>): T;\n\n /**\n Saves all of the records in the `ManyArray`.\n\n Note: this API can only be used in legacy mode with a configured Adapter.\n\n Example\n\n ```js\n const { content: { data: inbox } } = await store.request(findRecord({ type: 'inbox', id: '1' }));\n\n let messages = await inbox.messages;\n messages.forEach((message) => {\n message.isRead = true;\n });\n messages.save();\n ```\n\n @public\n */\n save: () => Promise<LegacyManyArray<T>>;\n\n /** @private */\n destroy: () => void;\n}\n\n/**\n * The options for {@link createLegacyManyArray}\n *\n * @private\n */\nexport interface LegacyManyArrayCreateOptions extends LegacyLiveArrayCreateOptions {\n isLoaded: boolean;\n editable: boolean;\n isAsync: boolean;\n isPolymorphic: boolean;\n field: LegacyHasManyField | LinksModeHasManyField;\n identifier: ResourceKey;\n links: Links | PaginationLinks | null;\n meta: Meta | null;\n}\n/**\n * Creates a {@link LegacyManyArray}\n *\n * @private\n */\nexport function createLegacyManyArray<T>(options: LegacyManyArrayCreateOptions): LegacyManyArray<T> {\n const extensions = options.store.schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions\n ? options.store.schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions(options.field)\n : null;\n\n return createReactiveResourceArray({\n store: options.store,\n manager: options.manager,\n editable: options.editable,\n source: options.source,\n data: {\n links: options.links,\n meta: options.meta,\n } as ObjectValue,\n features: {\n modelName: options.type,\n save,\n DEPRECATED_CLASS_NAME: 'ManyArray',\n isLoaded: options.isLoaded,\n isAsync: options.isAsync,\n isPolymorphic: options.isPolymorphic,\n identifier: options.identifier,\n key: options.field.name,\n reload,\n createRecord,\n notify,\n },\n extensions,\n options: null,\n destroy: destroyLegacyManyArray,\n mutate: _MUTATE,\n }) as LegacyManyArray<T>;\n}\n\nfunction _MUTATE<T>(\n target: ResourceKey[],\n receiver: typeof NativeProxy<ResourceKey[], T[]>,\n prop: string,\n args: unknown[],\n _SIGNAL: WarpDriveSignal\n): unknown {\n const collection = receiver as unknown as LegacyManyArray<T>;\n switch (prop) {\n case 'length 0': {\n Reflect.set(target, 'length', 0);\n mutateReplaceRelatedRecords(collection, [], _SIGNAL);\n return true;\n }\n case 'replace cell': {\n const [index, prior, value] = args as [number, ResourceKey, ResourceKey];\n target[index] = value;\n mutateReplaceRelatedRecord(collection, { value, prior, index }, _SIGNAL);\n return true;\n }\n case 'push': {\n const newValues = extractIdentifiersFromRecords(args);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.push(...newValues),\n `Cannot push duplicates to a hasMany's state.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const seen = new Set(target);\n const unique = new Set<OpaqueRecordInstance>();\n\n args.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.add(item);\n }\n });\n\n const newArgs = Array.from(unique);\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n if (newArgs.length) {\n mutateAddToRelatedRecords(collection, { value: extractIdentifiersFromRecords(newArgs) }, _SIGNAL);\n }\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (newValues.length) {\n mutateAddToRelatedRecords(collection, { value: newValues }, _SIGNAL);\n }\n return result;\n }\n\n case 'pop': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n if (result) {\n mutateRemoveFromRelatedRecords(\n collection,\n { value: recordIdentifierFor(result as OpaqueRecordInstance) },\n _SIGNAL\n );\n }\n return result;\n }\n\n case 'unshift': {\n const newValues = extractIdentifiersFromRecords(args);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.unshift(...newValues),\n `Cannot unshift duplicates to a hasMany's state.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const seen = new Set(target);\n const unique = new Set<OpaqueRecordInstance>();\n\n args.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.add(item);\n }\n });\n\n const newArgs = Array.from(unique);\n const result: unknown = Reflect.apply(target[prop], receiver, newArgs);\n\n if (newArgs.length) {\n mutateAddToRelatedRecords(collection, { value: extractIdentifiersFromRecords(newArgs), index: 0 }, _SIGNAL);\n }\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (newValues.length) {\n mutateAddToRelatedRecords(collection, { value: newValues, index: 0 }, _SIGNAL);\n }\n return result;\n }\n\n case 'shift': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n\n if (result) {\n mutateRemoveFromRelatedRecords(\n collection,\n { value: recordIdentifierFor(result as OpaqueRecordInstance), index: 0 },\n _SIGNAL\n );\n }\n return result;\n }\n\n case 'sort': {\n const result: unknown = Reflect.apply(target[prop], receiver, args);\n mutateSortRelatedRecords(collection, (result as OpaqueRecordInstance[]).map(recordIdentifierFor), _SIGNAL);\n return result;\n }\n\n case 'splice': {\n const [start, _deleteCount, ...adds] = args as [number, number | undefined, ...OpaqueRecordInstance[]];\n\n // Don't know if I like this approach, is there not a way where we can just use splice, see what it deleted and go from there?\n let deleteCount;\n if (args.length === 1) {\n // Omitting deleteCount: remove ALL elements (a.k.a. Infinity)\n deleteCount = Infinity;\n } else {\n // deleteCount is undefined, not a valid number, a negative number...\n if (typeof _deleteCount !== 'number' || _deleteCount < 0) {\n // do not remove any elements\n deleteCount = 0;\n } else {\n deleteCount = _deleteCount;\n }\n }\n\n // sanitize deleteCount to not exceed length / amount of items from index to end\n deleteCount = Math.min(collection[Context].source.length - start, deleteCount);\n\n // detect a full replace\n if (start === 0 && deleteCount === collection[Context].source.length) {\n const newValues = extractIdentifiersFromRecords(adds);\n\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.splice(start, deleteCount, ...newValues),\n `Cannot replace a hasMany's state with a new state that contains duplicates.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const current = new Set(adds);\n const unique = Array.from(current);\n const newArgs = ([start, deleteCount] as unknown[]).concat(unique);\n\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n mutateReplaceRelatedRecords(collection, extractIdentifiersFromRecords(unique), _SIGNAL);\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n mutateReplaceRelatedRecords(collection, newValues, _SIGNAL);\n return result;\n }\n\n const newValues = extractIdentifiersFromRecords(adds);\n assertNoDuplicates(\n collection,\n target,\n (currentState) => currentState.splice(start, deleteCount, ...newValues),\n `Cannot splice a hasMany's state with a new state that contains duplicates.`\n );\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n // dedupe\n const currentState = target.slice();\n currentState.splice(start, deleteCount);\n\n const seen = new Set(currentState);\n const unique: OpaqueRecordInstance[] = [];\n adds.forEach((item) => {\n const identifier = recordIdentifierFor(item);\n if (!seen.has(identifier)) {\n seen.add(identifier);\n unique.push(item);\n }\n });\n\n const newArgs = [start, deleteCount, ...unique];\n const result = Reflect.apply(target[prop], receiver, newArgs) as OpaqueRecordInstance[];\n\n if (deleteCount > 0) {\n mutateRemoveFromRelatedRecords(collection, { value: result.map(recordIdentifierFor), index: start }, _SIGNAL);\n }\n\n if (unique.length > 0) {\n mutateAddToRelatedRecords(\n collection,\n { value: extractIdentifiersFromRecords(unique), index: start },\n _SIGNAL\n );\n }\n\n return result;\n }\n\n // else, no dedupe, error on duplicates\n const result = Reflect.apply(target[prop], receiver, args) as OpaqueRecordInstance[];\n if (deleteCount > 0) {\n mutateRemoveFromRelatedRecords(collection, { value: result.map(recordIdentifierFor), index: start }, _SIGNAL);\n }\n if (newValues.length > 0) {\n mutateAddToRelatedRecords(collection, { value: newValues, index: start }, _SIGNAL);\n }\n return result;\n }\n default:\n assert(`unable to convert ${prop} into a transaction that updates the cache state for this record array`);\n }\n}\n\nfunction notify(this: LegacyManyArray): void {\n notifyInternalSignal(this[Context].signal);\n}\n\nfunction reload<T>(this: LegacyManyArray<T>, options?: BaseFinderOptions): Promise<LegacyManyArray<T>> {\n const { manager } = this[Context];\n assert(`Expected the manager for ManyArray to implement reloadHasMany`, typeof manager.reloadHasMany === 'function');\n // TODO this is odd, we don't ask the store for anything else like this?\n return manager.reloadHasMany<T>(this.key, options) as Promise<LegacyManyArray<T>>;\n}\n\nfunction createRecord<T>(this: LegacyManyArray<T>, hash: CreateRecordProperties<T>): T {\n const { store } = this[Context];\n assert(`Expected modelName to be set`, this.modelName);\n const record = store.createRecord<T>(this.modelName as TypeFromInstance<T>, hash);\n this.push(record);\n\n return record;\n}\n\nfunction destroyLegacyManyArray(this: ReactiveResourceArray): void {\n destroy.call(this, false);\n}\n\ntype PromiseProxyRecord = { then(): void; content: OpaqueRecordInstance | null | undefined };\n\nfunction assertRecordPassedToHasMany(record: OpaqueRecordInstance | PromiseProxyRecord) {\n assert(\n `All elements of a hasMany relationship must be instances of Model, you passed ${typeof record}`,\n (function () {\n try {\n recordIdentifierFor(record);\n return true;\n } catch {\n return false;\n }\n })()\n );\n}\n\nfunction extractIdentifiersFromRecords(records: OpaqueRecordInstance[]): ResourceKey[] {\n return records.map(extractIdentifierFromRecord);\n}\n\nfunction extractIdentifierFromRecord(recordOrPromiseRecord: PromiseProxyRecord | OpaqueRecordInstance) {\n assertRecordPassedToHasMany(recordOrPromiseRecord);\n return recordIdentifierFor(recordOrPromiseRecord);\n}\n\nfunction assertNoDuplicates<T>(\n collection: LegacyManyArray<T>,\n target: ResourceKey[],\n callback: (currentState: ResourceKey[]) => void,\n reason: string\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n const state = target.slice();\n callback(state);\n\n if (state.length !== new Set(state).size) {\n const duplicates = state.filter((currentValue, currentIndex) => state.indexOf(currentValue) !== currentIndex);\n\n if (DEPRECATE_MANY_ARRAY_DUPLICATES) {\n deprecate(\n `${reason} This behavior is deprecated. Found duplicates for the following records within the new state provided to \\`<${\n identifier.type\n }:${identifier.id || identifier.lid}>.${collection.key}\\`\\n\\t- ${Array.from(new Set(duplicates))\n .map((r) => (isResourceKey(r) ? r.lid : recordIdentifierFor(r).lid))\n .sort((a, b) => a.localeCompare(b))\n .join('\\n\\t- ')}`,\n false,\n {\n id: 'ember-data:deprecate-many-array-duplicates',\n for: 'ember-data',\n until: '6.0',\n since: {\n enabled: '5.3',\n available: '4.13',\n },\n }\n );\n } else {\n throw new Error(\n `${reason} Found duplicates for the following records within the new state provided to \\`<${\n identifier.type\n }:${identifier.id || identifier.lid}>.${collection.key}\\`\\n\\t- ${Array.from(new Set(duplicates))\n .map((r) => (isResourceKey(r) ? r.lid : recordIdentifierFor(r).lid))\n .sort((a, b) => a.localeCompare(b))\n .join('\\n\\t- ')}`\n );\n }\n }\n}\n\nfunction mutateAddToRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n operationInfo: { value: ResourceKey | ResourceKey[]; index?: number },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'add',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateRemoveFromRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n operationInfo: { value: ResourceKey | ResourceKey[]; index?: number },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'remove',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateReplaceRelatedRecord<T>(\n collection: LegacyManyArray<T>,\n operationInfo: {\n value: ResourceKey;\n prior: ResourceKey;\n index: number;\n },\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'replaceRelatedRecord',\n record: identifier,\n field: collection.key,\n ...operationInfo,\n },\n _SIGNAL\n );\n}\n\nfunction mutateReplaceRelatedRecords<T>(\n collection: LegacyManyArray<T>,\n value: ResourceKey[],\n _SIGNAL: WarpDriveSignal\n) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'replaceRelatedRecords',\n record: identifier,\n field: collection.key,\n value,\n },\n _SIGNAL\n );\n}\n\nfunction mutateSortRelatedRecords<T>(collection: LegacyManyArray<T>, value: ResourceKey[], _SIGNAL: WarpDriveSignal) {\n const identifier = collection[Context].features!.identifier as ResourceKey;\n\n // FIXME field needs to use sourceKey\n mutate(\n collection,\n {\n op: 'sortRelatedRecords',\n record: identifier,\n field: collection.key,\n value,\n },\n _SIGNAL\n );\n}\n\nfunction mutate<T>(collection: LegacyManyArray<T>, mutation: LocalRelationshipOperation, _SIGNAL: WarpDriveSignal) {\n const { manager } = collection[Context];\n\n assert(`Expected the manager for ManyArray to implement mutate`, typeof manager.mutate === 'function');\n manager.mutate(mutation);\n notifyInternalSignal(_SIGNAL);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { LegacyAliasField, ObjectAliasField, PolarisAliasField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getAliasField(context: KindContext<LegacyAliasField | ObjectAliasField | PolarisAliasField>): unknown {\n assert(`Alias field access is not implemented`);\n}\n\nexport function setAliasField(context: KindContext<LegacyAliasField | ObjectAliasField | PolarisAliasField>): boolean {\n assert(`Alias field setting is not implemented`);\n return false;\n}\n","import { DEPRECATE_COMPUTED_CHAINS } from '@warp-drive/build-config/deprecations';\nimport { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../../index.ts';\nimport type { WarpDriveSignal } from '../../../signals/-private.ts';\nimport { ARRAY_SIGNAL, consumeInternalSignal, entangleSignal, withSignalStore } from '../../../signals/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { ArrayValue, ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { OpaqueRecordInstance } from '../../../types/record.ts';\nimport type { ArrayField, HashField, SchemaArrayField } from '../../../types/schema/fields.ts';\nimport type { KindContext, ObjectContext } from '../default-mode.ts';\nimport { ReactiveResource } from '../record.ts';\nimport type { SchemaService } from '../schema.ts';\nimport { Context, Destroy, SOURCE } from '../symbols.ts';\nimport type { ProxiedMethod } from './extension.ts';\nimport { isExtensionProp, performArrayExtensionGet, performExtensionSet } from './extension.ts';\n\ntype KeyType = string | symbol | number;\nconst ARRAY_GETTER_METHODS = new Set<KeyType>([\n Symbol.iterator,\n 'concat',\n 'entries',\n 'every',\n 'fill',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'forEach',\n 'includes',\n 'indexOf',\n 'join',\n 'keys',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'values',\n]);\n// const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\nconst SYNC_PROPS = new Set<KeyType>(['[]', 'length']);\nfunction isArrayGetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_GETTER_METHODS.has(prop);\n}\nconst ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);\n\nfunction isArraySetter<T>(prop: KeyType): prop is keyof Array<T> {\n return ARRAY_SETTER_METHODS.has(prop);\n}\n\n// function isSelfProp<T extends object>(self: T, prop: KeyType): prop is keyof T {\n// return prop in self;\n// }\n\nfunction convertToInt(prop: KeyType): number | null {\n if (typeof prop === 'symbol') return null;\n\n const num = Number(prop);\n\n if (isNaN(num)) return null;\n\n return num % 1 === 0 ? num : null;\n}\n\ntype ForEachCB = (record: OpaqueRecordInstance, index: number, context: typeof Proxy<unknown[]>) => void;\nfunction safeForEach(\n instance: typeof Proxy<unknown[]>,\n arr: unknown[],\n store: Store,\n callback: ForEachCB,\n target: unknown\n) {\n if (target === undefined) {\n target = null;\n }\n // clone to prevent mutation\n arr = arr.slice();\n assert('`forEach` expects a function as first argument.', typeof callback === 'function');\n\n // because we retrieveLatest above we need not worry if array is mutated during iteration\n // by unloadRecord/rollbackAttributes\n // push/add/removeObject may still be problematic\n // but this is a more traditionally expected forEach bug.\n const length = arr.length; // we need to access length to ensure we are consumed\n\n for (let index = 0; index < length; index++) {\n callback.call(target, arr[index], index, instance);\n }\n\n return instance;\n}\n\ntype MemoizedSchemaObject = {\n type: string;\n identity: number | string | object;\n index: number;\n context: ObjectContext;\n value: WeakRef<ReactiveResource>;\n};\n\nexport interface ManagedArray extends Omit<Array<unknown>, '[]'> {\n [SOURCE]: unknown[];\n identifier: ResourceKey;\n path: string | string[];\n owner: ReactiveResource;\n [ARRAY_SIGNAL]: WarpDriveSignal;\n [Context]: KindContext<SchemaArrayField | ArrayField>;\n}\n\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ManagedArray {\n constructor(context: KindContext<SchemaArrayField | ArrayField>, owner: ReactiveResource, data: unknown[]) {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n this[SOURCE] = data?.slice();\n const IS_EDITABLE = context.editable ?? false;\n this[Context] = context;\n const schema = context.store.schema as SchemaService;\n const cache = context.store.cache;\n const { field } = context;\n\n const signals = withSignalStore(this);\n let _SIGNAL: WarpDriveSignal = null as unknown as WarpDriveSignal;\n const boundFns = new Map<KeyType, ProxiedMethod>();\n this.identifier = context.resourceKey;\n this.path = context.path;\n this.owner = owner;\n let transaction = false;\n type StorageKlass = typeof WeakMap<object, MemoizedSchemaObject>;\n const KeyMode = (field as SchemaArrayField).options?.key ?? '@identity';\n // listener.\n const RefStorage: StorageKlass =\n KeyMode === '@identity'\n ? WeakMap\n : // CAUTION CAUTION CAUTION\n // this is a pile of lies\n // the Map is Map<string, WeakRef<ReactiveResource>>\n // but TS does not understand how to juggle modes like this\n // internal to a method like ours without us duplicating the code\n // into two separate methods.\n Map<object, MemoizedSchemaObject>;\n const ManagedRecordRefs = field.kind === 'schema-array' ? new RefStorage() : null;\n const extensions = context.legacy ? schema.CAUTION_MEGA_DANGER_ZONE_arrayExtensions(field) : null;\n const proxy = new Proxy(this[SOURCE], {\n get<R extends typeof Proxy<unknown[]>>(target: unknown[], prop: keyof R, receiver: R) {\n if (prop === ARRAY_SIGNAL) {\n return _SIGNAL;\n }\n if (prop === 'identifier') {\n return self.identifier;\n }\n if (prop === 'owner') {\n return self.owner;\n }\n if (prop === Context) {\n return self[Context];\n }\n\n const index = convertToInt(prop);\n if (_SIGNAL.isStale && (index !== null || SYNC_PROPS.has(prop) || isArrayGetter(prop))) {\n _SIGNAL.isStale = false;\n const newData = cache.getAttr(context.resourceKey, context.path);\n if (newData && newData !== self[SOURCE]) {\n self[SOURCE].length = 0;\n self[SOURCE].push(...(newData as ArrayValue));\n }\n }\n\n if (prop === 'length') {\n return (consumeInternalSignal(_SIGNAL), target.length);\n }\n if (prop === '[]') return (consumeInternalSignal(_SIGNAL), receiver);\n\n if (index !== null) {\n if (!transaction) {\n consumeInternalSignal(_SIGNAL);\n }\n const rawValue = target[index];\n\n if (field.kind === 'array') {\n if (field.type) {\n const transform = schema.transformation(field);\n return transform.hydrate(rawValue as Value, field.options ?? null, self.owner);\n }\n return rawValue;\n }\n\n /**\n * When the array is polymorphic, we need to determine the real type\n * in order to apply the correct identity as schema-object identity\n * is only required to be unique by type\n */\n let objectType: string;\n if (field.options?.polymorphic) {\n const typePath = (field.options.type as string) ?? 'type';\n // if we are polymorphic, then context.field.options.type will\n // either specify a path on the rawValue to use as the type, defaulting to \"type\" or\n // the special string \"@hash\" which tells us to treat field.type as a hashFn name with which\n // to calc the type.\n if (typePath === '@hash') {\n assert(`Expected the field to define a hashFn as its type`, field.type);\n const hashFn = schema.hashFn({ type: field.type });\n // TODO consider if there are better options and name args we could provide.\n objectType = hashFn(rawValue as object, null, null);\n } else {\n objectType = (rawValue as ObjectValue)[typePath] as string;\n assert(\n `Expected the type path for the field to be a value on the raw object`,\n typePath && objectType && typeof objectType === 'string'\n );\n }\n } else {\n assert(`A non-polymorphic SchemaArrayField must provide a SchemaObject type in its definition`, field.type);\n objectType = field.type;\n }\n\n /**\n * When KeyMode=@hash the ReactiveResource is keyed into\n * ManagedRecordRefs by the return value of @hash on the rawValue.\n *\n * This means that we could find a way to only recompute the identity\n * when ARRAY_SIGNAL is dirty if hash performance becomes a bottleneck.\n */\n let schemaObjectKeyValue: string | number | object;\n if (KeyMode === '@hash') {\n const hashField = schema.resource({ type: objectType! }).identity as HashField;\n const hashFn = schema.hashFn(hashField);\n schemaObjectKeyValue = hashFn(rawValue as object, hashField.options ?? null, hashField.name);\n } else {\n // if mode is not @identity or @index, then access the key path.\n // we should assert that `mode` is a string\n // it should read directly from the cache value for that field (e.g. no derivation, no transformation)\n // and, we likely should lookup the associated field and throw an error IF\n // the given field does not exist OR\n // the field is anything other than a GenericField or LegacyAttributeField.\n if (DEBUG) {\n const isPathKeyMode = KeyMode !== '@identity' && KeyMode !== '@index';\n if (isPathKeyMode) {\n assert('mode must be a string', typeof KeyMode === 'string' && KeyMode !== '');\n const modeField = schema.fields({ type: objectType! }).get(KeyMode);\n assert('field must exist in schema', modeField);\n assert(\n 'field must be a GenericField or LegacyAttributeField',\n modeField.kind === 'field' || modeField.kind === 'attribute'\n );\n }\n }\n schemaObjectKeyValue =\n KeyMode === '@identity'\n ? (rawValue as object)\n : KeyMode === '@index'\n ? index\n : ((rawValue as ObjectValue)[KeyMode] as string | number | object);\n }\n\n if (!schemaObjectKeyValue && schemaObjectKeyValue !== 0) {\n assert(`Unexpected out of bounds access on SchemaArray`);\n return undefined;\n }\n\n const recordRef = ManagedRecordRefs!.get(schemaObjectKeyValue as object);\n const record = recordRef?.value.deref();\n\n // confirm the type and key still match\n if (record && recordRef!.type === objectType && recordRef!.identity === schemaObjectKeyValue) {\n if (recordRef!.index !== index) {\n recordRef!.index = index;\n recordRef!.context.path[recordRef!.context.path.length - 1] = index as unknown as string;\n }\n return record;\n } else if (record) {\n // TODO schedule idle once we can\n void Promise.resolve().then(() => {\n record[Destroy]();\n });\n }\n\n const recordPath = context.path.slice();\n // this is a dirty lie since path is string[] but really we\n // should change the types for paths to `Array<string | number>`\n recordPath.push(index as unknown as string);\n\n const objectContext = {\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: recordPath,\n field: field,\n value: objectType,\n };\n const schemaObject = new ReactiveResource(objectContext);\n\n ManagedRecordRefs!.set(schemaObjectKeyValue as object, {\n type: objectType,\n identity: schemaObjectKeyValue,\n index,\n context: objectContext,\n value: new WeakRef(schemaObject),\n });\n\n return schemaObject;\n }\n\n if (isArrayGetter(prop)) {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n if (prop === 'forEach') {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n transaction = true;\n const result = safeForEach(receiver, target, context.store, arguments[0] as ForEachCB, arguments[1]);\n transaction = false;\n return result;\n };\n } else {\n fn = function () {\n consumeInternalSignal(_SIGNAL);\n // array functions must run through Reflect to work properly\n // binding via other means will not work.\n transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n transaction = false;\n return result;\n };\n }\n boundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (isArraySetter(prop)) {\n let fn = boundFns.get(prop);\n\n if (fn === undefined) {\n fn = function () {\n if (!IS_EDITABLE) {\n throw new Error(\n `Mutating this array via ${String(prop)} is not allowed because the ReactiveResource is not editable`\n );\n }\n consumeInternalSignal(_SIGNAL);\n transaction = true;\n const result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;\n transaction = false;\n return result;\n };\n boundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performArrayExtensionGet(\n receiver,\n extensions!,\n signals,\n prop,\n _SIGNAL,\n boundFns,\n (v: boolean) => void (transaction = v)\n );\n }\n\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop: KeyType, value: unknown, receiver: object) {\n if (!IS_EDITABLE) {\n let errorPath = context.resourceKey.type;\n if (context.path) {\n errorPath = context.path[context.path.length - 1];\n }\n assert(`Cannot set ${String(prop)} on ${errorPath} because the ReactiveResource is not editable`);\n return false;\n }\n if (prop === 'identifier') {\n self.identifier = value as ResourceKey;\n return true;\n }\n if (prop === 'owner') {\n self.owner = value as ReactiveResource;\n return true;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n const reflect = Reflect.set(target, prop, value, receiver);\n\n if (reflect) {\n if (!field.type) {\n cache.setAttr(context.resourceKey, context.path, self[SOURCE] as Value);\n _SIGNAL.isStale = true;\n return true;\n }\n\n let rawValue = self[SOURCE] as ArrayValue;\n if (field.kind !== 'schema-array') {\n const transform = schema.transformation(field);\n if (!transform) {\n throw new Error(\n `No '${field.type}' transform defined for use by ${context.resourceKey.type}.${String(prop)}`\n );\n }\n rawValue = (self[SOURCE] as ArrayValue).map((item) =>\n transform.serialize(item, field.options ?? null, self.owner)\n );\n }\n cache.setAttr(context.resourceKey, context.path, rawValue);\n _SIGNAL.isStale = true;\n }\n return reflect;\n },\n has(target, prop) {\n if (prop === 'identifier' || prop === 'owner' || prop === ARRAY_SIGNAL) {\n return true;\n }\n return Reflect.has(target, prop);\n },\n }) as ManagedArray;\n\n // we entangle the signal on the returned proxy since that is\n // the object that other code will be interfacing with.\n _SIGNAL = entangleSignal(signals, proxy, ARRAY_SIGNAL, undefined);\n\n return proxy;\n }\n}\n\n// this will error if someone tries to call\n// A(identifierArray) since it is not configurable\n// which is preferable to the `meta` override we used\n// before which required importing all of Ember\nconst desc = {\n enumerable: true,\n configurable: false,\n get: function () {\n // here to support computed chains\n // and {{#each}}\n if (DEPRECATE_COMPUTED_CHAINS) {\n return this;\n }\n },\n};\n// compat(desc);\nObject.defineProperty(ManagedArray.prototype, '[]', desc);\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ARRAY_SIGNAL, entangleSignal, peekInternalSignal } from '../../../signals/-private';\nimport type { ArrayValue, ObjectValue } from '../../../types/json/raw';\nimport type { ArrayField, SchemaArrayField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedArray } from '../fields/managed-array';\n\nexport function getArrayField(context: KindContext<ArrayField | SchemaArrayField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n // the thing we hand out needs to know its owner and path in a private manner\n // its \"address\" is the parent identifier (identifier) + field name (field.name)\n // in the nested object case field name here is the full dot path from root resource to this value\n // its \"key\" is the field on the parent record\n // its \"owner\" is the parent record\n const { record } = context;\n let managedArray = signal.value as ManagedArray | null;\n\n if (managedArray) {\n // if the signal is stale, we need to check the rawValue has not become\n // `null`.\n if (signal.isStale) {\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n const rawValue = cache.getAttr(resourceKey, path);\n // if the rawValue is null or the rawValue is undefined and the field has no defaultValue\n // we need to reset the managedArray to null\n if (rawValue === null || (!rawValue && typeof rawValue === 'undefined' && !field.options?.defaultValue)) {\n signal.value = null;\n // TODO once we fix schema-object GC we should run Destroy here on the managed array\n return null;\n }\n }\n return managedArray;\n } else {\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as unknown[];\n\n // we only apply the defaultValue if the rawValue is undefined, this allows\n // use of explicit null for the field.\n if (!rawValue && typeof rawValue === 'undefined' && field.options?.defaultValue) {\n rawValue = [];\n }\n\n if (!rawValue) {\n return null;\n }\n managedArray = new ManagedArray(context, record, rawValue);\n signal.value = managedArray;\n }\n return managedArray;\n}\n\nexport function setArrayField(context: KindContext<ArrayField>): boolean {\n const { field, record, value } = context;\n const { cache, schema } = context.store;\n const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1)!);\n const peeked = fieldSignal?.value as ManagedArray | undefined;\n\n const transform = field.type ? schema.transformation(field) : null;\n // prettier-ignore\n const rawValue = value === null ? null\n : field.type ? (value as ArrayValue).map((item) => transform!.serialize(item, (field.options as ObjectValue) ?? null, record))\n : (value as ArrayValue)?.slice();\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n if (peeked) {\n assert(`Expected the peekManagedArray for ${field.kind} to return a ManagedArray`, ARRAY_SIGNAL in peeked);\n const arrSignal = peeked[ARRAY_SIGNAL];\n arrSignal.isStale = true;\n // TODO run array destroy?\n }\n\n if (!Array.isArray(rawValue) && fieldSignal) {\n fieldSignal.value = null;\n }\n\n return true;\n}\n","import { entangleInitiallyStaleSignal } from '../../../signals/-private';\nimport type { Value } from '../../../types/json/raw';\nimport type { LegacyAttributeField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getAttributeField(context: KindContext<LegacyAttributeField>): unknown {\n entangleInitiallyStaleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { cache } = context.store;\n return context.editable\n ? cache.getAttr(context.resourceKey, context.path)\n : cache.getRemoteAttr(context.resourceKey, context.path);\n}\n\nexport function setAttributeField(context: KindContext<LegacyAttributeField>): boolean {\n context.store.cache.setAttr(context.resourceKey, context.path, context.value as Value);\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { CacheableFieldSchema, FieldSchema, HashField, IdentityField } from '../../../types/schema/fields.ts';\n\nconst InvalidKinds = ['alias', 'derived', '@local'] as const;\ntype InvalidKind = 'alias' | 'derived' | '@local';\n\nexport function isInvalidKind(kind: string): kind is InvalidKind {\n return InvalidKinds.includes(kind as InvalidKind);\n}\n\nexport function isNonIdentityCacheableField(\n field: FieldSchema | IdentityField | HashField\n): field is Exclude<CacheableFieldSchema, IdentityField> {\n return !isInvalidKind(field.kind) && field.kind !== '@id' && field.kind !== '@hash';\n}\n\nexport function getFieldCacheKeyStrict(field: CacheableFieldSchema): string {\n return field.sourceKey || field.name;\n}\n\nexport function getFieldCacheKey(field: FieldSchema | IdentityField | HashField): string | null {\n return 'sourceKey' in field && field.sourceKey ? field.sourceKey : field.name;\n}\n\nexport function assertIsCacheField(field: FieldSchema | IdentityField): asserts field is CacheableFieldSchema {\n assert(\n `The FieldSchema ${field.kind} is not a CacheField and cannot be used to retrieve cache data`,\n !isInvalidKind(field.kind)\n );\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { cacheKeyFor } from '../../..';\nimport { entangleSignal } from '../../../signals/-private';\nimport type { ResourceKey } from '../../../types';\nimport type { LegacyBelongsToField } from '../../../types/schema/fields';\nimport type { SingleResourceRelationship } from '../../../types/spec/json-api-raw';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key';\nimport type { ReactiveResource } from '../record';\nimport type { SchemaService } from '../schema';\n\nexport function getBelongsToField(context: KindContext<LegacyBelongsToField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { field, resourceKey, store } = context;\n const { schema, cache } = store;\n if (field.options.linksMode) {\n const rawValue = context.editable\n ? (cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field)) as SingleResourceRelationship)\n : (cache.getRemoteRelationship(resourceKey, getFieldCacheKeyStrict(field)) as SingleResourceRelationship);\n\n return rawValue.data ? store.peekRecord(rawValue.data) : null;\n }\n\n // FIXME move this to a \"LegacyMode\" make this part of \"PolarisMode\"\n assert(`Can only use belongsTo fields when the resource is in legacy mode`, context.legacy);\n return (schema as SchemaService)._kind('@legacy', 'belongsTo').get(store, context.record, resourceKey, field);\n}\n\nexport function setBelongsToField(context: KindContext<LegacyBelongsToField>): boolean {\n const { field, resourceKey, store } = context;\n const { schema, cache } = store;\n\n /**\n * We currently only allow editing sync belongsTo relationships\n * in PolarisMode\n */\n const isValidPolarisConfig = field.options.linksMode && !field.options.async;\n if (!context.legacy && isValidPolarisConfig) {\n const name = context.path.at(-1)!;\n cache.mutate(\n {\n op: 'replaceRelatedRecord',\n record: resourceKey,\n field: name,\n value: getResourceKey(context.value as ReactiveResource | null),\n },\n // @ts-expect-error\n true\n );\n return true;\n }\n\n assert(`Can only mutate belongsTo fields when the resource is in legacy mode`, context.legacy);\n (schema as SchemaService)\n ._kind('@legacy', 'belongsTo')\n .set(store, context.record, context.resourceKey, context.field, context.value);\n return true;\n}\n\nexport function getResourceKey(record: ReactiveResource | null): ResourceKey | null {\n if (!record) {\n return null;\n }\n\n return cacheKeyFor(record);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private';\nimport type { CollectionField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getCollectionField(context: KindContext<CollectionField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n assert(`Accessing collection fields is not yet implemented`);\n}\n\nexport function setCollectionField(context: KindContext<CollectionField>): boolean {\n assert(`Setting collection fields is not yet implemented`);\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { DerivedField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getDerivedField(context: KindContext<DerivedField>): unknown {\n const { schema } = context.store;\n return schema.derivation(context.field)(context.record, context.field.options ?? null, context.field.name);\n}\n\nexport function setDerivedField(context: KindContext<DerivedField>): boolean {\n assert(\n `ILLEGAL SET: Cannot set '${context.path.join('.')}' on '${context.resourceKey.type}' as ${context.field.kind} fields are not mutable`\n );\n return false;\n}\n","import { entangleInitiallyStaleSignal } from '../../../signals/-private';\nimport type { Value } from '../../../types/json/raw';\nimport type { GenericField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getGenericField(context: KindContext<GenericField>): unknown {\n const signal = entangleInitiallyStaleSignal(context.signals, context.record, context.path.at(-1)!, null);\n // FIXME we should be able to cache the computation here, but some tests fail.\n // if (!signal.isStale) {\n // return signal.value;\n // }\n signal.isStale = false;\n const { cache, schema } = context.store;\n const rawValue = context.editable\n ? cache.getAttr(context.resourceKey, context.path)\n : cache.getRemoteAttr(context.resourceKey, context.path);\n\n const { field } = context;\n if (!field.type) {\n // signal.value = rawValue;\n return rawValue;\n }\n\n const transform = schema.transformation(field);\n // signal.value = transform.hydrate(rawValue, field.options ?? null, context.record);\n // return signal.value;\n return transform.hydrate(rawValue, field.options ?? null, context.record);\n}\n\nexport function setGenericField(context: KindContext<GenericField>): boolean {\n const { cache, schema } = context.store;\n const { field } = context;\n\n if (!field.type) {\n cache.setAttr(context.resourceKey, context.path, context.value as Value);\n return true;\n }\n\n const transform = schema.transformation(field);\n const rawValue = transform.serialize(context.value, field.options ?? null, context.record);\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n return true;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../../index.ts';\nimport type { RelatedCollection as ManyArray } from '../../../store/-private.ts';\nimport { fastPush } from '../../../store/-private.ts';\nimport type { CollectionRelationship } from '../../../types/cache/relationship.ts';\nimport type { LocalRelationshipOperation } from '../../../types/graph.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { CacheOptions } from '../../../types/request.ts';\nimport { EnableHydration } from '../../../types/request.ts';\nimport type { CollectionResourceRelationship } from '../../../types/spec/json-api-raw.ts';\nimport type { ReactiveResource } from '../record.ts';\nimport { Context } from '../symbols.ts';\n\nexport interface FindHasManyOptions {\n reload?: boolean;\n backgroundReload?: boolean;\n}\n\nexport class ManyArrayManager {\n declare record: ReactiveResource;\n declare store: Store;\n declare identifier: ResourceKey;\n declare editable: boolean;\n\n constructor(record: ReactiveResource, editable: boolean) {\n const context = record[Context];\n this.record = record;\n this.store = context.store;\n this.identifier = context.resourceKey;\n this.editable = editable;\n }\n\n _syncArray(array: ManyArray): void {\n const method = this.editable ? 'getRelationship' : 'getRemoteRelationship';\n // FIXME field needs to use sourceKey\n const rawValue = this.store.cache[method](this.identifier, array.key) as CollectionRelationship;\n\n if (rawValue.meta) {\n array.meta = rawValue.meta;\n }\n\n if (rawValue.links) {\n array.links = rawValue.links;\n }\n\n const currentState = array[Context].source;\n\n // rawValue.data is undefined when the relationship has never received membership\n // data (e.g. a links-only payload) - there is nothing to sync in that case, and the\n // array must already be empty since it could only ever have been populated from data\n if (rawValue.data !== undefined && currentState !== rawValue.data) {\n // unlike in the normal RecordArray case, we don't need to divorce the reference\n // because we don't need to worry about associate/disassociate since the graph\n // takes care of that for us\n currentState.length = 0;\n fastPush(currentState, rawValue.data);\n }\n }\n\n reloadHasMany<T>(key: string, options?: FindHasManyOptions): Promise<ManyArray<T>> {\n // FIXME field needs to use sourceKey\n const field = this.store.schema.fields(this.identifier).get(key);\n assert(`Expected a hasMany field for ${key}`, field?.kind === 'hasMany');\n\n const cacheOptions = options ? extractCacheOptions(options) : { reload: true };\n cacheOptions.types = [field.type];\n\n const rawValue = this.store.cache.getRelationship(this.identifier, key) as CollectionRelationship;\n\n const req = {\n url: getRelatedLink(rawValue),\n op: 'findHasMany',\n method: 'GET' as const,\n records: rawValue.data as ResourceKey[],\n cacheOptions,\n options: {\n field,\n identifier: this.identifier,\n links: rawValue.links,\n meta: rawValue.meta,\n },\n [EnableHydration]: false,\n };\n\n return this.store.request(req) as unknown as Promise<ManyArray<T>>;\n }\n\n mutate(mutation: LocalRelationshipOperation): void {\n this.store.cache.mutate(mutation);\n }\n}\n\nfunction getRelatedLink(resource: CollectionResourceRelationship): string {\n const related = resource.links?.related;\n assert(`Expected a related link`, related);\n\n return typeof related === 'object' ? related.href : related;\n}\n\nfunction extractCacheOptions(options: FindHasManyOptions) {\n const cacheOptions: CacheOptions = {};\n if ('reload' in options) {\n cacheOptions.reload = options.reload;\n }\n if ('backgroundReload' in options) {\n cacheOptions.backgroundReload = options.backgroundReload;\n }\n return cacheOptions;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private.ts';\nimport type { RelatedCollection as ManyArray } from '../../../store/-private.ts';\nimport { createLegacyManyArray } from '../../../store/-private.ts';\nimport type { ResourceKey } from '../../../types/identifier.ts';\nimport type { LegacyHasManyField } from '../../../types/schema/fields.ts';\nimport type { CollectionResourceRelationship } from '../../../types/spec/json-api-raw.ts';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key.ts';\nimport { ManyArrayManager } from '../fields/many-array-manager.ts';\nimport type { SchemaService } from '../schema.ts';\n\nexport function getHasManyField(context: KindContext<LegacyHasManyField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { store, field } = context;\n if (field.options.linksMode) {\n const { record } = context;\n // the thing we hand out needs to know its owner and path in a private manner\n // its \"address\" is the parent identifier (identifier) + field name (field.name)\n // in the nested object case field name here is the full dot path from root resource to this value\n // its \"key\" is the field on the parent record\n // its \"owner\" is the parent record\n\n const cached = signal.value as ManyArray | undefined;\n if (cached) {\n return cached;\n }\n const { editable, resourceKey } = context;\n const { cache } = store;\n // the editable copy renders reconciled local state; the readonly copy\n // renders remote state (and re-pulls remote state when notified on the\n // 'remote' channel), mirroring ManyArrayManager._syncArray and\n // getBelongsToField.\n const rawValue = (\n editable\n ? cache.getRelationship(resourceKey, getFieldCacheKeyStrict(field))\n : cache.getRemoteRelationship(resourceKey, getFieldCacheKeyStrict(field))\n ) as CollectionResourceRelationship;\n if (!rawValue) {\n return null;\n }\n const managedArray = createLegacyManyArray({\n store,\n manager: new ManyArrayManager(record, editable),\n source: (rawValue.data?.slice() ?? []) as ResourceKey[],\n type: field.type,\n isLoaded: true,\n editable,\n isAsync: field.options.async ?? false,\n isPolymorphic: field.options.polymorphic ?? false,\n field,\n identifier: resourceKey,\n links: rawValue.links || null,\n meta: rawValue.meta || null,\n });\n signal.value = managedArray;\n return managedArray;\n }\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n return (store.schema as SchemaService)\n ._kind('@legacy', 'hasMany')\n .get(store, context.record, context.resourceKey, field);\n}\n\nexport function setHasManyField(context: KindContext<LegacyHasManyField>): boolean {\n const { store } = context;\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n assert(`You must pass an array of records to set a hasMany relationship`, Array.isArray(context.value));\n (store.schema as SchemaService)\n ._kind('@legacy', 'hasMany')\n .set(store, context.record, context.resourceKey, context.field, context.value);\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { HashField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getHashField(context: KindContext<HashField>): unknown {\n const { field, path, resourceKey } = context;\n const { schema, cache } = context.store;\n assert(`Cannot use a ${field.kind} directly on a resource.`, Array.isArray(path) && path.length > 1);\n const realPath = path.slice(0, -1);\n const rawData = context.editable ? cache.getAttr(resourceKey, realPath) : cache.getRemoteAttr(resourceKey, realPath);\n return schema.hashFn(field)(rawData as object, field.options ?? null, field.name ?? null);\n}\n\nexport function setHashField(context: KindContext<HashField>): boolean {\n assert(\n `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`\n );\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private.ts';\nimport type { IdentityField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\n\nexport function getIdentityField(context: KindContext<IdentityField>): unknown {\n entangleSignal(context.signals, context.record, '@identity', null);\n return context.resourceKey.id;\n}\n\nexport function setIdentityField(context: KindContext<IdentityField>): boolean {\n const { value, resourceKey, store } = context;\n assert(`Expected to receive a string id`, typeof value === 'string' && value.length);\n const normalizedId = String(value);\n const didChange = normalizedId !== resourceKey.id;\n assert(\n `Cannot set ${resourceKey.type} record's id to ${normalizedId}, because id is already ${resourceKey.id}`,\n !didChange || resourceKey.id === null\n );\n\n if (normalizedId !== null && didChange) {\n store._instanceCache.setRecordId(resourceKey, normalizedId);\n store.notifications.notify(resourceKey, 'identity', null);\n }\n return true;\n}\n","import { consumeInternalSignal, getOrCreateInternalSignal, notifyInternalSignal } from '../../../signals/-private';\nimport type { LocalField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\n\nexport function getLocalField(context: KindContext<LocalField>): unknown {\n const { field } = context;\n const signal = getOrCreateInternalSignal(\n context.signals,\n context.record,\n field.name,\n field.options?.defaultValue ?? null\n );\n consumeInternalSignal(signal);\n return signal.value;\n}\n\nexport function setLocalField(context: KindContext<LocalField>): boolean {\n const { value } = context;\n const signal = getOrCreateInternalSignal(context.signals, context.record, context.field.name, value);\n if (signal.value !== value) {\n signal.value = value;\n notifyInternalSignal(signal);\n }\n return true;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport {\n consumeInternalSignal,\n entangleSignal,\n notifyInternalSignal,\n OBJECT_SIGNAL,\n type WarpDriveSignal,\n withSignalStore,\n} from '../../../signals/-private.ts';\nimport { getOrSetGlobal } from '../../../types/-private.ts';\nimport type { ObjectValue, Value } from '../../../types/json/raw.ts';\nimport type { ObjectField, SchemaObjectField } from '../../../types/schema/fields.ts';\nimport type { KindContext } from '../default-mode.ts';\nimport type { ReactiveResource } from '../record.ts';\nimport type { SchemaService } from '../schema.ts';\nimport { Context, SOURCE } from '../symbols.ts';\nimport { isExtensionProp, performExtensionSet, performObjectExtensionGet } from './extension.ts';\n\nexport function notifyObject(obj: ManagedObject): void {\n notifyInternalSignal(obj[OBJECT_SIGNAL]);\n}\n\ntype ObjectSymbol = typeof OBJECT_SIGNAL | typeof SOURCE | typeof Context;\nconst ObjectSymbols = new Set<ObjectSymbol>([OBJECT_SIGNAL, Context, SOURCE]);\n\ntype KeyType = string | symbol | number;\n// const ignoredGlobalFields = new Set<string>(['setInterval', 'nodeType', 'nodeName', 'length', 'document', STRUCTURED]);\nexport interface ManagedObject {\n [SOURCE]: object;\n [Context]: KindContext<ObjectField>;\n [OBJECT_SIGNAL]: WarpDriveSignal;\n}\n\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ManagedObject {\n constructor(context: KindContext<ObjectField>) {\n const { field, path } = context;\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n this[SOURCE] = Object.assign({}, context.value);\n const signals = withSignalStore(this);\n const _SIGNAL = (this[OBJECT_SIGNAL] = entangleSignal(signals, this, OBJECT_SIGNAL, undefined));\n this[Context] = context;\n const identifier = context.resourceKey;\n const { cache, schema } = context.store;\n\n // prettier-ignore\n const extensions =\n !context.legacy ? null : (schema as SchemaService).CAUTION_MEGA_DANGER_ZONE_objectExtensions(field, null);\n\n const proxy = new Proxy(this[SOURCE], {\n ownKeys() {\n return Object.keys(self[SOURCE]);\n },\n\n has(target: unknown, prop: string | number | symbol) {\n return prop in self[SOURCE];\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return {\n writable: context.editable,\n enumerable: true,\n configurable: true,\n };\n },\n\n get<R extends typeof Proxy<object>>(target: object, prop: keyof R, receiver: R) {\n if (ObjectSymbols.has(prop as ObjectSymbol)) {\n return self[prop as keyof typeof target];\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => null;\n }\n if (prop === Symbol.toStringTag) {\n return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;\n }\n if (prop === 'constructor') {\n return Object;\n }\n if (prop === 'toString') {\n return function () {\n return `ManagedObject<${identifier.type}:${identifier.id} (${identifier.lid})>`;\n };\n }\n if (prop === 'toHTML') {\n return function () {\n return '<span>ManagedObject</span>';\n };\n }\n\n if (_SIGNAL.isStale) {\n _SIGNAL.isStale = false;\n let newData = cache.getAttr(identifier, path);\n if (newData && newData !== self[SOURCE]) {\n if (field.type) {\n const transform = schema.transformation(field);\n newData = transform.hydrate(\n newData,\n (field.options as ObjectValue) ?? null,\n context.record\n ) as ObjectValue;\n }\n self[SOURCE] = Object.assign({}, newData) as ObjectValue; // Add type assertion for newData\n }\n }\n\n // toJSON and extensions need to come after we update data if stale\n if (prop === 'toJSON') {\n return function () {\n return structuredClone(self[SOURCE]);\n };\n }\n\n // we always defer to data before extensions\n if (prop in self[SOURCE]) {\n consumeInternalSignal(_SIGNAL);\n\n return (self[SOURCE] as R)[prop];\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performObjectExtensionGet(receiver, extensions!, signals, prop);\n }\n\n return Reflect.get(target, prop, receiver) as R;\n },\n\n set(target: object, prop: KeyType, value: unknown, receiver: object) {\n assert(`Cannot set read-only property '${String(prop)}' on ManagedObject`, context.editable);\n // `assert` is stripped in production, so without this the write below would silently\n // succeed against the underlying writable `target` instead of being rejected.\n if (!context.editable) {\n return false;\n }\n\n // since objects function as dictionaries, we can't defer to schema/data before extensions\n // unless the prop is in the existing data.\n if (!(prop in self[SOURCE]) && isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n const reflect = Reflect.set(target, prop, value, receiver);\n if (!reflect) {\n return false;\n }\n\n if (!field.type) {\n cache.setAttr(identifier, path, self[SOURCE] as Value);\n } else {\n const transform = schema.transformation(field);\n const val = transform.serialize(self[SOURCE], (field.options as ObjectValue) ?? null, context.record);\n cache.setAttr(identifier, path, val);\n }\n\n _SIGNAL.isStale = true;\n return true;\n },\n }) as ManagedObject;\n\n return proxy;\n }\n}\n\nexport const ManagedObjectMap: Map<ReactiveResource, Map<string, ManagedObject | ReactiveResource>> = getOrSetGlobal(\n 'ManagedObjectMap',\n new Map<ReactiveResource, Map<string, ManagedObject | ReactiveResource>>()\n);\n\nexport function peekManagedObject(record: ReactiveResource, field: ObjectField): ManagedObject | undefined;\nexport function peekManagedObject(record: ReactiveResource, field: SchemaObjectField): ReactiveResource | undefined;\nexport function peekManagedObject(\n record: ReactiveResource,\n field: ObjectField | SchemaObjectField\n): ManagedObject | ReactiveResource | undefined {\n const managedObjectMapForRecord = ManagedObjectMap.get(record);\n if (managedObjectMapForRecord) {\n return managedObjectMapForRecord.get(field.name);\n }\n}\n","import { entangleSignal, OBJECT_SIGNAL } from '../../../signals/-private';\nimport type { ObjectValue, Value } from '../../../types/json/raw';\nimport type { ObjectField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedObject, ManagedObjectMap, peekManagedObject } from '../fields/managed-object';\n\nexport function getObjectField(context: KindContext<ObjectField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { record, field } = context;\n const managedObjectMapForRecord = ManagedObjectMap.get(record);\n let managedObject;\n if (managedObjectMapForRecord) {\n managedObject = managedObjectMapForRecord.get(field.name);\n }\n if (managedObject) {\n return managedObject;\n } else {\n const { store, resourceKey, path } = context;\n const { cache, schema } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as object;\n if (!rawValue) {\n return null;\n }\n if (field.type) {\n const transform = schema.transformation(field);\n rawValue = transform.hydrate(rawValue as ObjectValue, (field.options as ObjectValue) ?? null, record) as object;\n }\n\n managedObject = new ManagedObject({\n store,\n resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path,\n field,\n record,\n signals: context.signals,\n value: rawValue,\n });\n\n if (!managedObjectMapForRecord) {\n ManagedObjectMap.set(record, new Map([[field.name, managedObject]]));\n } else {\n managedObjectMapForRecord.set(field.name, managedObject);\n }\n }\n return managedObject;\n}\n\nexport function setObjectField(context: KindContext<ObjectField>): boolean {\n const { field, value, record } = context;\n const { cache, schema } = context.store;\n\n if (!field.type) {\n let newValue = value as Value;\n if (value !== null) {\n newValue = { ...(value as ObjectValue) };\n } else {\n ManagedObjectMap.delete(record);\n }\n\n cache.setAttr(context.resourceKey, context.path, newValue);\n\n const peeked = peekManagedObject(record, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n objSignal.isStale = true;\n }\n return true;\n }\n\n const transform = schema.transformation(field);\n const rawValue = transform.serialize({ ...(value as ObjectValue) }, (field.options as ObjectValue) ?? null, record);\n\n cache.setAttr(context.resourceKey, context.path, rawValue);\n const peeked = peekManagedObject(record, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n objSignal.isStale = true;\n }\n return true;\n}\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/build-config/macros';\n\nimport type { Future } from '../../../request';\nimport { defineSignal, entangleSignal } from '../../../signals/-private';\nimport type { StoreRequestInput } from '../../../store/-private';\nimport type { ResourceField } from '../../../types/schema/fields';\nimport type { Link, Links, SingleResourceRelationship } from '../../../types/spec/json-api-raw';\nimport type { KindContext } from '../default-mode';\nimport { getFieldCacheKeyStrict } from '../fields/get-field-key';\nimport type { ReactiveResource } from '../record';\nimport { Context } from '../symbols';\n\ninterface ResourceRelationship<T extends ReactiveResource = ReactiveResource> {\n lid: string;\n name: string;\n [Context]: KindContext<ResourceField>;\n\n data: T | null;\n links: Links;\n meta: Record<string, unknown>;\n}\n\n// TODO probably this should just be a Document\n// but its separate until we work out the lid situation\nclass ResourceRelationship<T extends ReactiveResource = ReactiveResource> {\n constructor(context: KindContext<ResourceField>) {\n const { store, resourceKey } = context;\n const { cache } = store;\n const name = getFieldCacheKeyStrict(context.field);\n const rawValue = (\n context.editable ? cache.getRelationship(resourceKey, name) : cache.getRemoteRelationship(resourceKey, name)\n ) as SingleResourceRelationship;\n\n // TODO setup true lids for relationship documents\n // @ts-expect-error we need to give relationship documents a lid\n // oxlint-disable-next-line typescript/no-unsafe-assignment\n this.lid = rawValue.lid ?? rawValue.links?.self ?? `relationship:${resourceKey.lid}.${name}`;\n this.data = rawValue.data ? (store.peekRecord(rawValue.data) as T) : null;\n this.name = name;\n\n if (DEBUG) {\n this.links = Object.freeze(Object.assign({}, rawValue.links));\n this.meta = Object.freeze(Object.assign({}, rawValue.meta));\n } else {\n this.links = rawValue.links ?? {};\n this.meta = rawValue.meta ?? {};\n }\n\n this[Context] = context;\n }\n\n fetch(options?: StoreRequestInput<T>): Future<T> {\n const url = options?.url ?? getHref(this.links.related) ?? getHref(this.links.self) ?? null;\n\n if (!url) {\n throw new Error(\n `Cannot ${options?.method ?? 'fetch'} ${this[Context].resourceKey.type}.${String(\n this.name\n )} because it has no related link`\n );\n }\n const request = Object.assign(\n {\n url,\n method: 'GET',\n },\n options\n );\n\n return this[Context].store.request<T>(request);\n }\n}\n\ndefineSignal(ResourceRelationship.prototype, 'data', null);\ndefineSignal(ResourceRelationship.prototype, 'links', null);\ndefineSignal(ResourceRelationship.prototype, 'meta', null);\n\nfunction getHref(link?: Link | null): string | null {\n if (!link) {\n return null;\n }\n if (typeof link === 'string') {\n return link;\n }\n return link.href;\n}\n\nexport function getResourceField(context: KindContext<ResourceField>): unknown {\n entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n return new ResourceRelationship(context);\n}\n\nexport function setResourceField(context: KindContext<ResourceField>): boolean {\n assert(`setting resource relationships is not yet supported`);\n return false;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { ARRAY_SIGNAL, peekInternalSignal } from '../../../signals/-private';\nimport type { ArrayValue } from '../../../types/json/raw';\nimport type { SchemaArrayField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport type { ManagedArray } from '../fields/managed-array.ts';\n\nexport { getArrayField as getSchemaArrayField } from './array-field';\n\nexport function setSchemaArrayField(context: KindContext<SchemaArrayField>): boolean {\n const arrayValue = context.value === null ? null : (context.value as ArrayValue)?.slice();\n const fieldSignal = peekInternalSignal(context.signals, context.path.at(-1)!);\n const peeked = fieldSignal?.value as ManagedArray | undefined | null;\n\n context.store.cache.setAttr(context.resourceKey, context.path, arrayValue);\n if (peeked) {\n assert(`Expected the peekManagedArray for ${context.field.kind} to return a ManagedArray`, ARRAY_SIGNAL in peeked);\n const arrSignal = peeked[ARRAY_SIGNAL];\n arrSignal.isStale = true;\n\n if (!Array.isArray(arrayValue)) {\n fieldSignal!.value = null;\n }\n }\n\n return true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport { entangleSignal } from '../../../signals/-private';\nimport type { ObjectValue, Value } from '../../../types/json/raw';\nimport type { ObjectSchema, SchemaObjectField } from '../../../types/schema/fields';\nimport type { KindContext } from '../default-mode';\nimport { ManagedObjectMap } from '../fields/managed-object';\nimport { ReactiveResource } from '../record';\nimport { Destroy } from '../symbols';\n\ntype MemoizedSchemaObject = {\n type: string;\n identity: string | object;\n value: ReactiveResource;\n};\n\nexport function getSchemaObjectField(context: KindContext<SchemaObjectField>): unknown {\n const signal = entangleSignal(context.signals, context.record, context.path.at(-1)!, null);\n const { store, resourceKey, path, field } = context;\n const { cache } = store;\n let rawValue = (\n context.editable ? cache.getAttr(resourceKey, path) : cache.getRemoteAttr(resourceKey, path)\n ) as object;\n\n if (!rawValue && !field.options?.polymorphic && field.options?.defaultValue) {\n rawValue = {};\n }\n\n if (!rawValue) {\n if (signal.value) {\n const value = signal.value as MemoizedSchemaObject;\n // TODO if we had idle scheduling this should be done there.\n void Promise.resolve().then(() => {\n value.value[Destroy]();\n });\n signal.value = null;\n }\n return null;\n }\n\n const { schema } = store;\n let objectType: string;\n\n if (field.options?.polymorphic) {\n const typePath = field.options.type ?? 'type';\n // if we are polymorphic, then context.field.options.type will\n // either specify a path on the rawValue to use as the type, defaulting to \"type\" or\n // the special string \"@hash\" which tells us to treat field.type as a hashFn name with which\n // to calc the type.\n if (typePath === '@hash') {\n assert(`Expected the field to define a hashFn as its type`, field.type);\n const hashFn = schema.hashFn({ type: field.type });\n // TODO consider if there are better options and name args we could provide.\n objectType = hashFn(rawValue, null, null);\n } else {\n objectType = (rawValue as ObjectValue)[typePath] as string;\n assert(\n `Expected the type path for the field to be a value on the raw object`,\n typePath && objectType && typeof objectType === 'string'\n );\n }\n } else {\n assert(`A non-polymorphic SchemaObjectField must provide a SchemaObject type in its definition`, field.type);\n objectType = field.type;\n }\n\n const hashField = (schema.resource({ type: objectType }) as ObjectSchema).identity;\n const identity = hashField\n ? schema.hashFn(hashField)(rawValue, hashField.options ?? null, hashField.name)\n : field.name;\n\n const cachedSchemaObject = signal.value as MemoizedSchemaObject | null;\n if (cachedSchemaObject) {\n if (cachedSchemaObject.type === objectType && cachedSchemaObject.identity === identity) {\n return cachedSchemaObject.value;\n } else {\n // TODO if we had idle scheduling this should be done there.\n void Promise.resolve().then(() => {\n cachedSchemaObject.value[Destroy]();\n });\n }\n }\n\n const schemaObject = new ReactiveResource({\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: context.path,\n field: context.field,\n value: objectType,\n });\n\n signal.value = {\n type: objectType,\n identity: identity,\n value: schemaObject,\n };\n return schemaObject;\n}\n\nexport function setSchemaObjectField(context: KindContext<SchemaObjectField>): boolean {\n const { store, value } = context;\n let newValue = value as Value;\n if (value !== null) {\n assert(`Expected value to be an object`, typeof value === 'object');\n newValue = { ...(value as ObjectValue) };\n // FIXME the case of field.type to string here is likely incorrect\n const schemaFields = store.schema.fields({ type: context.field.type as string });\n for (const key of Object.keys(newValue)) {\n if (!schemaFields.has(key)) {\n assert(`Field ${key} does not exist on schema object ${context.field.type}`);\n return false;\n }\n }\n } else {\n ManagedObjectMap.delete(context.record);\n }\n store.cache.setAttr(context.resourceKey, context.path, newValue);\n // const peeked = peekManagedObject(self, field);\n // if (peeked) {\n // const objSignal = peeked[OBJECT_SIGNAL];\n // objSignal.isStale = true;\n // }\n return true;\n}\n","import type { SignalStore } from '../../signals/-private.ts';\nimport type { Store } from '../../store/-private.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport type {\n FieldSchema,\n HashField,\n IdentityField,\n SchemaArrayField,\n SchemaObjectField,\n} from '../../types/schema/fields.ts';\nimport { getAliasField, setAliasField } from './kind/alias-field.ts';\nimport { getArrayField, setArrayField } from './kind/array-field.ts';\nimport { getAttributeField, setAttributeField } from './kind/attribute-field.ts';\nimport { getBelongsToField, setBelongsToField } from './kind/belongs-to-field.ts';\nimport { getCollectionField, setCollectionField } from './kind/collection-field.ts';\nimport { getDerivedField, setDerivedField } from './kind/derived-field.ts';\nimport { getGenericField, setGenericField } from './kind/generic-field.ts';\nimport { getHasManyField, setHasManyField } from './kind/has-many-field.ts';\nimport { getHashField, setHashField } from './kind/hash-field.ts';\nimport { getIdentityField, setIdentityField } from './kind/identity-field.ts';\nimport { getLocalField, setLocalField } from './kind/local-field.ts';\nimport { getObjectField, setObjectField } from './kind/object-field.ts';\nimport { getResourceField, setResourceField } from './kind/resource-field.ts';\nimport { getSchemaArrayField, setSchemaArrayField } from './kind/schema-array-field.ts';\nimport { getSchemaObjectField, setSchemaObjectField } from './kind/schema-object-field.ts';\nimport type { ReactiveResource } from './record.ts';\n\nexport type PathLike = string | symbol | Array<string | symbol>;\n\nexport type ModeName = 'polaris' | 'legacy';\nexport interface ModeInfo {\n name: ModeName;\n legacy: boolean;\n editable: boolean;\n}\n\nexport interface BaseContext {\n /**\n * The {@link Store} instance that owns\n * the reactive context we are within.\n */\n store: Store;\n /**\n * The {@link ResourceKey} of the resource that\n * the reactive context we are within is for.\n */\n resourceKey: ResourceKey;\n /**\n * The name of the {@link ModeName | mode} that the\n * reactive context we are within is operating in.\n */\n modeName: ModeName;\n /**\n * Whether we are in legacy {@link ModeName | mode}\n * or not.\n */\n legacy: boolean;\n /**\n * Whether the ReactiveResource instance we are operating\n * in is currently editable or not. This should be true if the\n * record is currently checked out for editing or is in legacy mode\n * and false if the record is currently in a read-only state.\n */\n editable: boolean;\n}\n\nexport interface ResourceContext extends BaseContext {\n path: null;\n field: null;\n value: null;\n}\nexport interface ObjectContext extends BaseContext {\n path: string[];\n field: SchemaObjectField | SchemaArrayField;\n value: string;\n}\n\n/**\n * A ReactiveResource context object passed to\n * the get/set functions of a field kind implementation.\n *\n * This provides all the necessary information for\n * the field kind to perform its operations.\n */\nexport interface KindContext<T extends FieldSchema | IdentityField | HashField> extends BaseContext {\n /**\n * The \"cache\" path to the field within the resource.\n *\n * This is the path that should be used to access the\n * field's value in the cache.\n *\n * It differs from the \"ui path\" in that it will be\n * both unaliased and account for source keys.\n */\n path: string[];\n /**\n * The raw schema field definition\n */\n field: T;\n /**\n * The value being set in a set operation. This will be null in a get operation.\n */\n value: unknown;\n /**\n * The object (a ReactiveResource) that the field is being directly accessed on.\n * This is not necessarily the same as the instance that {@link BaseContext.resourceKey | resourceKey}\n * points to, as the field being accessed may be on an embedded schema-object\n * or similar.\n */\n record: ReactiveResource;\n /**\n * The signals object for the record, used to entangle signals for reactivity.\n */\n signals: SignalStore;\n}\n\nexport interface KindImpl<T extends FieldSchema | IdentityField | HashField> {\n /**\n * A function which produces the value for the field when invoked.\n */\n get: (context: KindContext<T>) => unknown;\n /**\n * A function which updates the value for the field when invoked.\n *\n * This will never be invoked when the record is in a non-editable mode.\n *\n * This should assert in dev and return false if mutation is not allowed.\n */\n set: (context: KindContext<T>) => boolean;\n /**\n * Whether this field is ever mutable (writable). This should be\n * if there is ever a scenario in which the field can be written\n * and false only if the field can never be written to.\n */\n mutable: boolean;\n /**\n * Whether this field's of this kind should be included in the\n * enumerated (iterable) keys of the record/object instance.\n *\n * This should generally be true except for fields that are not\n * producing a value backed by the cache. For instance, locals\n * should not be enumerable, as their value is not tied to the\n * cache at all.\n */\n enumerable: boolean;\n /**\n *\n */\n serializable: boolean;\n}\n\ntype Mode = {\n [Field in FieldSchema | IdentityField | HashField as Field['kind']]: KindImpl<Field>;\n};\n\nexport const DefaultMode: Mode = {\n '@hash': {\n get: getHashField,\n set: setHashField,\n mutable: false,\n enumerable: false,\n serializable: false,\n },\n '@id': {\n get: getIdentityField,\n set: setIdentityField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n '@local': {\n get: getLocalField,\n set: setLocalField,\n mutable: true,\n enumerable: false,\n serializable: false,\n },\n alias: {\n get: getAliasField,\n set: setAliasField,\n mutable: true,\n enumerable: true,\n serializable: false,\n },\n array: {\n get: getArrayField,\n set: setArrayField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n attribute: {\n get: getAttributeField,\n set: setAttributeField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n belongsTo: {\n get: getBelongsToField,\n set: setBelongsToField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n collection: {\n get: getCollectionField,\n set: setCollectionField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n derived: {\n get: getDerivedField,\n set: setDerivedField,\n mutable: true,\n enumerable: true,\n serializable: false,\n },\n field: {\n get: getGenericField,\n set: setGenericField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n hasMany: {\n get: getHasManyField,\n set: setHasManyField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n object: {\n get: getObjectField,\n set: setObjectField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n resource: {\n get: getResourceField,\n set: setResourceField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n 'schema-array': {\n get: getSchemaArrayField,\n set: setSchemaArrayField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n 'schema-object': {\n get: getSchemaObjectField,\n set: setSchemaObjectField,\n mutable: true,\n enumerable: true,\n serializable: true,\n },\n};\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { NotificationType } from '../../index.ts';\nimport {\n ARRAY_SIGNAL,\n entangleSignal,\n notifyInternalSignal,\n OBJECT_SIGNAL,\n Signals,\n withSignalStore,\n} from '../../signals/-private.ts';\nimport type { LegacyManyArray, Store } from '../../store/-private.ts';\nimport { recordIdentifierFor, setRecordIdentifier } from '../../store/-private.ts';\nimport { removeRecordIdentifier } from '../../store/-private/caches/instance-cache.ts';\nimport type { ResourceKey } from '../../types/identifier.ts';\nimport { STRUCTURED } from '../../types/request.ts';\nimport type { FieldSchema, GenericField, IdentityField } from '../../types/schema/fields.ts';\nimport { RecordStore } from '../../types/symbols.ts';\nimport type { ObjectContext, ResourceContext } from './default-mode.ts';\nimport { DefaultMode } from './default-mode.ts';\nimport type { ProxiedMethod } from './fields/extension.ts';\nimport { isExtensionProp, performExtensionSet, performObjectExtensionGet } from './fields/extension.ts';\nimport { getFieldCacheKey } from './fields/get-field-key.ts';\nimport type { ManagedArray } from './fields/managed-array.ts';\nimport { peekManagedObject } from './fields/managed-object.ts';\nimport type { SchemaService } from './schema.ts';\nimport { Checkout, Commit, Context, Destroy } from './symbols.ts';\n\nconst IgnoredGlobalFields = new Set<string>(['length', 'nodeType', 'then', 'setInterval', 'document', STRUCTURED]);\nconst symbolList = [Context, Destroy, RecordStore, Checkout, Commit];\nconst RecordSymbols = new Set(symbolList);\n\ntype RecordSymbol = (typeof symbolList)[number];\n\nfunction isPathMatch(a: string[], b: string[]) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction isNonEnumerableProp(prop: string | number | symbol) {\n return (\n prop === 'constructor' ||\n prop === 'prototype' ||\n prop === '__proto__' ||\n prop === 'toString' ||\n prop === 'toJSON' ||\n prop === 'toHTML' ||\n typeof prop === 'symbol'\n );\n}\n\nconst Editables = new Map<ReactiveResource, ReactiveResource>();\n\nexport interface ReactiveResource {\n /** @internal */\n [Symbol.toStringTag]: `ReactiveResource<${string}>`;\n\n /** @internal */\n [Context]: ObjectContext | ResourceContext;\n\n /** @internal */\n [RecordStore]: Store;\n\n /** @internal */\n ___notifications: object;\n\n /** @internal */\n [Destroy](): void;\n\n /** @internal */\n [Commit](): Promise<void>;\n\n /**\n * Create an editable copy of the record\n *\n * ReactiveResource instances are not editable by default. This method creates an editable copy of the record. To use,\n * import the `Checkout` symbol from `@warp-drive/core/reactive` and call it on the record.\n *\n * ```ts\n * import { Checkout } from '@warp-drive/core/reactive';\n *\n * const record = store.peekRecord('user', '1');\n * const editableRecord = await record[Checkout]();\n * ```\n *\n * @returns a promise that resolves to the editable record\n * @throws if the record is already editable or if the record is embedded\n * @private\n */\n [Checkout]<T>(): Promise<T>;\n}\n\n/**\n * @private\n */\nexport interface PrivateReactiveResource extends ReactiveResource {\n /**\n * @private\n */\n [Context]: ObjectContext | ResourceContext;\n}\n\n/**\n * A class that uses a the ResourceSchema for a ResourceType\n * and a ResourceKey to transform data from the cache into a rich, reactive\n * object.\n *\n * This class is not directly instantiable. To use it, you should\n * configure the store's `instantiateRecord` and `teardownRecord` hooks\n * with the matching hooks provided by this package.\n *\n * @hideconstructor\n * @public\n */\n// oxlint-disable-next-line typescript/no-extraneous-class\nexport class ReactiveResource {\n constructor(context: ResourceContext | ObjectContext) {\n const resourceKey = context.resourceKey;\n const isEmbedded = context.path !== null;\n const schema = context.store.schema as unknown as SchemaService;\n const objectType = isEmbedded ? context.value : resourceKey.type;\n const ResourceSchema = schema.resource(isEmbedded ? { type: objectType } : resourceKey);\n const identityField = ResourceSchema.identity;\n const BoundFns = new Map<string | symbol, ProxiedMethod>();\n\n // prettier-ignore\n const extensions =\n !context.legacy ? null\n : isEmbedded ? schema.CAUTION_MEGA_DANGER_ZONE_objectExtensions(context.field, objectType)\n : schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(resourceKey);\n\n this[Context] = context;\n this[RecordStore] = context.store;\n\n const fields = isEmbedded ? schema.fields({ type: objectType }) : schema.fields(resourceKey);\n const method = typeof schema.cacheFields === 'function' ? 'cacheFields' : 'fields';\n const cacheFields = isEmbedded ? schema[method]({ type: objectType }) : schema[method](resourceKey);\n\n const signals = withSignalStore(this);\n this.___notifications = context.store.notifications.subscribe(\n resourceKey,\n (_: ResourceKey, type: NotificationType, key?: string | string[]) => {\n switch (type) {\n case 'identity': {\n if (isEmbedded || !identityField) return; // base paths never apply to embedded records\n\n if (identityField.name && identityField.kind === '@id') {\n const signal = signals.get('@identity');\n if (signal) {\n notifyInternalSignal(signal);\n }\n }\n break;\n }\n case 'attributes':\n if (key) {\n if (Array.isArray(key)) {\n if (context.path === null) return; // deep paths will be handled by embedded records\n // TODO we should have the notification manager\n // ensure it is safe for each callback to mutate this array\n if (isPathMatch(context.path, key)) {\n // handle the notification\n // TODO we should likely handle this notification here\n // also we should add a LOGGING flag\n // oxlint-disable-next-line no-console\n console.warn(`Notification unhandled for ${key.join(',')} on ${resourceKey.type}`, proxy);\n return;\n }\n\n // TODO we should add a LOGGING flag\n // console.log(`Deep notification skipped for ${key.join('.')} on ${identifier.type}`, proxy);\n // deep notify the key path\n } else {\n if (isEmbedded) return; // base paths never apply to embedded records\n\n // TODO determine what LOGGING flag to wrap this in if any\n // console.log(`Notification for ${key} on ${identifier.type}`, proxy);\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n const field = cacheFields.get(key);\n if (field?.kind === 'array' || field?.kind === 'schema-array') {\n const peeked = signal?.value as ManagedArray | undefined;\n if (peeked) {\n assert(\n `Expected the peekManagedArray for ${field.kind} to return a ManagedArray`,\n ARRAY_SIGNAL in peeked\n );\n const arrSignal = peeked[ARRAY_SIGNAL];\n notifyInternalSignal(arrSignal);\n }\n }\n if (field?.kind === 'object') {\n const peeked = peekManagedObject(proxy, field);\n if (peeked) {\n const objSignal = peeked[OBJECT_SIGNAL];\n notifyInternalSignal(objSignal);\n }\n }\n }\n }\n break;\n case 'relationships':\n if (key) {\n if (Array.isArray(key)) {\n // FIXME\n } else {\n if (isEmbedded) return; // base paths never apply to embedded records\n\n const field = cacheFields.get(key);\n assert(`Expected relationship ${key} to be the name of a field`, field);\n if (field.kind === 'belongsTo') {\n // TODO determine what LOGGING flag to wrap this in if any\n // console.log(`Notification for ${key} on ${identifier.type}`, proxy);\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n // FIXME\n } else if (field.kind === 'resource') {\n // FIXME\n } else if (field.kind === 'hasMany') {\n if (field.options.linksMode) {\n const signal = signals.get(key);\n if (signal) {\n const peeked = signal.value as LegacyManyArray | undefined;\n if (peeked) {\n notifyInternalSignal(peeked[Context].signal);\n }\n }\n return;\n }\n\n assert(`Can only use hasMany fields when the resource is in legacy mode`, context.legacy);\n\n if (schema._kind('@legacy', 'hasMany').notify(context.store, proxy, resourceKey, field)) {\n assert(`Expected options to exist on relationship meta`, field.options);\n assert(`Expected async to exist on relationship meta options`, 'async' in field.options);\n if (field.options.async) {\n const signal = signals.get(key);\n if (signal) {\n notifyInternalSignal(signal);\n }\n }\n }\n } else if (field.kind === 'collection') {\n // FIXME\n }\n }\n }\n\n break;\n }\n },\n // Each copy subscribes to the channel of the projection it renders and\n // re-pulls that projection when notified. PolarisMode's default immutable\n // instance shows only remote state, so it subscribes 'remote' and is not\n // woken for purely-local changes it can't see. Legacy-mode schemas and any\n // editable instance (including a checked-out PolarisMode copy) show a\n // reconciled local view and so subscribe 'local' (the same as omitting the\n // channel) and are not woken for purely-remote changes (e.g. a push that\n // merely confirms a committed local mutation) that leave their view as-is.\n context.legacy || context.editable ? 'local' : 'remote'\n );\n\n const proxy = new Proxy(this, {\n ownKeys() {\n const identityKey = identityField?.name;\n const keys = Array.from(fields.keys());\n if (identityKey) {\n keys.unshift(identityKey);\n }\n return keys;\n },\n\n has(target: ReactiveResource, prop: string | number | symbol) {\n if (prop === Destroy || prop === Checkout) {\n return true;\n }\n if (prop === identityField?.name) {\n return true;\n }\n return fields.has(prop as string);\n },\n\n getOwnPropertyDescriptor(target, prop) {\n const schemaForField = prop === identityField?.name ? identityField : fields.get(prop as string)!;\n assert(`No field named ${String(prop)} on ${resourceKey.type}`, schemaForField);\n\n if (isNonEnumerableProp(prop)) {\n return {\n writable: false,\n enumerable: false,\n configurable: true,\n };\n }\n\n switch (schemaForField.kind) {\n case 'derived':\n return {\n writable: false,\n enumerable: true,\n configurable: true,\n };\n case '@id':\n return {\n writable: resourceKey.id === null,\n enumerable: true,\n configurable: true,\n };\n case '@hash':\n return schemaForField.name\n ? {\n writable: false,\n enumerable: true,\n configurable: true,\n }\n : {\n writable: false,\n enumerable: false,\n configurable: false,\n };\n case '@local':\n case 'field':\n case 'attribute':\n case 'resource':\n case 'alias':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n case 'schema-array':\n case 'array':\n case 'schema-object':\n case 'object':\n return {\n writable: context.editable,\n enumerable: true,\n configurable: true,\n };\n default:\n return {\n writable: false,\n enumerable: false,\n configurable: false,\n };\n }\n },\n\n get(target: ReactiveResource, prop: string | number | symbol, receiver: typeof Proxy<ReactiveResource>) {\n if (RecordSymbols.has(prop as RecordSymbol)) {\n if (prop === Destroy) {\n return () => _DESTROY(receiver as unknown as ReactiveResource);\n }\n if (prop === Checkout) {\n return () => Promise.resolve(_CHECKOUT(receiver as unknown as ReactiveResource));\n }\n if (prop === Commit) {\n return () => Promise.resolve(_COMMIT(receiver as unknown as ReactiveResource));\n }\n // this Proxy get trap must return raw property values, including methods, unbound\n // oxlint-disable-next-line typescript/unbound-method\n return target[prop as keyof ReactiveResource];\n }\n if (prop === Signals) {\n return signals;\n }\n\n // TODO make this a symbol\n if (prop === '___notifications') {\n return target.___notifications;\n }\n\n // ReactiveResource reserves use of keys that begin with these characters\n // for its own usage.\n // _, @, $, *\n\n const maybeField = prop === identityField?.name ? identityField : fields.get(prop as string);\n if (!maybeField) {\n if (IgnoredGlobalFields.has(prop as string)) {\n return undefined;\n }\n\n /////////////////////////////////////////////////////////////\n //// Note these bound function behaviors are essentially ////\n //// built-in but overrideable derivations. ////\n //// ////\n //// The bar for this has to be \"basic expectations of ////\n /// an object\" – very, very high ////\n /////////////////////////////////////////////////////////////\n\n if (prop === Symbol.toStringTag || prop === 'toString') {\n let fn = BoundFns.get('toString');\n if (!fn) {\n fn = function () {\n entangleSignal(signals, receiver, '@identity', null);\n return `Record<${resourceKey.type}:${resourceKey.id} (${resourceKey.lid})>`;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === 'toHTML') {\n let fn = BoundFns.get('toHTML');\n if (!fn) {\n fn = function () {\n entangleSignal(signals, receiver, '@identity', null);\n return `<span>Record<${resourceKey.type}:${resourceKey.id} (${resourceKey.lid})></span>`;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === 'toJSON') {\n let fn = BoundFns.get('toJSON');\n if (!fn) {\n fn = function () {\n const json: Record<string, unknown> = {};\n for (const key in receiver) {\n // serializing arbitrary property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n json[key] = receiver[key as keyof typeof receiver];\n }\n\n return json;\n };\n BoundFns.set(prop, fn);\n }\n return fn;\n }\n\n if (prop === Symbol.toPrimitive) return () => null;\n\n if (prop === Symbol.iterator) {\n let fn = BoundFns.get(Symbol.iterator);\n if (!fn) {\n fn = function* () {\n for (const key in receiver) {\n // yielding arbitrary property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n yield [key, receiver[key as keyof typeof receiver]];\n }\n };\n BoundFns.set(Symbol.iterator, fn);\n }\n return fn;\n }\n\n if (prop === 'constructor') {\n return ReactiveResource;\n }\n\n if (isExtensionProp(extensions, prop)) {\n return performObjectExtensionGet(receiver, extensions!, signals, prop);\n }\n\n // too many things check for random symbols\n if (typeof prop === 'symbol') return undefined;\n\n assert(`No field named ${String(prop)} on ${context.path ? context.value : resourceKey.type}`);\n return undefined;\n }\n\n const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;\n assert(\n `Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`,\n maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)\n );\n /**\n * Prop Array is the path from a resource to the field including\n * intermediate \"links\" on arrays,objects,schema-arrays and schema-objects.\n *\n * E.g. in the following\n *\n * ```\n * const user = {\n * addresses: [{\n * street: 'Sunset Blvd',\n * zip: 90210\n * }]\n * }\n * ```\n *\n * The propArray for \"street\" is ['addresses', 0, 'street']\n *\n * Prop Array follows the `cache` path to the value, not the ui path.\n * Thus, if `addresses` has a sourceKey of `user_addresses` and\n * `zip` has a sourceKey of `zip_code` then the propArray for \"zip\" is\n * ['user_addresses', 0, 'zip_code']\n */\n const propArray = context.path?.slice() ?? [];\n // we use the field.name instead of prop here because we want to use the cache-path not\n // the record path.\n // SAFETY: we lie as string here because if we were to get null\n // we would be in a field kind that won't use the propArray below.\n const fieldCacheKey = getFieldCacheKey(field) as string;\n propArray.push(fieldCacheKey);\n\n switch (field.kind) {\n case '@id':\n case '@hash':\n case '@local':\n case 'derived':\n case 'field':\n case 'attribute':\n case 'schema-array':\n case 'array':\n case 'schema-object':\n case 'object':\n case 'resource':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n return DefaultMode[field.kind as 'field'].get({\n store: context.store,\n resourceKey: resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: propArray,\n field: field as GenericField,\n record: receiver as unknown as ReactiveResource,\n signals,\n value: null,\n });\n\n default:\n assertNeverField(resourceKey, field, propArray);\n }\n },\n\n set(\n target: ReactiveResource,\n prop: string | number | symbol,\n value: unknown,\n receiver: typeof Proxy<ReactiveResource>\n ) {\n // the only \"editable\" prop as it is currently a proxy for \"isDestroyed\"\n if (prop === '___notifications') {\n target[prop] = value as object;\n return true;\n }\n\n if (!context.editable) {\n assert(\n `Cannot set ${String(prop)} on ${context.path !== null ? context.value : resourceKey.type} because the ReactiveResource is not editable`\n );\n return false;\n }\n\n const maybeField = prop === identityField?.name ? identityField : fields.get(prop as string);\n if (!maybeField) {\n const type = context.path !== null ? context.value : resourceKey.type;\n\n if (isExtensionProp(extensions, prop)) {\n return performExtensionSet(receiver, extensions!, signals, prop, value);\n }\n\n assert(`There is no settable field named ${String(prop)} on ${type}`);\n return false;\n }\n const field = maybeField.kind === 'alias' ? maybeField.options : maybeField;\n assert(\n `Alias fields cannot alias '@id' '@local' '@hash' or 'derived' fields`,\n maybeField.kind !== 'alias' || !['@id', '@local', '@hash', 'derived'].includes(maybeField.options.kind)\n );\n /**\n * Prop Array is the path from a resource to the field including\n * intermediate \"links\" on arrays,objects,schema-arrays and schema-objects.\n *\n * E.g. in the following\n *\n * ```\n * const user = {\n * addresses: [{\n * street: 'Sunset Blvd',\n * zip: 90210\n * }]\n * }\n * ```\n *\n * The propArray for \"street\" is ['addresses', 0, 'street']\n *\n * Prop Array follows the `cache` path to the value, not the ui path.\n * Thus, if `addresses` has a sourceKey of `user_addresses` and\n * `zip` has a sourceKey of `zip_code` then the propArray for \"zip\" is\n * ['user_addresses', 0, 'zip_code']\n */\n const propArray = context.path?.slice() ?? [];\n // we use the field.name instead of prop here because we want to use the cache-path not\n // the record path.\n // SAFETY: we lie as string here because if we were to get null\n // we would be in a field kind that won't use the propArray below.\n const fieldCacheKey = getFieldCacheKey(field) as string;\n propArray.push(fieldCacheKey);\n\n switch (field.kind) {\n case '@id':\n case '@hash':\n case '@local':\n case 'field':\n case 'attribute':\n case 'derived':\n case 'array':\n case 'schema-array':\n case 'schema-object':\n case 'object':\n case 'resource':\n case 'belongsTo':\n case 'hasMany':\n case 'collection':\n return DefaultMode[field.kind as '@id'].set({\n store: context.store,\n resourceKey: resourceKey,\n modeName: context.modeName,\n legacy: context.legacy,\n editable: context.editable,\n path: propArray,\n field: field as IdentityField,\n record: receiver as unknown as ReactiveResource,\n signals,\n value,\n });\n\n default:\n return assertNeverField(resourceKey, field, propArray);\n }\n },\n });\n\n if (DEBUG) {\n Object.defineProperty(this, '__SHOW_ME_THE_DATA_(debug mode only)__', {\n enumerable: false,\n configurable: true,\n get() {\n const data: Record<string, unknown> = {};\n for (const key of fields.keys()) {\n // building a debug-only snapshot of raw property values, never invoking them\n // oxlint-disable-next-line typescript/unbound-method\n data[key] = proxy[key as keyof ReactiveResource];\n }\n\n return data;\n },\n });\n }\n\n return proxy;\n }\n}\n\nasync function _COMMIT(record: ReactiveResource): Promise<void> {\n await Promise.resolve();\n const context = record[Context];\n context.store.cache.willCommit(context.resourceKey, null);\n context.store.cache.didCommit(context.resourceKey, null);\n}\n\nexport function _CHECKOUT(record: ReactiveResource): ReactiveResource {\n const context = record[Context];\n\n // IF we are already the editable record, throw an error\n if (context.editable) {\n throw new Error(`Cannot checkout an already editable record`);\n }\n\n const editable = Editables.get(record);\n if (editable) {\n return editable;\n }\n\n if (context.path !== null) {\n throw new Error(`Cannot checkout an embedded record`);\n }\n\n const editableRecord = new ReactiveResource({\n store: context.store,\n resourceKey: context.resourceKey,\n modeName: context.legacy ? 'legacy' : 'polaris',\n legacy: context.legacy,\n editable: true,\n path: null,\n field: null,\n value: null,\n });\n setRecordIdentifier(editableRecord, recordIdentifierFor(record));\n Editables.set(record, editableRecord);\n return editableRecord;\n}\n\nfunction _DESTROY(record: ReactiveResource): void {\n if (record[Context].legacy) {\n // @ts-expect-error\n record.isDestroying = true;\n // @ts-expect-error\n record.isDestroyed = true;\n } else if (!record[Context].editable) {\n const editable = Editables.get(record);\n if (editable) {\n _DESTROY(editable);\n removeRecordIdentifier(editable);\n }\n }\n\n record[Context].store.notifications.unsubscribe(record.___notifications);\n record.___notifications = null as unknown as object;\n\n // FIXME we need a way to also unsubscribe all SchemaObjects when the primary\n // resource is destroyed.\n}\n\nfunction assertNeverField(identifier: ResourceKey, field: never, path: string | string[]): false {\n assert(\n `Cannot use unknown field kind ${(field as FieldSchema).kind} on <${identifier.type}>.${Array.isArray(path) ? path.join('.') : path}`\n );\n return false;\n}\n\n/**\n * Checkout an immutable resource for editing.\n *\n * {@link ReactiveResource | ReactiveResources} are not editable by default. This method\n * creates an editable copy of the resource.\n *\n * This returns a promise which resolves with the editable\n * version of the resource.\n *\n * ```ts\n * import { checkout } from '@warp-drive/core/reactive';\n *\n * const immutable = store.peekRecord('user', '1');\n * const editable = await checkout(immutable);\n * ```\n *\n * Edits to editable resources will be automatically committed if a new\n * payload from the cache matches their existing value.\n *\n * @public\n *\n * @returns a promise that resolves to the editable resource\n * @throws if the resource is already editable or if resource is an embedded object\n */\nexport function checkout<T>(resource: unknown): Promise<T & ReactiveResource> {\n return (resource as ReactiveResource)[Checkout]();\n}\n\n/**\n * Forcibly commit all local changes on an editable resource to\n * the remote (immutable) version.\n *\n * This API should only be used cautiously. Typically a better\n * approach is for either the API or a Handler to reflect saved\n * changes back to update the cache.\n *\n * @public\n */\nexport function commit(record: ReactiveResource): Promise<void> {\n return record[Commit]();\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Store } from '../../index.ts';\nimport type { ResourceKey } from '../../types.ts';\nimport { isResourceSchema } from '../../types/schema/fields.ts';\nimport { ReactiveResource } from './record.ts';\nimport type { SchemaService } from './schema.ts';\nimport { Destroy } from './symbols.ts';\n\n/**\n * The store's default `instantiateRecord` hook implementation, which\n * produces a {@link ReactiveResource} for `identifier` using the resource\n * schema registered for its type.\n *\n * `createArgs` are only applied (via `Object.assign`) when the resource's\n * schema is `legacy`, matching the historical behavior of assigning initial\n * properties when creating a new legacy record.\n *\n * @public\n */\nexport function instantiateRecord(\n store: Store,\n identifier: ResourceKey,\n createArgs?: Record<string, unknown>\n): ReactiveResource {\n const schema = store.schema as unknown as SchemaService;\n const resourceSchema = schema.resource(identifier);\n assert(`Expected a resource schema`, isResourceSchema(resourceSchema));\n const legacy = resourceSchema?.legacy ?? false;\n const editable = legacy;\n const record = new ReactiveResource({\n store,\n resourceKey: identifier,\n modeName: legacy ? 'legacy' : 'polaris',\n legacy: legacy,\n editable: editable,\n path: null,\n field: null,\n value: null,\n });\n\n if (createArgs && editable) {\n Object.assign(record, createArgs);\n }\n\n return record;\n}\n\nfunction assertReactiveResource(record: unknown): asserts record is ReactiveResource {\n assert('Expected a ReactiveResource', record && typeof record === 'object' && Destroy in record);\n}\n\n/**\n * The store's default `teardownRecord` hook implementation, which asserts\n * that `record` is a {@link ReactiveResource} and invokes its `Destroy`\n * behavior.\n *\n * @public\n */\nexport function teardownRecord(record: unknown): void {\n assertReactiveResource(record);\n record[Destroy]();\n}\n","import { deprecate, warn } from '@ember/debug';\n\nimport { ENFORCE_STRICT_RESOURCE_FINALIZATION } from '@warp-drive/build-config/canary-features';\nimport { DEBUG } from '@warp-drive/build-config/env';\nimport { ENABLE_LEGACY_SCHEMA_SERVICE } from '@warp-drive/core/build-config/deprecations';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { recordIdentifierFor } from '../../index.ts';\nimport { createInternalMemo, type WarpDriveSignal, withSignalStore } from '../../signals/-private.ts';\nimport type { Store } from '../../store/-private.ts';\nimport type { SchemaService as SchemaServiceInterface } from '../../types.ts';\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport type { ResourceKey } from '../../types/identifier.ts';\nimport type { ObjectValue, Value } from '../../types/json/raw.ts';\nimport type { Derivation, HashFn } from '../../types/schema/concepts.ts';\nimport {\n type ArrayField,\n type CacheableFieldSchema,\n type DerivedField,\n type FieldSchema,\n type GenericField,\n type HashField,\n type IdentityField,\n isResourceSchema,\n type LegacyAttributeField,\n type LegacyBelongsToField,\n type LegacyHasManyField,\n type LegacyRelationshipField,\n type LegacyResourceSchema,\n type LinksModeBelongsToField,\n type LinksModeHasManyField,\n type ObjectField,\n type ObjectSchema,\n type PolarisResourceSchema,\n type ResourceSchema,\n type SchemaArrayField,\n type SchemaObjectField,\n type Trait,\n} from '../../types/schema/fields.ts';\nimport { Type } from '../../types/symbols.ts';\nimport type { WithPartial } from '../../types/utils.ts';\nimport { getFieldCacheKeyStrict, isNonIdentityCacheableField } from './fields/get-field-key.ts';\nimport type { ReactiveResource } from './record.ts';\nimport { Context } from './symbols.ts';\n\nconst Support = getOrSetGlobal('Support', new WeakMap<WeakKey, Record<string, unknown>>());\n\nconst ConstructorField = {\n type: '@constructor',\n name: 'constructor',\n kind: 'derived',\n} satisfies DerivedField;\nconst TypeField = {\n type: '@identity',\n name: '$type',\n kind: 'derived',\n options: { key: 'type' },\n} satisfies DerivedField;\nconst IdentifierField = {\n type: '@identity',\n name: '$key',\n kind: 'derived',\n options: { key: '^' },\n} satisfies DerivedField;\nconst DefaultIdentityField = { name: 'id', kind: '@id' } satisfies IdentityField;\n\nfunction _constructor(record: ReactiveResource) {\n let state = Support.get(record);\n if (!state) {\n state = {};\n Support.set(record, state);\n }\n\n return (state._constructor = state._constructor || {\n name: `ReactiveResource<${recordIdentifierFor(record).type}>`,\n get modelName() {\n assert(`record.constructor.modelName is not available outside of legacy mode`, false);\n return undefined;\n },\n });\n}\n_constructor[Type] = '@constructor';\n\n/**\n * Extensions allow providing non-schema driven behaviors to\n * ReactiveResources, ReactiveArrays, and ReactiveObjects.\n *\n * This should only be used for temporary migration purposes\n * to the new schema system when migrating from either Model\n * or ModelFragments.\n */\nexport interface CAUTION_MEGA_DANGER_ZONE_Extension {\n /**\n * Whether this extension extends the behaviors of objects\n * (both ReactiveObjects and ReactiveResources) or of arrays.\n */\n kind: 'object' | 'array';\n /**\n * The name of the extension, to be used when specifying\n * either `objectExtensions` or `arrayExtensions` on the\n * field, ResourceSchema or ObjectSchema\n */\n name: string;\n /**\n * An object with iterable keys whose values are the getters\n * or methods to expose on the object or array.\n *\n * or\n *\n * A constructable such as a Function or Class whose prototype\n * will be iterated with getOwnPropertyNames.\n *\n * Examples:\n *\n * **An Object with methods**\n *\n * ```ts\n * store.schema.CAUTION_MEGA_DANGER_ZONE_registerExtension({\n * kind: 'object',\n * name: 'do-thing-1',\n * features: {\n * doThingOne(this: { street: string }) {\n * return `do-thing-1:${this.street}`;\n * },\n * doThingTwo(this: { street: string }) {\n * return `do-thing-1:${this.street}`;\n * },\n * },\n * });\n * ```\n *\n * **A class with getters, methods and decorated fields**\n *\n * ```ts\n * class Features {\n * sayHello() {\n * return 'hello!';\n * }\n *\n * @tracked trackedField = 'initial tracked value';\n *\n * get realName() {\n * const self = this as unknown as { name: string };\n * return self.name;\n * }\n * set realName(v: string) {\n * const self = this as unknown as { name: string };\n * self.name = v;\n * }\n *\n * get greeting() {\n * const self = this as unknown as { name: string };\n * return `hello ${self.name}!`;\n * }\n *\n * @computed('name')\n * get salutation() {\n * const self = this as unknown as { name: string };\n * return `salutations ${self.name}!`;\n * }\n *\n * @cached\n * get helloThere() {\n * const self = this as unknown as { name: string };\n * return `Well Hello There ${self.name}!`;\n * }\n * }\n *\n * // non-decorated fields dont appear on class prototypes as they are instance only\n * // @ts-expect-error\n * Features.prototype.untrackedField = 'initial untracked value';\n *\n * store.schema.CAUTION_MEGA_DANGER_ZONE_registerExtension({\n * kind: 'object',\n * name: 'my-ext',\n * features: Features,\n * });\n * ```\n *\n */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n features: Record<string | symbol, unknown> | Function;\n}\n\n/**\n * Describes one feature added to a resource by a schema extension, as\n * classified by {@link processExtension} from the property descriptor it\n * was declared with (a method, a plain value, or a getter/setter pair).\n */\nexport type ExtensionDef =\n | {\n /** A callable feature, installed as a method. */\n kind: 'method';\n /** The function to invoke when the feature is called. */\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n fn: Function;\n }\n | {\n /** A plain, non-writable data feature. */\n kind: 'readonly-value';\n /** The value to expose for the feature. */\n value: unknown;\n }\n | {\n /** A plain, writable data feature. */\n kind: 'mutable-value';\n /** The value to expose for the feature. */\n value: unknown;\n }\n | {\n /** An accessor feature with only a getter. */\n kind: 'readonly-field';\n /** Computes the feature's value. */\n get: () => unknown;\n }\n | {\n /** An accessor feature with both a getter and a setter. */\n kind: 'mutable-field';\n /** Computes the feature's value. */\n get: () => unknown;\n /** Assigns the feature's value. */\n set: (value: unknown) => void;\n }\n | {\n /** An accessor feature with only a setter. */\n kind: 'writeonly-field';\n /** Assigns the feature's value. */\n set: (value: unknown) => void;\n };\n\n/**\n * The result of {@link processExtension} normalizing a\n * {@link CAUTION_MEGA_DANGER_ZONE_Extension} into a lookup of its features\n * by name.\n */\nexport interface ProcessedExtension {\n /** Whether this extension applies to objects/resources or to arrays. */\n kind: 'object' | 'array';\n /** The name the extension was registered under. */\n name: string;\n /** Each feature the extension exposes, keyed by its property name. */\n features: Map<string | symbol, ExtensionDef>;\n}\n\nconst BannedKeys = ['constructor', '__proto__'];\n\nfunction processExtension(extension: CAUTION_MEGA_DANGER_ZONE_Extension): ProcessedExtension {\n const { kind, name } = extension;\n const features = new Map<string | symbol, ExtensionDef>();\n const baseFeatures =\n typeof extension.features === 'function'\n ? (extension.features.prototype as Record<string | symbol, unknown>)\n : extension.features;\n for (const key of Object.getOwnPropertyNames(baseFeatures)) {\n if (BannedKeys.includes(key)) continue;\n\n const decl = Object.getOwnPropertyDescriptor(baseFeatures, key);\n assert(`Expected to find a declaration for ${key} on extension ${name}`, decl);\n if (decl.value) {\n const { value } = decl as { value: unknown };\n features.set(\n key,\n typeof value === 'function'\n ? {\n kind: 'method',\n fn: value,\n }\n : decl.writable\n ? {\n kind: 'mutable-value',\n value,\n }\n : {\n kind: 'readonly-value',\n value,\n }\n );\n continue;\n }\n\n if (decl.get || decl.set) {\n const { get, set } = decl as { get?: () => unknown; set?: (v: unknown) => void };\n features.set(\n key,\n // prettier-ignore\n get && set ? { kind: 'mutable-field', get, set }\n : get ? { kind: 'readonly-field', get }\n : { kind: 'writeonly-field', set: set! }\n );\n continue;\n }\n\n assert(`The feature ${key} on extension ${name} is of an unknown variety.`);\n }\n\n return {\n kind,\n name,\n features,\n };\n}\n/**\n * A field (or schema) capable of declaring `objectExtensions` and/or\n * `arrayExtensions` to mix registered {@link CAUTION_MEGA_DANGER_ZONE_Extension}\n * features onto it.\n */\nexport interface ExtensibleField {\n /** The kind of field, only some of which support extensions. */\n kind: 'schema-object' | 'schema-array' | 'array' | 'object' | 'hasMany';\n /** Configures which registered extensions to mix onto this field. */\n options?: {\n /** Names of registered object extensions to mix onto this field. */\n objectExtensions?: string[];\n /** Names of registered array extensions to mix onto this field. */\n arrayExtensions?: string[];\n };\n}\n\nfunction getExt(\n extCache: { object: Map<string | symbol, ProcessedExtension>; array: Map<string | symbol, ProcessedExtension> },\n type: 'array' | 'object',\n extName: string | symbol\n): null | ProcessedExtension['features'] {\n const ext = extCache[type].get(extName);\n assert(`expected to have an extension named ${String(extName)} available for ${type}s`, ext);\n return ext?.features ?? null;\n}\n\nfunction hasObjectSchema(\n field: ObjectSchema | ResourceSchema | SchemaArrayField | SchemaObjectField | ExtensibleField\n): field is SchemaArrayField | SchemaObjectField {\n return 'kind' in field && (field.kind === 'schema-array' || field.kind === 'schema-object');\n}\n\nfunction pretendIsResourceOrObjectSchema(\n field: ObjectSchema | ResourceSchema | ExtensibleField\n): asserts field is ObjectSchema | LegacyResourceSchema {}\n\nfunction processExtensions(\n schema: SchemaService,\n field: ExtensibleField | ObjectSchema | ResourceSchema,\n scenario: 'resource' | 'object' | 'array',\n resolvedType: string | null\n) {\n // if we're looking up extensions for a resource, there is no\n // merging required so if we have no objectExtensions\n // we are done.\n if (scenario === 'resource') {\n pretendIsResourceOrObjectSchema(field);\n if (!('objectExtensions' in field || !field.objectExtensions?.length)) {\n return null;\n }\n }\n\n const type = scenario === 'resource' ? 'object' : scenario;\n const extCache = schema._extensions;\n const fieldCache = schema._cachedFieldExtensionsByField;\n\n if (fieldCache[type].has(field)) {\n return fieldCache[type].get(field)!;\n }\n\n // prettier-ignore\n const extensions =\n (\n scenario === 'resource' ? (field as { objectExtensions?: string[] }).objectExtensions\n : scenario === 'object' ? (field as ExtensibleField).options?.objectExtensions\n : (field as ExtensibleField).options?.arrayExtensions\n ) || null;\n\n // if we are a resource scenario, we know from the first check we do have extensions\n // if we are an object scenario, we can now return the resource scenario.\n // if we are an array scenario, there is nothing more to process.\n if (!extensions) {\n if (scenario === 'array') return null;\n\n if (!hasObjectSchema(field)) {\n return null;\n }\n\n return schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resolvedType ? { type: resolvedType } : (field as { type: string })\n );\n }\n\n // if we have made it here, we have extensions, lets check if there's\n // a cached version we can use\n const baseExtensions =\n scenario === 'resource' && hasObjectSchema(field)\n ? schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(field as { type: string })\n : scenario === 'object' && hasObjectSchema(field)\n ? schema.CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resolvedType ? { type: resolvedType } : (field as { type: string })\n )\n : null;\n\n if (!baseExtensions && extensions.length === 1) {\n const value = getExt(extCache, type, extensions[0]);\n fieldCache[type].set(field, value);\n return value;\n }\n\n const features = new Map<string | symbol, ExtensionDef>(baseExtensions);\n for (const extName of extensions) {\n const value = getExt(extCache, type, extName);\n if (value) {\n for (const [feature, desc] of value) {\n features.set(feature, desc);\n }\n }\n }\n\n const value = features.size ? features : null;\n fieldCache[type].set(field, value);\n\n return value;\n}\n\n/**\n * Utility for constructing a ResourceSchema with the recommended\n * fields for the PolarisMode experience.\n *\n * Using this requires registering the PolarisMode derivations\n *\n * ```ts\n * import { registerDerivations } from '@warp-drive/schema-record';\n *\n * registerDerivations(schema);\n * ```\n *\n * @public\n * @param schema\n * @return {PolarisResourceSchema}\n */\nexport function withDefaults(schema: WithPartial<PolarisResourceSchema, 'identity'>): PolarisResourceSchema {\n schema.identity = schema.identity || DefaultIdentityField;\n\n // because fields gets iterated in definition order,\n // we add TypeField to the beginning so that it will\n // appear right next to the identity field\n schema.fields.unshift(TypeField);\n schema.fields.unshift(IdentifierField);\n schema.fields.push(ConstructorField);\n return schema as PolarisResourceSchema;\n}\n\ninterface FromIdentityDerivation {\n (record: ReactiveResource, options: { key: 'lid' } | { key: 'type' }, key: string): string;\n (record: ReactiveResource, options: { key: 'id' }, key: string): string | null;\n (record: ReactiveResource, options: { key: '^' }, key: string): ResourceKey;\n (record: ReactiveResource, options: null, key: string): asserts options;\n (\n record: ReactiveResource,\n options: { key: 'id' | 'lid' | 'type' | '^' } | null,\n key: string\n ): ResourceKey | string | null;\n [Type]: '@identity';\n}\n\n/**\n * A derivation that computes its value from the\n * record's identity.\n *\n * It can be used via a derived field definition like:\n *\n * ```ts\n * {\n * kind: 'derived',\n * name: 'id',\n * type: '@identity',\n * options: { key: 'id' }\n * }\n * ```\n *\n * Valid keys are `'id'`, `'lid'`, `'type'`, and `'^'`.\n *\n * `^` returns the entire identifier object.\n *\n * @public\n */\nexport const fromIdentity = ((\n record: ReactiveResource,\n options: { key: 'id' | 'lid' | 'type' | '^' } | null,\n key: string\n): ResourceKey | string | null => {\n const context = record[Context];\n const identifier = context.resourceKey;\n assert(`Cannot compute @identity for a record without an identifier`, identifier);\n assert(\n `Expected to receive a key to compute @identity, but got ${String(options)}`,\n options?.key && ['lid', 'id', 'type', '^'].includes(options.key)\n );\n\n return options.key === '^' ? identifier : identifier[options.key];\n}) as unknown as FromIdentityDerivation;\nfromIdentity[Type] = '@identity';\n\n/**\n * Registers the default derivations for records that want\n * to use the PolarisMode defaults provided by\n *\n * ```ts\n * import { withDefaults } from '@warp-drive/schema-record';\n * ```\n *\n * @public\n */\nexport function registerDerivations(schema: SchemaServiceInterface): void {\n schema.registerDerivation(fromIdentity);\n schema.registerDerivation(_constructor);\n}\n\n/**\n * A relationship field capable of declaring `options.as`, marking it as a\n * concrete implementation of an abstract polymorphic type.\n */\ntype AbstractTypeImplementerField =\n | LegacyBelongsToField\n | LegacyHasManyField\n | LinksModeBelongsToField\n | LinksModeHasManyField;\n\n/**\n * A relationship field contributed to an abstract type's schema, along with\n * the name of the type that contributed it (either a concrete implementer,\n * via `options.as`, or the abstract type's own schema), for use in assertion\n * messages when two contributions disagree on shape.\n */\ninterface AbstractFieldContribution {\n field: AbstractTypeImplementerField;\n source: string;\n}\n\n/**\n * Reduces a field to a plain object with a fixed key order, covering every\n * option any relationship-implementer field can declare, so two fields can\n * be compared for exact equality via `JSON.stringify` regardless of the key\n * order the schema author happened to write them in.\n *\n * `options.as` is included and is *not* special-cased: every contributor to\n * a given field name on an abstract type - including the abstract type's\n * own schema, if it has one - is expected to declare `as` equal to that\n * abstract type's own name. This is redundant/self-referential for the\n * abstract type's own schema, but required for consistency: relationship\n * resolution elsewhere (e.g. `inverse` name-matching) does not itself\n * validate `as`, so a field with a missing or incorrect `as` can otherwise\n * be silently pulled into a relationship it never declared it implements.\n */\nfunction comparableAbstractFieldShape(field: FieldSchema): unknown {\n const { kind, name, type, sourceKey, options } = field as {\n kind: string;\n name: string;\n type?: string;\n sourceKey?: string;\n options?: {\n as?: string;\n async?: boolean;\n inverse?: string | null;\n polymorphic?: boolean;\n linksMode?: boolean;\n resetOnRemoteUpdate?: boolean;\n arrayExtensions?: string[];\n };\n };\n return {\n kind,\n name,\n type,\n sourceKey,\n options: {\n as: options?.as,\n async: options?.async,\n inverse: options?.inverse,\n polymorphic: options?.polymorphic,\n linksMode: options?.linksMode,\n resetOnRemoteUpdate: options?.resetOnRemoteUpdate,\n arrayExtensions: options?.arrayExtensions,\n },\n };\n}\n\n/**\n * Asserts that two contributions to the same field name on an abstract\n * polymorphic type - whether from two different concrete implementers, or\n * from an implementer and the abstract type's own schema - declare an\n * identical shape: `kind`, `type`, and every option, including `as` (which\n * every contributor, the abstract type's own schema included, must declare\n * equal to `abstractType`). A mismatch here (e.g. one implementer's field\n * being a `hasMany` while another's is a `belongsTo`, the two disagreeing on\n * `inverse`/`async`/`polymorphic`, or one omitting or misdeclaring `as`)\n * cannot be resolved by picking one side arbitrarily, since that would\n * silently leave whichever side lost the mismatch pointing at a relationship\n * whose true shape differs from what its own schema declared.\n */\nfunction assertConsistentAbstractFieldShape(\n abstractType: string,\n fieldName: string,\n existing: { field: FieldSchema; source: string },\n incoming: { field: FieldSchema; source: string }\n): void {\n // This function exists solely to support the `assert()` call below - there\n // is no other work here with an effect in production. Since `assert()`'s\n // own babel-macro stripping only removes the call expression itself, not\n // the (comparatively expensive, involving `JSON.stringify`) computation of\n // its arguments, guard the whole body so none of it survives in production\n // builds, matching how `assertPolymorphicType`/`assertInheritedSchema` and\n // their call sites are gated in `assert-polymorphic-type.ts`.\n if (DEBUG) {\n const existingShape = comparableAbstractFieldShape(existing.field);\n const incomingShape = comparableAbstractFieldShape(incoming.field);\n assert(\n `Expected the relationship '${fieldName}' on the abstract polymorphic type '${abstractType}' to be declared identically everywhere it is implemented (including 'options.as', which every contributor - the abstract type's own schema included - must declare equal to '${abstractType}'), but '${existing.source}' declares it as:\\n\\n${JSON.stringify(existingShape, null, 2)}\\n\\nwhile '${incoming.source}' declares it as:\\n\\n${JSON.stringify(incomingShape, null, 2)}\\n\\nAll concrete implementers of an abstract type - and the abstract type's own schema, if it has one - must declare an identical shape for any relationship field they share.`,\n JSON.stringify(existingShape) === JSON.stringify(incomingShape)\n );\n }\n}\n\ninterface InternalSchema {\n original: ResourceSchema | ObjectSchema;\n finalized: boolean;\n traits: Set<string>;\n fields: Map<string, FieldSchema>;\n cacheFields: Map<string, Exclude<CacheableFieldSchema, IdentityField>>;\n attributes: Record<string, LegacyAttributeField>;\n relationships: Record<string, LegacyRelationshipField>;\n}\n\n/**\n * Defines how to convert a `GenericField`, `ObjectField`, or `ArrayField`\n * between the raw value `T` stored in the cache and the presentation value\n * `PT` exposed on the record.\n */\nexport type Transformation<T extends Value = Value, PT = unknown> = {\n /** Converts the presentation value into the raw value to store in the cache. */\n serialize(value: PT, options: Record<string, unknown> | null, record: ReactiveResource): T;\n /** Converts the raw cache value into its presentation value. */\n hydrate(value: T | undefined, options: Record<string, unknown> | null, record: ReactiveResource): PT;\n /** Computes the value to use when the cache has no value for the field. */\n defaultValue?(options: Record<string, unknown> | null, identifier: ResourceKey): T;\n /** The name under which this transformation is registered and looked up. */\n [Type]: string;\n};\n\n/**\n * Wraps a derivation in a new function with Derivation signature but that looks\n * up the value in the cache before recomputing.\n *\n * @internal\n */\nfunction makeCachedDerivation<R, T, FM extends ObjectValue | null>(\n derivation: Derivation<R, T, FM>\n): Derivation<R, T, FM> {\n const memoizedDerivation = (record: R, options: FM, prop: string): T => {\n const signals = withSignalStore(record as object);\n let signal = signals.get(prop);\n if (!signal) {\n signal = createInternalMemo(signals, record as object, prop, () => {\n return derivation(record, options, prop);\n }) as unknown as WarpDriveSignal; // a total lie, for convenience of reusing the storage\n }\n\n return (signal as unknown as () => T)();\n };\n memoizedDerivation[Type] = derivation[Type];\n return memoizedDerivation;\n}\n\ninterface KindFns {\n belongsTo: {\n get: (store: Store, record: object, resourceKey: ResourceKey, field: LegacyBelongsToField) => unknown;\n set: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyBelongsToField, value: unknown) => void;\n };\n hasMany: {\n get: (store: Store, record: object, resourceKey: ResourceKey, field: LegacyHasManyField) => unknown;\n set: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyHasManyField, value: unknown) => void;\n notify: (store: Store, record: object, cacheKey: ResourceKey, field: LegacyHasManyField) => boolean;\n };\n}\n\nexport interface SchemaService {\n doesTypeExist(type: string): boolean;\n attributesDefinitionFor(identifier: { type: string }): InternalSchema['attributes'];\n relationshipsDefinitionFor(identifier: { type: string }): InternalSchema['relationships'];\n}\n\ninterface InternalTrait {\n name: string;\n mode: 'legacy' | 'polaris';\n fields: Map<string, FieldSchema>;\n traits: string[];\n}\n\n/**\n * A SchemaService designed to work with dynamically registered schemas.\n *\n * @public\n */\nexport class SchemaService implements SchemaServiceInterface {\n /** @internal */\n declare _schemas: Map<string, InternalSchema>;\n /** @internal */\n declare _transforms: Map<string, Transformation>;\n /** @internal */\n declare _hashFns: Map<string, HashFn>;\n /** @internal */\n // oxlint-disable-next-line typescript/no-explicit-any\n declare _derivations: Map<string, Derivation<any, any, any>>;\n /** @internal */\n declare _traits: Map<string, InternalTrait>;\n /** @internal */\n declare _modes: Map<string, KindFns>;\n /**\n * Tracks, per abstract type, the relationship fields that concrete\n * implementers have contributed via `options.as`, along with the type\n * that contributed each one (for assertion messages). This is\n * independent of whatever schema (synthesized or user-registered)\n * currently occupies `_schemas` for that type, so that these fields\n * survive regardless of the order in which the abstract type's\n * implementers and its own (optional) concrete schema are registered.\n *\n * @internal\n */\n declare _abstractImplementerFields: Map<string, Map<string, AbstractFieldContribution>>;\n /** @internal */\n declare _extensions: {\n object: Map<string, ProcessedExtension>;\n array: Map<string, ProcessedExtension>;\n };\n /** @internal */\n declare _cachedFieldExtensionsByField: {\n object: Map<object, ProcessedExtension['features'] | null>;\n array: Map<object, ProcessedExtension['features'] | null>;\n };\n\n constructor() {\n this._schemas = new Map();\n this._transforms = new Map();\n this._hashFns = new Map();\n this._derivations = new Map();\n this._traits = new Map();\n this._modes = new Map();\n this._abstractImplementerFields = new Map();\n this._extensions = {\n object: new Map(),\n array: new Map(),\n };\n this._cachedFieldExtensionsByField = {\n object: new Map(),\n array: new Map(),\n };\n }\n\n resourceTypes(): Readonly<string[]> {\n return Array.from(this._schemas.keys());\n }\n\n hasTrait(type: string): boolean {\n return this._traits.has(type);\n }\n resourceHasTrait(resource: ResourceKey | { type: string }, trait: string): boolean {\n return this._schemas.get(resource.type)!.traits.has(trait);\n }\n transformation(field: GenericField | ObjectField | ArrayField | { type: string }): Transformation {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `'${kind}' fields cannot be transformed. Only fields of kind 'field' 'object' or 'array' can specify a transformation. Attempted to find '${field.type ?? '<unknown type>'}' on field '${name}'.`,\n !('kind' in field) || ['field', 'object', 'array'].includes(kind)\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a transformation via 'field.type', but none was present`,\n field.type\n );\n assert(\n `No transformation registered with name '${field.type}' for '${kind}' field '${name}'`,\n this._transforms.has(field.type)\n );\n return this._transforms.get(field.type)!;\n }\n derivation(field: DerivedField | { type: string }): Derivation {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `The '${kind}' field '${name}' is not derived and so cannot be used to lookup a derivation`,\n !('kind' in field) || kind === 'derived'\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a derivation via 'field.type', but no value was present`,\n field.type\n );\n assert(\n `No '${field.type}' derivation registered for use by the '${kind}' field '${name}'`,\n this._derivations.has(field.type)\n );\n return this._derivations.get(field.type)!;\n }\n hashFn(field: HashField | { type: string }): HashFn {\n const kind = 'kind' in field ? field.kind : '<unknown kind>';\n const name = 'name' in field ? field.name : '<unknown name>';\n assert(\n `The '${kind}' field '${name}' is not a HashField and so cannot be used to lookup a hash function`,\n !('kind' in field) || kind === '@hash'\n );\n assert(\n `Expected the '${kind}' field '${name}' to specify a hash function via 'field.type', but no value was present`,\n field.type\n );\n assert(\n `No '${field.type}' hash function is registered for use by the '${kind}' field '${name}'`,\n this._hashFns.has(field.type)\n );\n return this._hashFns.get(field.type)!;\n }\n resource(resource: ResourceKey | { type: string }): ResourceSchema | ObjectSchema {\n assert(`No resource registered with name '${resource.type}'`, this._schemas.has(resource.type));\n return this._schemas.get(resource.type)!.original;\n }\n registerResources(schemas: Array<ResourceSchema | ObjectSchema>): void {\n schemas.forEach((schema) => {\n this.registerResource(schema);\n });\n }\n registerResource(schema: ResourceSchema | ObjectSchema): void {\n const fields = new Map<string, FieldSchema>();\n const relationships: Record<string, LegacyRelationshipField> = {};\n const attributes: Record<string, LegacyAttributeField> = {};\n const abstractImplementations: AbstractTypeImplementerField[] = [];\n\n for (const field of schema.fields) {\n assert(\n `${field.kind} is not valid inside a ResourceSchema's fields.`,\n // @ts-expect-error we are checking for mistakes at runtime\n field.kind !== '@id' && field.kind !== '@hash'\n );\n fields.set(field.name, field);\n if (field.kind === 'attribute') {\n attributes[field.name] = field;\n } else if (field.kind === 'belongsTo' || field.kind === 'hasMany') {\n relationships[field.name] = field;\n if (field.options?.as) {\n abstractImplementations.push(field);\n }\n }\n }\n\n // This type may already be known as an abstract polymorphic type,\n // implemented by other concrete types via `options.as`, from before it\n // ever had a schema of its own (see `_registerAbstractTypeImplementation`).\n // Carry those previously-contributed fields forward so that registering\n // a \"real\" schema for the type - whenever that happens to occur - never\n // erases the relationships its implementers depend on.\n const implementerFields = this._abstractImplementerFields.get(schema.type);\n if (implementerFields) {\n for (const [name, contribution] of implementerFields) {\n const ownField = fields.get(name);\n if (!ownField) {\n fields.set(name, contribution.field);\n relationships[name] = contribution.field;\n } else if (DEBUG) {\n assertConsistentAbstractFieldShape(schema.type, name, contribution, { field: ownField, source: schema.type });\n }\n }\n }\n\n const cacheFields = null as unknown as Map<string, Exclude<CacheableFieldSchema, IdentityField>>;\n const traits = new Set<string>(isResourceSchema(schema) ? schema.traits : []);\n const finalized = traits.size === 0;\n const internalSchema: InternalSchema = {\n original: schema,\n finalized,\n fields,\n cacheFields,\n relationships,\n attributes,\n traits,\n };\n\n if (traits.size === 0) {\n internalSchema.cacheFields = getCacheFields(internalSchema);\n }\n\n this._schemas.set(schema.type, internalSchema);\n\n // A relationship field's `as` option marks it as a valid concrete\n // implementer of an abstract polymorphic type (e.g. `as: 'commentable'`).\n // That abstract type may never be given its own schema by the user - it\n // may exist only to be implemented by concrete types like this one - or\n // it may already have (or later receive) a schema of its own, e.g. if it\n // turns out to also be a real, directly-resolvable resource. Either way,\n // ensure it has a schema with this field present, so that it behaves\n // like any other registered resource (`hasResource`, `fields`, etc.)\n // instead of requiring special-casing wherever abstract relationship\n // types are resolved.\n for (const field of abstractImplementations) {\n this._registerAbstractTypeImplementation(field, schema.type);\n }\n }\n\n /** @internal */\n private _registerAbstractTypeImplementation(field: AbstractTypeImplementerField, implementer: string): void {\n const abstractType = field.options.as!;\n\n let implementerFields = this._abstractImplementerFields.get(abstractType);\n if (!implementerFields) {\n implementerFields = new Map();\n this._abstractImplementerFields.set(abstractType, implementerFields);\n }\n\n // Unlike the original approach this replaced, `as` is *not* stripped here:\n // the field as synthesized onto the abstract type's own schema keeps\n // `options.as === abstractType`, redundant/self-referential as that is.\n // This keeps every contributor - implementers and the abstract type's\n // own schema alike - declaring the same thing, which is what\n // `assertConsistentAbstractFieldShape` checks, and it is also what lets\n // `assertPolymorphicType` (which reads a field's declared `as` off\n // whatever `schema.fields()` serves for its type) correctly permit the\n // abstract type itself to be pushed directly into this relationship.\n const abstractField = { ...field };\n const contribution: AbstractFieldContribution = { field: abstractField, source: implementer };\n\n // all concrete implementations of an abstract type are required to\n // share the same shape for the field that implements it, so the first\n // one registered is as good a canonical source as any - but a later,\n // differently-shaped one is almost certainly a mistake rather than an\n // intentional override, so we catch it rather than silently ignoring it.\n const existingImplementer = implementerFields.get(field.name);\n if (existingImplementer) {\n if (DEBUG) {\n assertConsistentAbstractFieldShape(abstractType, field.name, existingImplementer, contribution);\n }\n return;\n }\n implementerFields.set(field.name, contribution);\n\n let abstractSchema = this._schemas.get(abstractType);\n if (!abstractSchema) {\n abstractSchema = {\n original: {\n legacy: true,\n identity: { kind: '@id', name: 'id' },\n type: abstractType,\n fields: [],\n },\n finalized: true,\n fields: new Map(),\n cacheFields: new Map(),\n relationships: {},\n attributes: {},\n traits: new Set(),\n };\n this._schemas.set(abstractType, abstractSchema);\n }\n\n const existingAbstractField = abstractSchema.fields.get(field.name);\n if (existingAbstractField) {\n if (DEBUG) {\n assertConsistentAbstractFieldShape(\n abstractType,\n field.name,\n { field: existingAbstractField, source: abstractType },\n contribution\n );\n }\n return;\n }\n\n abstractSchema.fields.set(field.name, abstractField);\n abstractSchema.relationships[field.name] = abstractField;\n\n // If the schema is mid-finalization (traits pending), finalizeResource\n // will recompute cacheFields from the current `fields` map anyway; avoid\n // doing so prematurely from a partially-resolved set of fields.\n if (abstractSchema.finalized) {\n abstractSchema.cacheFields = getCacheFields(abstractSchema);\n }\n }\n\n /**\n * Registers a {@link Trait} for use by resource schemas.\n *\n * Traits are re-usable collections of fields that can be composed to\n * build up a resource schema. Often they represent polymorphic behaviors\n * a resource should exhibit.\n *\n * When we finalize a resource, we walk its traits and apply their fields\n * to the resource's fields. All specified traits must be registered by\n * this time or an error will be thrown.\n *\n * Traits are applied left-to-right, with traits of traits being applied in the same\n * way. Thus for the most part, application of traits is a post-order graph traversal\n * problem.\n *\n * A trait is only ever processed once. If multiple traits (A, B, C) have the same\n * trait (D) as a dependency, D will be included only once when first encountered by\n * A.\n *\n * If a cycle exists such that trait A has trait B which has Trait A, trait A will\n * be applied *after* trait B in production. In development a cycle error will be thrown.\n *\n * Fields are finalized on a \"last wins principle\". Thus traits appearing higher in\n * the tree and further to the right of a traits array take precedence, with the\n * resource's fields always being applied last and winning out.\n *\n * @public\n */\n registerTrait(trait: Trait): void {\n const internalTrait = Object.assign({}, trait, { fields: new Map() }) as InternalTrait;\n for (const field of trait.fields) {\n internalTrait.fields.set(field.name, field);\n }\n this._traits.set(trait.name, internalTrait);\n }\n\n registerTransformation<T extends Value = string, PT = unknown>(transformation: Transformation<T, PT>): void {\n this._transforms.set(transformation[Type], transformation);\n }\n\n registerDerivation<R, T, FM extends ObjectValue | null>(derivation: Derivation<R, T, FM>): void {\n this._derivations.set(derivation[Type], makeCachedDerivation(derivation));\n }\n\n CAUTION_MEGA_DANGER_ZONE_registerExtension(extension: CAUTION_MEGA_DANGER_ZONE_Extension): void {\n assert(\n `an extension named ${extension.name} for ${extension.kind} already exists!`,\n !this._extensions[extension.kind].has(extension.name)\n );\n this._extensions[extension.kind].set(extension.name, processExtension(extension));\n }\n\n CAUTION_MEGA_DANGER_ZONE_resourceExtensions(\n resource: ResourceKey | { type: string }\n ): null | ProcessedExtension['features'] {\n const schema = this.resource(resource);\n return processExtensions(this, schema, 'resource', null);\n }\n\n CAUTION_MEGA_DANGER_ZONE_objectExtensions(\n field: ExtensibleField,\n resolvedType: string | null\n ): null | ProcessedExtension['features'] {\n return processExtensions(this, field, 'object', resolvedType);\n }\n\n CAUTION_MEGA_DANGER_ZONE_arrayExtensions(field: ExtensibleField): null | ProcessedExtension['features'] {\n return processExtensions(this, field, 'array', null);\n }\n\n CAUTION_MEGA_DANGER_ZONE_hasExtension(ext: { kind: 'object' | 'array'; name: string }): boolean {\n return this._extensions[ext.kind].has(ext.name);\n }\n\n /**\n * This is an internal method used to register behaviors for legacy mode.\n * It is not intended for public use.\n *\n * We do think a generalized `kind` registration system would be useful,\n * but we have not yet designed it.\n *\n * See https://github.com/warp-drive-data/warp-drive/issues/9534\n *\n * @internal\n */\n _registerMode(mode: string, kinds: KindFns): void {\n assert(`Mode '${mode}' is already registered`, !this._modes.has(mode));\n this._modes.set(mode, kinds);\n }\n\n /**\n * This is an internal method used to enable legacy behaviors for legacy mode.\n * It is not intended for public use.\n *\n * We do think a generalized `kind` registration system would be useful,\n * but we have not yet designed it.\n *\n * See https://github.com/warp-drive-data/warp-drive/issues/9534\n *\n * @internal\n */\n _kind<T extends keyof KindFns>(mode: string, kind: T): KindFns[T] {\n assert(`Mode '${mode}' is not registered`, this._modes.has(mode));\n const kinds = this._modes.get(mode)!;\n assert(`Kind '${kind}' is not registered for mode '${mode}'`, kinds[kind]);\n return kinds[kind];\n }\n\n /**\n * Registers a {@link HashFn} for use with a {@link HashField} for\n * either {@link ObjectSchema} identity or polymorphic type calculation.\n *\n * @public\n */\n registerHashFn<T extends object>(hashFn: HashFn<T>): void {\n this._hashFns.set(hashFn[Type], hashFn as HashFn);\n }\n\n fields({ type }: { type: string }): InternalSchema['fields'] {\n const schema = this._schemas.get(type);\n assert(`No schema defined for ${type}`, schema);\n\n if (!schema.finalized) {\n finalizeResource(this, schema);\n }\n\n return schema.fields;\n }\n\n cacheFields({ type }: { type: string }): InternalSchema['cacheFields'] {\n const schema = this._schemas.get(type);\n assert(`No schema defined for ${type}`, schema);\n\n if (!schema.finalized) {\n finalizeResource(this, schema);\n }\n\n return schema.cacheFields;\n }\n\n hasResource(resource: { type: string }): boolean {\n return this._schemas.has(resource.type);\n }\n}\n\nif (ENABLE_LEGACY_SCHEMA_SERVICE) {\n SchemaService.prototype.attributesDefinitionFor = function ({\n type,\n }: {\n type: string;\n }): InternalSchema['attributes'] {\n deprecate(`Use \\`schema.fields({ type })\\` instead of \\`schema.attributesDefinitionFor({ type })\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n const schema = this._schemas.get(type);\n\n if (!schema) {\n throw new Error(`No schema defined for ${type}`);\n }\n\n return schema.attributes;\n };\n\n SchemaService.prototype.relationshipsDefinitionFor = function ({\n type,\n }: {\n type: string;\n }): InternalSchema['relationships'] {\n deprecate(`Use \\`schema.fields({ type })\\` instead of \\`schema.relationshipsDefinitionFor({ type })\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n const schema = this._schemas.get(type);\n\n if (!schema) {\n throw new Error(`No schema defined for ${type}`);\n }\n\n return schema.relationships;\n };\n\n SchemaService.prototype.doesTypeExist = function (type: string): boolean {\n deprecate(`Use \\`schema.hasResource({ type })\\` instead of \\`schema.doesTypeExist(type)\\``, false, {\n id: 'ember-data:schema-service-updates',\n until: '6.0',\n for: 'ember-data',\n since: {\n available: '4.13',\n enabled: '5.4',\n },\n });\n return this._schemas.has(type);\n };\n}\n\n/**\n * When we finalize a resource, we walk its traits and apply their fields\n * to the resource's fields.\n *\n * Traits are applied left-to-right, with traits of traits being applied in the same\n * way. Thus for the most part, application of traits is a post-order graph traversal\n * problem.\n *\n * A trait is only ever processed once. If multiple traits (A, B, C) have the same\n * trait (D) as a dependency, D will be included only once when first encountered by\n * A.\n *\n * If a cycle exists such that trait A has trait B which has Trait A, trait A will\n * be applied *after* trait B in production. In development a cycle error will be thrown.\n *\n * Fields are finalized on a \"last wins principle\". Thus traits appearing higher in\n * the tree and further to the right of a traits array take precedence, with the\n * resource's fields always being applied last and winning out.\n */\nfunction finalizeResource(schema: SchemaService, resource: InternalSchema): void {\n const fields: Map<string, FieldSchema> = new Map();\n const seen: Set<InternalTrait> = new Set();\n\n for (const traitName of resource.traits) {\n const trait = schema._traits.get(traitName);\n assert(\n `The trait ${traitName} MUST be supplied before the resource ${resource.original.type} can be finalized for use.`,\n trait\n );\n\n walkTrait(schema, trait, fields, seen, resource.original.type, DEBUG ? [] : null);\n }\n\n mergeMap(fields, resource.fields);\n resource.fields = fields;\n resource.cacheFields = getCacheFields(resource);\n resource.finalized = true;\n}\n\nfunction getCacheFields(resource: InternalSchema) {\n const { fields } = resource;\n const cacheFields = new Map<string, Exclude<CacheableFieldSchema, IdentityField>>();\n for (const [key, value] of fields) {\n if (isNonIdentityCacheableField(value)) {\n assert(\n `The sourceKey '${value.sourceKey}' for the field '${key}' on ${resource.original.type} is invalid because it matches the name of an existing field`,\n !value.sourceKey || value.sourceKey === key || !fields.has(value.sourceKey)\n );\n const cacheKey = getFieldCacheKeyStrict(value);\n cacheFields.set(cacheKey, value);\n }\n }\n return cacheFields;\n}\n\nfunction walkTrait(\n schema: SchemaService,\n trait: InternalTrait,\n fields: Map<string, FieldSchema>,\n seen: Set<InternalTrait>,\n type: string,\n debugPath: string[] | null\n): void {\n if (seen.has(trait)) {\n // if the trait is in the current path, we throw a cycle error in dev.\n if (DEBUG) {\n if (debugPath!.includes(trait.name)) {\n throw new Error(\n `CycleError: The Trait '${trait.name}' utilized by the Resource '${type}' includes the following circular reference \"${debugPath!.join(' > ')} > ${trait.name}\"`\n );\n }\n }\n return;\n }\n const ownPath = DEBUG ? [...debugPath!, trait.name] : null;\n\n // immediately mark as seen to prevent cycles\n // further down the tree from looping back\n seen.add(trait);\n\n // first apply any child traits\n if (trait.traits?.length) {\n for (const traitName of trait.traits) {\n const subtrait = schema._traits.get(traitName);\n if (ENFORCE_STRICT_RESOURCE_FINALIZATION) {\n assert(\n `The trait ${traitName} used by the trait ${trait.name} MUST be supplied before the resource ${type} can be finalized for use.`,\n subtrait\n );\n } else {\n warn(\n `The trait ${traitName} used by the trait ${trait.name} MUST be supplied before the resource ${type} can be finalized for use.`,\n !!subtrait,\n {\n id: 'warp-drive:missing-trait-schema-for-resource',\n }\n );\n }\n if (!subtrait) continue;\n walkTrait(schema, subtrait, fields, seen, type, ownPath);\n }\n }\n\n // then apply our own fields\n mergeMap(fields, trait.fields);\n}\n\nfunction mergeMap(base: Map<string, unknown>, toApply: Map<string, unknown>) {\n for (const [key, value] of toApply) {\n base.set(key, value);\n }\n}\n","/**\n * # About\n *\n * This module provides an implementation of reactive objects that a Store may use for creating\n * reactive representations of the raw data for requests, resources and their relationships\n * stored in the cache.\n *\n * - For configuring the store to use these reactive objects, see [The Setup Guide](/guides/configuration/)\n * - For defining resource schemas, see [The Schema Guide](/guides/the-manual/schemas/)\n *\n * Any method that returns a record instance will use the `instantiateRecord`\n * hook configured above to instantiate a ReactiveResource once this is in place.\n * After that, its up to you what ReactiveResource can do.\n *\n * ## Modes\n *\n * ReactiveResource has two modes: `legacy` and `polaris`.\n *\n * **LegacyMode** can be used to emulate the behaviors and capabilities of WarpDrive's `Model` class,\n * and because there is little distinction between Model and a ReactiveResource in LegacyMode we refer\n * to both of these approaches as LegacyMode. This mode is the default experience in V5.\n *\n * In LegacyMode:\n *\n * - records are mutable\n * - local changes immediately reflect app wide\n * - records have all the APIs of Model (references, state props, currentState, methods etc)\n * - the continued use of `@warp-drive/legacy` is required (though most imports from it can be removed)\n * - `async: true` relationships are supported (but not recommended outside of [LinksMode](/guides/the-manual/misc/links-mode.md))\n *\n * ---\n *\n * **PolarisMode** is an upcoming suite of features that will become the default experience in V6.\n *\n * In PolarisMode:\n *\n * - records are immutable, unless creating a new resource or explicitly checking out a record for editing\n * - local changes are isolated until committed, displaying only via the editable version of the record\n * - records have a more limited API, focused on only what is in their schema.\n * - some common operations may have more friction to perform because intended utilities are not yet available\n * - `async: true` relationships are not supported (see [LinksMode](/guides/the-manual/misc/links-mode.md))\n * - The `@warp-drive/legacy` package is not required\n *\n * These modes are interopable. The reactive object (record) for a resource in PolarisMode can relate to\n * a record in LegacyMode and vice-versa. This interopability is true whether the record in LegacyMode is\n * a ReactiveResource or a Model.\n *\n * ---\n *\n * ## Basic Usage\n *\n * ReactiveResource is a reactive object that transforms raw data from an associated\n * cache into reactive data backed by Signals.\n *\n * The shape of the object and the transformation of raw cache data into its\n * reactive form is controlled by a resource schema.\n *\n * For instance, lets say your API is a [{json:api}](https://jsonapi.org) and your store is using\n * the Cache provided by {@link @warp-drive/json-api! | @warp-drive/json-api}, and a request\n * returns the following raw data:\n *\n * ```ts\n * {\n * data: {\n * type: 'user',\n * id: '1',\n * attributes: { firstName: 'Chris', lastName: 'Thoburn' },\n * relationships: { pets: { data: [{ type: 'dog', id: '1' }] }}\n * },\n * included: [\n * {\n * type: 'dog',\n * id: '1',\n * attributes: { name: 'Rey' },\n * relationships: { owner: { data: { type: 'user', id: '1' }}}\n * }\n * ]\n * }\n * ```\n *\n * We could describe the `'user'` and `'dog'` resources in the above payload\n * with the following schemas:\n *\n * ```ts\n * store.schema.registerResources([\n * {\n * type: 'user',\n * identity: { type: '@id', name: 'id' },\n * fields: [\n * {\n * type: '@identity',\n * name: '$type',\n * kind: 'derived',\n * options: { key: 'type' },\n * },\n * { kind: 'field', name: 'firstName' },\n * { kind: 'field', name: 'lastName' },\n * {\n * kind: 'derived',\n * name: 'name',\n * type: 'concat',\n * options: { fields: ['firstName', 'lastName'], separator: ' ' }\n * },\n * {\n * kind: 'hasMany',\n * name: 'pets',\n * type: 'pet',\n * options: {\n * async: false,\n * inverse: 'owner',\n * polymorphic: true,\n * linksMode: true,\n * }\n * }\n * ]\n * },\n * {\n * type: 'dog',\n * identity: { type: '@id', name: 'id' },\n * fields: [\n * {\n * type: '@identity',\n * name: '$type',\n * kind: 'derived',\n * options: { key: 'type' },\n * },\n * { kind: 'field', name: 'name' },\n * {\n * kind: 'belongsTo',\n * name: 'owner',\n * type: 'user',\n * options: {\n * async: false,\n * inverse: 'pets',\n * as: 'pet',\n * linksMode: true,\n * }\n * }\n * ]\n * }\n * ]);\n * ```\n *\n * With these schemas in place, the reactive objects that the store would\n * provide us whenever we encountered a `'user'` or a `'dog'` would be:\n *\n * ```ts\n * interface Pet {\n * readonly id: string;\n * readonly owner: User;\n * }\n *\n * interface Dog extends Pet {\n * readonly $type: 'dog';\n * readonly name: string;\n * }\n *\n * interface EditableUser {\n * readonly $type: 'user';\n * readonly id: string;\n * firstName: string;\n * lastName: string;\n * readonly name: string;\n * pets: Array<Dog | Pet>;\n * }\n *\n * interface User {\n * readonly $type: 'user';\n * readonly id: string;\n * readonly firstName: string;\n * readonly lastName: string;\n * readonly name: string;\n * readonly pets: Readonly<Array<Dog | Pet>>;\n * [Checkout](): Promise<EditableUser>\n * }>\n * ```\n *\n * Note how based on the schema the reactive object we receive is able to produce\n * `name` on user (despite no name field being in the cache), provide `$type`\n * pulled from the identity of the resource, and flatten the individual attributes\n * and relationships onto the record for easier use.\n *\n * Notice also how we typed this object with `readonly`. This is because while\n * ReactiveResource instances are ***deeply reactive***, they are also ***immutable***.\n *\n * We can mutate a ReactiveResource only be explicitly asking permission to do so, and\n * in the process gaining access to an editable copy. The immutable version will\n * not show any in-process edits made to this editable copy.\n *\n * ```ts\n * import { Checkout } from '@warp-drive/schema-record';\n *\n * const editable = await user[Checkout]();\n * ```\n *\n * ## Utilities\n *\n * ReactiveResource provides a schema builder that simplifies setting up a couple of\n * conventional fields like identity and `$type`. We can rewrite the schema\n * definition above using this utility like so:\n *\n * ```ts\n * import { withDefaults } from '@warp-drive/core/reactive';\n *\n * store.schema.registerResources([\n * withDefaults({\n * type: 'user',\n * fields: [\n * { kind: 'field', name: 'firstName' },\n * { kind: 'field', name: 'lastName' },\n * {\n * kind: 'derived',\n * name: 'name',\n * type: 'concat',\n * options: { fields: ['firstName', 'lastName'], separator: ' ' }\n * },\n * {\n * kind: 'hasMany',\n * name: 'pets',\n * type: 'pet',\n * options: {\n * async: false,\n * inverse: 'owner',\n * polymorphic: true,\n * linksMode: true,\n * resetOnRemoteUpdate: false,\n * }\n * }\n * ]\n * }),\n * withDefaults({\n * type: 'dog',\n * fields: [\n * { kind: 'field', name: 'name' },\n * {\n * kind: 'belongsTo',\n * name: 'owner',\n * type: 'user',\n * options: {\n * async: false,\n * inverse: 'pets',\n * as: 'pet',\n * linksMode: true,\n * resetOnRemoteUpdate: false,\n * }\n * }\n * ]\n * })\n * ]);\n * ```\n *\n * ## Type Support\n *\n * ### Resource Schemas\n *\n * - {@link PolarisResourceSchema}\n * - {@link LegacyResourceSchema}\n * - {@link ObjectSchema}\n *\n * ### Resource Schema Type Utils\n *\n * - {@link resourceSchema}\n * - {@link objectSchema}\n * - {@link isResourceSchema}\n * - {@link isLegacyResourceSchema}\n *\n * ### Field Schemas\n *\n * - {@link LegacyModeFieldSchema}\n * - {@link PolarisModeFieldSchema}\n *\n * @module\n */\nimport { checkout } from './reactive/-private/record.ts';\nimport type {\n // oxlint-disable-next-line no-unused-vars\n isLegacyResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n isResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n LegacyModeFieldSchema,\n // oxlint-disable-next-line no-unused-vars\n LegacyResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n ObjectSchema,\n // oxlint-disable-next-line no-unused-vars\n objectSchema,\n // oxlint-disable-next-line no-unused-vars\n PolarisModeFieldSchema,\n // oxlint-disable-next-line no-unused-vars\n PolarisResourceSchema,\n // oxlint-disable-next-line no-unused-vars\n resourceSchema,\n} from './types/schema/fields';\n\nexport { instantiateRecord, teardownRecord } from './reactive/-private/hooks';\nexport {\n type CAUTION_MEGA_DANGER_ZONE_Extension,\n type ProcessedExtension,\n type ExtensionDef,\n type Transformation,\n SchemaService,\n withDefaults,\n fromIdentity,\n registerDerivations,\n} from './reactive/-private/schema';\nexport { commit, type ReactiveResource } from './reactive/-private/record.ts';\n\nexport { checkout };\nexport {\n /** @deprecated use {@link checkout} */\n Checkout,\n} from './reactive/-private/symbols';\nexport {\n type ReactiveDocument,\n type ReactiveDataDocument,\n type ReactiveErrorDocument,\n} from './reactive/-private/document';\nexport {\n createRequestSubscription,\n getRequestState,\n type RequestSubscription,\n type RequestLoadingState,\n type RequestState,\n} from './signals/-private';\n\nexport {\n getPromiseState,\n type PromiseState,\n type ResolvedPromise,\n type RejectedPromise,\n type PendingPromise,\n} from './signals/-private.ts';\n\nexport type { LegacyLiveArray } from './store/-private/record-arrays/legacy-live-array.ts';\nexport type { LegacyManyArray } from './store/-private/record-arrays/legacy-many-array.ts';\nexport type { LegacyQueryArray } from './store/-private/record-arrays/legacy-query.ts';\nexport type { ReactiveResourceArray } from './store/-private/record-arrays/resource-array.ts';\n","import { DEBUG } from '@warp-drive/core/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { getRuntimeConfig } from '../../types/runtime.ts';\nimport { cloneResponseProperties, type Context } from './context';\nimport { DOMError, type FetchError } from './utils';\n\nexport type { FetchError };\n\ninterface FastbootRequest extends Request {\n protocol: string;\n host: string;\n}\nexport interface FastBoot {\n require(moduleName: string): unknown;\n isFastBoot: boolean;\n request: FastbootRequest;\n}\n\n// Lazily close over fetch to avoid breaking Mirage\nconst _fetch: typeof fetch =\n typeof fetch !== 'undefined'\n ? (...args) => fetch(...args)\n : typeof FastBoot !== 'undefined'\n ? (...args) => ((FastBoot as FastBoot).require('node-fetch') as typeof fetch)(...args)\n : () => {\n throw new Error('No Fetch Implementation Found');\n };\n\n// clones a response in a way that should still\n// allow it to stream\nfunction cloneResponse(response: Response, overrides: Partial<Response>) {\n const props = cloneResponseProperties(response);\n return new Response(response.body, Object.assign(props, overrides));\n}\n\nfunction withDateHeader(response: Response): Response {\n const headers = new Headers(response.headers);\n headers.set('date', new Date().toUTCString());\n return cloneResponse(response, { headers });\n}\n\n// Detects Mirage (or another Pretender-based fetch mock), whose `Response`\n// may (unlike a spec-compliant `fetch()`, whose Response headers are always\n// immutable) allow header mutation and may not support streaming reads.\n//\n// This is inherently a heuristic - many legitimate tools (APM/monitoring\n// agents, browser extensions, polyfills) also patch `window.fetch`, and can\n// produce false positives. `setWarpDriveIsMaybeMirage(value)` lets an app\n// declare the answer explicitly (`true` or `false`), overriding the\n// heuristic in either direction; leave it unset to keep the default\n// detection. See https://github.com/warp-drive-data/warp-drive/issues/10535\nlet IS_MAYBE_MIRAGE = () => false;\nif (DEBUG) {\n IS_MAYBE_MIRAGE = () => {\n const override = getRuntimeConfig().mirage;\n if (override !== undefined) {\n return override;\n }\n return Boolean(\n typeof window !== 'undefined' &&\n ((window as { server?: { pretender: unknown } }).server?.pretender ||\n window.fetch.toString().replace(/\\s+/g, '') !== 'function fetch() { [native code] }'.replace(/\\s+/g, ''))\n );\n };\n}\n\nconst MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);\nconst ERROR_STATUS_CODE_FOR = new Map([\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [402, 'Payment Required'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [405, 'Method Not Allowed'],\n [406, 'Not Acceptable'],\n [407, 'Proxy Authentication Required'],\n [408, 'Request Timeout'],\n [409, 'Conflict'],\n [410, 'Gone'],\n [411, 'Length Required'],\n [412, 'Precondition Failed'],\n [413, 'Payload Too Large'],\n [414, 'URI Too Long'],\n [415, 'Unsupported Media Type'],\n [416, 'Range Not Satisfiable'],\n [417, 'Expectation Failed'],\n [419, 'Page Expired'],\n [420, 'Enhance Your Calm'],\n [421, 'Misdirected Request'],\n [422, 'Unprocessable Entity'],\n [423, 'Locked'],\n [424, 'Failed Dependency'],\n [425, 'Too Early'],\n [426, 'Upgrade Required'],\n [428, 'Precondition Required'],\n [429, 'Too Many Requests'],\n [430, 'Request Header Fields Too Large'],\n [431, 'Request Header Fields Too Large'],\n [450, 'Blocked By Windows Parental Controls'],\n [451, 'Unavailable For Legal Reasons'],\n [500, 'Internal Server Error'],\n [501, 'Not Implemented'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n [505, 'HTTP Version Not Supported'],\n [506, 'Variant Also Negotiates'],\n [507, 'Insufficient Storage'],\n [508, 'Loop Detected'],\n [509, 'Bandwidth Limit Exceeded'],\n [510, 'Not Extended'],\n [511, 'Network Authentication Required'],\n]);\n\n/**\n * ```ts\n * import { Fetch } from '@warp-drive/core';\n * ```\n *\n * A basic Fetch Handler which converts a request into a\n * `fetch` call presuming the response to be `json`.\n *\n * ```ts\n * import { RequestManager, Fetch } from '@warp-drive/core';\n *\n * const manager = new RequestManager()\n * .use([Fetch]);\n * ```\n *\n * @public\n * @badge Handler\n */\nconst Fetch = {\n /**\n * Issues the request via native `fetch`, setting the response and\n * (when requested) streaming the decoded body via {@link Context.setStream}\n * as it downloads, then resolves with the parsed JSON body.\n *\n * @public\n */\n async request<T>(context: Context): Promise<T> {\n let response: Response;\n\n try {\n assert(\n 'The Fetch handler expects the request to have a URL, none was provided.',\n context.request.url && typeof context.request.url === 'string'\n );\n response = await _fetch(context.request.url, context.request);\n } catch (e) {\n const isDOMException = e instanceof DOMError;\n if (isDOMException && e.name === 'AbortError') {\n (e as FetchError).statusText = 'Aborted';\n (e as FetchError).status = 20;\n (e as FetchError).isRequestError = true;\n } else {\n (e as FetchError).statusText = 'Unknown Network Error';\n (e as FetchError).status = 0;\n if (!isDOMException) {\n (e as FetchError).code = 0;\n }\n (e as FetchError).isRequestError = true;\n }\n throw e;\n }\n\n const isError = !response.ok || response.status >= 400;\n const op = context.request.op;\n const isMutationOp = Boolean(op && MUTATION_OPS.has(op));\n\n if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {\n if (IS_MAYBE_MIRAGE()) {\n try {\n response.headers.set('date', new Date().toUTCString());\n } catch {\n // IS_MAYBE_MIRAGE() was a false positive, or the mock's headers\n // are (correctly) immutable - fall back to cloning.\n response = withDateHeader(response);\n }\n } else {\n response = withDateHeader(response);\n }\n }\n\n context.setResponse(response);\n\n if (response.status === 204 || context.request.method === 'HEAD') {\n return null as T;\n }\n\n let text = '';\n // if we are in a mirage context, we cannot support streaming\n if (IS_MAYBE_MIRAGE()) {\n text = await response.text();\n } else {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let isStreaming = context.hasRequestedStream;\n let stream: TransformStream | null = isStreaming ? new TransformStream() : null;\n let writer = stream?.writable.getWriter();\n\n if (isStreaming) {\n // Listen for the abort event on the AbortSignal\n context.request.signal?.addEventListener('abort', () => {\n if (!isStreaming) {\n return;\n }\n void stream!.writable.abort('Request Aborted');\n void stream!.readable.cancel('Request Aborted');\n });\n context.setStream(stream!.readable);\n }\n\n while (true) {\n // we manually read the stream instead of using `response.json()`\n // or `response.text()` because if we need to stream the body\n // we need to be able to pass the stream along efficiently.\n const { done, value } = await reader.read();\n if (done) {\n if (isStreaming) {\n isStreaming = false;\n await writer!.ready;\n await writer!.close();\n }\n break;\n }\n text += decoder.decode(value, { stream: true });\n\n // if we are streaming, we want to pass the stream along\n if (isStreaming) {\n await writer!.ready;\n await writer!.write(value);\n } else if (context.hasRequestedStream) {\n const encode = new TextEncoder();\n isStreaming = true;\n stream = new TransformStream();\n // Listen for the abort event on the AbortSignal\n // oxlint-disable-next-line no-loop-func\n context.request.signal?.addEventListener('abort', () => {\n if (!isStreaming) {\n return;\n }\n void stream!.writable.abort('Request Aborted');\n void stream!.readable.cancel('Request Aborted');\n });\n context.setStream(stream.readable);\n writer = stream.writable.getWriter();\n await writer.ready;\n await writer.write(encode.encode(text));\n await writer.ready;\n await writer.write(value);\n }\n }\n\n if (isStreaming) {\n isStreaming = false;\n await writer!.ready;\n await writer!.close();\n }\n }\n // if we are an error, we will want to throw\n if (isError) {\n let errorPayload: object | undefined;\n try {\n errorPayload = JSON.parse(text) as object;\n } catch {\n // void;\n }\n // attempt errors discovery\n const errors = Array.isArray(errorPayload)\n ? errorPayload\n : isDict(errorPayload) && Array.isArray(errorPayload.errors)\n ? errorPayload.errors\n : null;\n\n const statusText = response.statusText || ERROR_STATUS_CODE_FOR.get(response.status) || 'Unknown Request Error';\n const msg = `[${response.status} ${statusText}] ${context.request.method ?? 'GET'} (${response.type}) - ${\n response.url\n }`;\n\n const error = (errors ? new AggregateError(errors, msg) : new Error(msg)) as Error & {\n content: object | undefined;\n } & FetchError;\n error.status = response.status;\n error.statusText = statusText;\n error.isRequestError = true;\n error.code = error.status;\n error.name = error.statusText.replaceAll(' ', '') + 'Error';\n error.content = errorPayload;\n throw error;\n } else {\n return JSON.parse(text) as T;\n }\n },\n};\n\nfunction isDict(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object';\n}\n\nexport { Fetch };\n","import { DEBUG, TESTING } from '@warp-drive/core/build-config/env';\n\nimport { waitFor } from '../../signals/-private';\nimport { peekUniversalTransient, setUniversalTransient } from '../../types/-private';\nimport type { RequestKey } from '../../types/identifier';\nimport { EnableHydration, type RequestInfo, type StructuredErrorDocument } from '../../types/request';\nimport { assertValidRequest } from './debug';\nimport { upgradePromise } from './future';\nimport { clearRequestResult, getRequestResult, setPromiseResult } from './promise-cache';\nimport type { CacheHandler, Future, GenericCreateArgs, GodContext, Handler, ManagedRequestPriority } from './types';\nimport { executeNextHandler, IS_CACHE_HANDLER } from './utils';\n\n/**\n * ## Import\n *\n * ```js\n * import { RequestManager } from '@warp-drive/core';\n * ```\n *\n * For complete usage guide see the [RequestManager Documentation](/guides/).\n *\n * ## How It Works\n *\n * ```ts\n * interface RequestManager {\n * request<T>(req: RequestInfo): Future<T>;\n * }\n * ```\n *\n * A RequestManager provides a request/response flow in which configured\n * handlers are successively given the opportunity to handle, modify, or\n * pass-along a request.\n *\n * <img src=\"/images/handlers-all-labeled.gif\" alt=\"RequestManager Flow Animation\" width=\"100%\" />\n *\n * For example:\n *\n * ::: code-group\n *\n * ```ts [Setup.ts]\n * import { RequestManager, Fetch } from '@warp-drive/core';\n * import { AutoCompress } from '@warp-drive/utilities/handlers';\n * import Auth from 'ember-simple-auth/handler';\n *\n * // ... create manager\n * const manager = new RequestManager()\n * .use([Auth, new AutoCompress(), Fetch]); // [!code focus]\n * ```\n *\n * ```ts [Usage.ts]\n * import Config from './config';\n *\n * const { apiUrl } = Config;\n *\n * // ... execute a request\n * const response = await manager.request({\n * url: `${apiUrl}/users`\n * });\n * ```\n *\n * :::\n *\n * ### Futures\n *\n * The return value of `manager.request` is a `Future`, which allows\n * access to limited information about the request while it is still\n * pending and fulfills with the final state when the request completes.\n *\n * A `Future` is cancellable via `abort`.\n *\n * Handlers may optionally expose a `ReadableStream` to the `Future` for\n * streaming data; however, when doing so the future should not resolve\n * until the response stream is fully read.\n *\n * ```ts\n * interface Future<T> extends Promise<StructuredDocument<T>> {\n * abort(): void;\n *\n * async getStream(): ReadableStream | null;\n * }\n * ```\n *\n * ### StructuredDocuments\n *\n * A Future resolves with a `StructuredDataDocument` or rejects with a `StructuredErrorDocument`.\n *\n * ```ts\n * interface StructuredDataDocument<T> {\n * request: ImmutableRequestInfo;\n * response: ImmutableResponseInfo;\n * content: T;\n * }\n * interface StructuredErrorDocument extends Error {\n * request: ImmutableRequestInfo;\n * response: ImmutableResponseInfo;\n * error: string | object;\n * }\n * type StructuredDocument<T> = StructuredDataDocument<T> | StructuredErrorDocument;\n * ```\n *\n * @public\n */\nexport class RequestManager {\n /** @internal */\n declare private _handlers: Handler[];\n /** @internal */\n declare private _hasCacheHandler: boolean;\n /**\n * A map of pending requests from request.id to their\n * associated CacheHandler promise.\n *\n * This queue is managed by the CacheHandler\n *\n * @internal\n */\n declare _pending: Map<number, Promise<unknown>>;\n /** @internal */\n declare _deduped: Map<RequestKey, { priority: ManagedRequestPriority; promise: Promise<unknown> }>;\n\n constructor(options?: GenericCreateArgs) {\n Object.assign(this, options);\n this._pending = new Map();\n this._deduped = new Map();\n this._handlers = [];\n }\n\n /**\n * Register a handler to use for primary cache intercept.\n *\n * Only one such handler may exist. If using the same\n * RequestManager as the Store instance the Store\n * registers itself as a Cache handler.\n *\n * @public\n */\n useCache(cacheHandler: CacheHandler & { [IS_CACHE_HANDLER]?: true }): this {\n if (DEBUG) {\n if (this._hasCacheHandler) {\n throw new Error(`\\`RequestManager.useCache(<handler>)\\` May only be invoked once.`);\n }\n if (Object.isFrozen(this._handlers)) {\n throw new Error(\n `\\`RequestManager.useCache(<handler>)\\` May only be invoked prior to any request having been made.`\n );\n }\n this._hasCacheHandler = true;\n }\n cacheHandler[IS_CACHE_HANDLER] = true;\n this._handlers.unshift(cacheHandler as Handler);\n return this;\n }\n\n /**\n * Register handler(s) to use when a request is issued.\n *\n * Handlers will be invoked in the order they are registered.\n * Each Handler is given the opportunity to handle the request,\n * curry the request, or pass along a modified request.\n *\n * @public\n */\n use(newHandlers: Handler[]): this {\n const handlers = this._handlers;\n if (DEBUG) {\n if (Object.isFrozen(handlers)) {\n throw new Error(`Cannot add a Handler to a RequestManager after a request has been made`);\n }\n if (!Array.isArray(newHandlers)) {\n throw new Error(\n `\\`RequestManager.use(<Handler[]>)\\` expects an array of handlers, but was called with \\`${typeof newHandlers}\\``\n );\n }\n newHandlers.forEach((handler, index) => {\n if (\n !handler ||\n (typeof handler !== 'function' && typeof handler !== 'object') ||\n typeof handler.request !== 'function'\n ) {\n throw new Error(\n `\\`RequestManager.use(<Handler[]>)\\` expected to receive an array of handler objects with request methods, by the handler at index ${index} does not conform.`\n );\n }\n });\n }\n handlers.push(...newHandlers);\n return this;\n }\n\n /**\n * Issue a Request.\n *\n * Returns a Future that fulfills with a StructuredDocument\n *\n * @public\n */\n request<RT>(request: RequestInfo<RT>): Future<RT> {\n const handlers = this._handlers;\n if (DEBUG) {\n if (!Object.isFrozen(handlers)) {\n Object.freeze(handlers);\n }\n assertValidRequest(request, true);\n }\n\n const controller = request.controller || new AbortController();\n if (request.controller) {\n delete request.controller;\n }\n\n const requestId = peekUniversalTransient<number>('REQ_ID') ?? 0;\n setUniversalTransient('REQ_ID', requestId + 1);\n\n const context = {\n controller,\n response: null,\n stream: null,\n hasRequestedStream: false,\n id: requestId,\n identifier: null,\n requester: request[EnableHydration] && request.store ? request.store : this,\n } satisfies GodContext;\n const promise = executeNextHandler<RT>(handlers, request, 0, context);\n\n // the cache handler will set the result of the request synchronously\n // if it is able to fulfill the request from the cache\n const cacheResult = getRequestResult(requestId);\n\n if (TESTING) {\n if (!request.disableTestWaiter) {\n const newPromise = waitFor(promise);\n const finalPromise = upgradePromise(\n newPromise.then(\n (result) => {\n setPromiseResult(finalPromise, { isError: false, result });\n clearRequestResult(requestId);\n return result;\n },\n (error: StructuredErrorDocument) => {\n setPromiseResult(finalPromise, { isError: true, result: error });\n clearRequestResult(requestId);\n throw error;\n }\n ),\n promise\n );\n\n if (cacheResult) {\n setPromiseResult(finalPromise, cacheResult);\n }\n\n return finalPromise;\n }\n }\n\n // const promise1 = store.request(myRequest);\n // const promise2 = store.request(myRequest);\n // promise1 === promise2; // false\n // either we need to make promise1 === promise2, or we need to make sure that\n // we need to have a way to key from request to result\n // such that we can lookup the result here and return it if it exists\n const finalPromise = upgradePromise(\n promise.then(\n (result) => {\n setPromiseResult(finalPromise, { isError: false, result });\n clearRequestResult(requestId);\n return result;\n },\n (error: StructuredErrorDocument) => {\n setPromiseResult(finalPromise, { isError: true, result: error });\n clearRequestResult(requestId);\n throw error;\n }\n ),\n promise\n );\n\n if (cacheResult) {\n setPromiseResult(finalPromise, cacheResult);\n }\n\n return finalPromise;\n }\n\n /**\n * This method exists so that the RequestManager can be created\n * can be created by container/factory systems that expect to\n * call a static `create` method to instantiate the class.\n *\n * Using `new RequestManager()` directly is preferred.\n *\n * @private\n */\n static create(options?: GenericCreateArgs): RequestManager {\n return new this(options);\n }\n}\n\n/**\n * This type exists for internal use only for\n * where intimate contracts still exist either for\n * the Test Suite or for Legacy code.\n *\n * @private\n */\nexport interface PrivateRequestManager extends RequestManager {\n /**\n * A map of pending requests from request.id to their\n * associated CacheHandler promise.\n *\n * This queue is managed by the CacheHandler\n *\n */\n _pending: Map<number, Promise<unknown>>;\n _deduped: Map<RequestKey, { priority: ManagedRequestPriority; promise: Promise<unknown> }>;\n}\n","/**\n * @module\n * @mergeModuleWith <project>\n */\n\nimport { TESTING } from '@warp-drive/build-config/env';\n\nimport type { CAUTION_MEGA_DANGER_ZONE_Extension } from './reactive.ts';\nimport { instantiateRecord, registerDerivations, SchemaService, teardownRecord } from './reactive.ts';\nimport type { ReactiveDocument } from './reactive/-private/document.ts';\nimport type { Handler } from './request.ts';\nimport { Fetch } from './request/-private/fetch.ts';\nimport { RequestManager } from './request/-private/manager.ts';\nimport { DefaultCachePolicy } from './store.ts';\nimport { CacheHandler, type CachePolicy, Store, recordIdentifierFor } from './store/-private.ts';\nimport type { CacheCapabilitiesManager, ResourceKey } from './types.ts';\nimport type { Cache } from './types/cache.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { RequestInfo } from './types/request.ts';\nimport { getRuntimeConfig, setIsMaybeMirage, setLogging } from './types/runtime.ts';\nimport type { Derivation, HashFn, Transformation } from './types/schema/concepts.ts';\nimport type { ObjectSchema, PolarisResourceSchema, Trait } from './types/schema/fields.ts';\n\nexport { recordIdentifierFor, recordIdentifierFor as cacheKeyFor };\n\nexport { Fetch, RequestManager };\n\nif (TESTING) {\n // @ts-expect-error adding to globalThis\n globalThis.setWarpDriveLogging = setLogging;\n\n // @ts-expect-error adding to globalThis\n globalThis.getWarpDriveRuntimeConfig = getRuntimeConfig;\n}\n\n// Mirage (or another Pretender-based fetch mock) may be used outside of a\n// `TESTING` build (e.g. `ember serve` in dev mode), so this override is\n// exposed unconditionally rather than gated to the `TESTING` env.\n// @ts-expect-error adding to globalThis\nglobalThis.setWarpDriveIsMaybeMirage = setIsMaybeMirage;\n\nexport { Store, CacheHandler, type CachePolicy };\n\nexport { type StoreRequestContext, type StoreRequestInput, storeFor } from './store/-private.ts';\n\n/**\n * @deprecated use {@link ReactiveDocument} instead\n */\nexport type Document<T> = ReactiveDocument<T>;\n\nexport type {\n DocumentCacheOperation,\n CacheOperation,\n NotificationChannel,\n NotificationType,\n NotifyKeys,\n} from './store/-private/managers/notification-manager.ts';\n\nexport {\n setIdentifierGenerationMethod,\n setIdentifierUpdateMethod,\n setIdentifierForgetMethod,\n setIdentifierResetMethod,\n setKeyInfoForResource,\n} from './store/-private/managers/cache-key-manager.ts';\n\n/**\n * Options for setting up a Store instance with `useRecommendedStore`.\n */\nexport interface StoreSetupOptions<T extends Cache = Cache> {\n /**\n * A constructor for the {@link Cache} implementation to use, receiving the\n * store's {@link CacheCapabilitiesManager} when instantiated.\n */\n cache: {\n /**\n * Constructs a new {@link Cache} instance for the store.\n */\n new (capabilities: CacheCapabilitiesManager): T;\n };\n /**\n * The Cache policy to use.\n *\n * Defaults to {@link DefaultCachePolicy} configured to\n * respect `Expires`, `X-WarpDrive-Expires`, and `Cache-Control` headers\n * with a fallback to 30s soft expiration and 15m hard expiration.\n */\n policy?: CachePolicy;\n /**\n * The request handlers to use. {@link Fetch} will automatically\n * be added to the end of the handler chain and {@link CacheHandler}\n * will automatically be added as the cache handler.\n *\n * May also be given as a function that receives the {@link Store} instance\n * and returns the handlers to use. This is useful when a handler needs\n * access to the store (e.g. to look up its owner for injections) or when\n * the set of handlers should be decided lazily (e.g. based on a feature\n * flag service that may not be ready until after the store is constructed).\n *\n * The function is invoked lazily, the first time the store's `requestManager`\n * is accessed, and only once per store instance.\n *\n * See the \"Adding Stateful Handlers\" section of {@link useRecommendedStore}\n * for an example of using this callback to construct a handler that needs\n * access to an Ember service.\n */\n handlers?: Handler[] | ((store: Store) => Handler[]);\n /**\n * Schemas describing the structure of your resource data.\n *\n * See {@link PolarisResourceSchema,} and {@link ObjectSchema} for more information.\n */\n schemas?: Array<PolarisResourceSchema | ObjectSchema>;\n /**\n * {@link Trait | Traits} to use with {@link PolarisResourceSchema, | Resource Schemas}\n */\n traits?: Trait[];\n /**\n * {@link Derivation | Derivations} to use for derived fields.\n */\n derivations?: Derivation[];\n /**\n * {@link Transformation | Transformations} to use for transforming fields.\n */\n transformations?: Transformation[];\n /**\n * {@link HashFn | Hash Functions} to use for embedded object identity and polymorphic type calculations\n */\n hashFns?: HashFn[];\n /**\n * {@link CAUTION_MEGA_DANGER_ZONE_Extension | Extensions} to use with resources, objects and arrays\n * to provide custom behaviors and capabilities that are not described by Schema.\n *\n * This feature should only be used during a transition period to support migrating towards\n * schemas from existing Model and ModelFragments implementations.\n */\n CAUTION_MEGA_DANGER_ZONE_extensions?: CAUTION_MEGA_DANGER_ZONE_Extension[];\n}\n\nexport declare class ConfiguredStore<\n T extends {\n /**\n * The {@link Cache} instance type this configured store's `createCache`\n * method produces.\n */\n cache: Cache;\n },\n Policy extends CachePolicy = CachePolicy,\n> extends Store {\n lifetimes: Policy;\n // get cache(): T extends OptionsWithCache<infer R> ? R : never;\n createCache(capabilities: CacheCapabilitiesManager): T['cache'];\n}\n\n/**\n * Creates a configured Store class with recommended defaults\n * for schema handling, reactivity, caching, and request management.\n *\n * ```ts\n * import { useRecommendedStore } from '@warp-drive/core';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * export const Store = useRecommendedStore({\n * cache: JSONAPICache,\n * schemas: [],\n * });\n * ```\n *\n * ### Adding Stateful Handlers\n *\n * A request {@link Handler} is sometimes more than a plain object or class with\n * a `request` method — it may need access to a stateful dependency such as an\n * Ember service (an auth token, a feature-flags service, an i18n helper, etc.).\n *\n * A plain class handler that only relies on Ember's `@service` decorator will\n * not work here on its own: the handler is never instantiated *through* Ember's\n * container (it's just `new`'d up), so it has no owner and its `@service`\n * injections would fail to resolve.\n *\n * Instead, give {@link StoreSetupOptions.handlers | handlers} a function. It\n * receives the {@link Store} instance being configured, which by the time the\n * function runs already has an owner assigned. Use `getOwner`/`setOwner` from\n * `@ember/owner` to transfer that owner onto your handler instance before\n * returning it, exactly as you would when constructing any other DI-aware\n * object outside of the container:\n *\n * ```ts\n * import { getOwner, setOwner } from '@ember/owner';\n * import { service } from '@ember/service';\n * import { useRecommendedStore } from '@warp-drive/core';\n * import type { NextFn } from '@warp-drive/core/request';\n * import type { RequestContext } from '@warp-drive/core/types/request';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * class AuthHandler {\n * @service session;\n *\n * request<T>(context: RequestContext, next: NextFn<T>) {\n * const headers = new Headers(context.request.headers);\n * headers.append('Authorization', `Bearer ${this.session.accessToken}`);\n * return next(Object.assign({}, context.request, { headers }));\n * }\n * }\n *\n * export default useRecommendedStore({\n * cache: JSONAPICache,\n * handlers: (store) => {\n * const authHandler = new AuthHandler();\n * setOwner(authHandler, getOwner(store)!);\n * return [authHandler];\n * },\n * });\n * ```\n *\n * The `handlers` function is invoked lazily and only once per store instance,\n * the first time `store.requestManager` is accessed, so it is safe to do\n * owner-dependent setup like this inside of it.\n *\n * ### Accessing the Store from a Handler's Context\n *\n * If a handler only needs to read something *off of the store itself*\n * (its cache, or a property/service you've attached to a custom store\n * subclass) rather than an unrelated Ember service, there is a second,\n * simpler option that requires no DI/`setOwner` wiring at all.\n *\n * Every request issued via {@link Store.request | store.request(...)}\n * automatically carries the originating store along as\n * {@link RequestInfo.store | context.request.store}. Any handler — a plain\n * object, a function-built handler, or a class — can read it directly,\n * without needing the `handlers` callback form shown above:\n *\n * ```ts\n * import { useRecommendedStore } from '@warp-drive/core';\n * import type { NextFn } from '@warp-drive/core/request';\n * import type { RequestContext } from '@warp-drive/core/types/request';\n * import { JSONAPICache } from '@warp-drive/json-api';\n *\n * const LoggingHandler = {\n * request<T>(context: RequestContext, next: NextFn<T>) {\n * // only present when the request was made via `store.request(...)`\n * const store = context.request.store;\n * if (store) {\n * console.log(`[${store.constructor.name}] ${context.request.url ?? ''}`);\n * }\n * return next(context.request);\n * },\n * };\n *\n * export default useRecommendedStore({\n * cache: JSONAPICache,\n * handlers: [LoggingHandler],\n * });\n * ```\n *\n * The trade-off versus the `getOwner`/`setOwner` pattern above is that\n * `context.request.store` is only populated for requests issued via\n * `store.request(...)`; a request made directly against a\n * {@link RequestManager} won't have it set unless the caller supplies it\n * explicitly, so a handler relying on it should treat it as optional (as\n * `LoggingHandler` does above).\n */\nexport function useRecommendedStore<T extends Cache, Policy extends CachePolicy>(\n options: StoreSetupOptions<T> & { policy: Policy },\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }, Policy>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T> & { policy?: undefined },\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }, DefaultCachePolicy>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T>,\n StoreKlass?: typeof Store\n): typeof ConfiguredStore<{ cache: T }>;\nexport function useRecommendedStore<T extends Cache>(\n options: StoreSetupOptions<T>,\n StoreKlass: typeof Store = Store\n): typeof ConfiguredStore<{ cache: T }> {\n return class AppStore extends StoreKlass {\n constructor(createArgs?: unknown) {\n super(createArgs);\n // installed via defineProperty (rather than a class field/accessor) so that\n // this lazy override of the inherited `requestManager` field does not\n // conflict with the documented pattern of assigning it directly on\n // consumer-authored Store subclasses. The setter preserves the ability\n // to replace `requestManager` outright after construction.\n let requestManager: RequestManager | undefined;\n Object.defineProperty(this, 'requestManager', {\n configurable: true,\n enumerable: true,\n get: (): RequestManager => {\n if (!requestManager) {\n const handlers = typeof options.handlers === 'function' ? options.handlers(this) : (options.handlers ?? []);\n requestManager = new RequestManager().use([...handlers, Fetch]).useCache(CacheHandler);\n }\n return requestManager;\n },\n set: (value: RequestManager): void => {\n requestManager = value;\n },\n });\n }\n\n lifetimes =\n options.policy ??\n new DefaultCachePolicy({\n apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes\n apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds\n constraints: {\n headers: {\n 'X-WarpDrive-Expires': true,\n 'Cache-Control': true,\n Expires: true,\n },\n },\n });\n\n createSchemaService() {\n const schema = new SchemaService();\n registerDerivations(schema);\n if (options.schemas) schema.registerResources(options.schemas);\n\n if (options.traits) {\n for (const trait of options.traits) {\n schema.registerTrait(trait);\n }\n }\n\n if (options.derivations) {\n for (const derivation of options.derivations) {\n schema.registerDerivation(derivation);\n }\n }\n\n if (options.transformations) {\n for (const transformation of options.transformations) {\n schema.registerTransformation(transformation);\n }\n }\n\n if (options.hashFns) {\n for (const hashFn of options.hashFns) {\n schema.registerHashFn(hashFn);\n }\n }\n\n if (options.CAUTION_MEGA_DANGER_ZONE_extensions) {\n for (const extension of options.CAUTION_MEGA_DANGER_ZONE_extensions) {\n schema.CAUTION_MEGA_DANGER_ZONE_registerExtension(extension);\n }\n }\n\n return schema;\n }\n\n createCache(capabilities: CacheCapabilitiesManager) {\n // oxlint-disable-next-line new-cap\n return new options.cache(capabilities);\n }\n\n instantiateRecord(key: ResourceKey, createArgs?: Record<string, unknown>) {\n return instantiateRecord(this, key, createArgs);\n }\n\n teardownRecord(record: unknown): void {\n return teardownRecord(record);\n }\n };\n}\n"],"x_google_ignoreList":[18],"mappings":";;;;;;;;;;;;;;;AAcA,SAASM,YAAYC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