@warp-drive/core 5.9.0-beta.2 → 5.9.0-beta.3
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-BL9zXgJB.js} +3 -3
- package/dist/{-private-zrP4VGAf.js.map → -private-BL9zXgJB.js.map} +1 -1
- package/dist/{-private-CyhhcK1a.js → -private-Cxa8cMBj.js} +2 -2
- package/dist/{-private-CyhhcK1a.js.map → -private-Cxa8cMBj.js.map} +1 -1
- package/dist/{-private-BYn1Vh-L.js → -private-xK1KgxZJ.js} +2 -2
- package/dist/{-private-BYn1Vh-L.js.map → -private-xK1KgxZJ.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-z2NByNx0.js} +2 -2
- package/dist/{request-7BJFgSu_.js.map → request-z2NByNx0.js.map} +1 -1
- package/dist/request.js +1 -1
- package/dist/signals/-leaked.js +1 -1
- package/dist/{src-BOAWJH_S.js → src-s5HHjglV.js} +5 -5
- package/dist/{src-BOAWJH_S.js.map → src-s5HHjglV.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-BGCYELwo.js} +2 -2
- package/dist/unpkg/{prod/-private-B36B1ztP.js.map → dev/-private-BGCYELwo.js.map} +1 -1
- package/dist/unpkg/dev/{-private-D6Tw25AD.js → -private-DhiS6yOR.js} +2 -2
- package/dist/unpkg/dev/{-private-D6Tw25AD.js.map → -private-DhiS6yOR.js.map} +1 -1
- package/dist/unpkg/dev/{-private-BoSTJwp9.js → -private-pNQae3qH.js} +3 -3
- package/dist/unpkg/{dev-deprecated/-private-BoSTJwp9.js.map → dev/-private-pNQae3qH.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-BbbzRou7.js} +2 -2
- package/dist/unpkg/dev/{request-CwjpJB3r.js.map → request-BbbzRou7.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-Cf7NXXR2.js} +5 -5
- package/dist/unpkg/dev/{src-CP6e_ozt.js.map → src-Cf7NXXR2.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-BGCYELwo.js} +2 -2
- package/dist/unpkg/dev-deprecated/{-private-CUkeqUhO.js.map → -private-BGCYELwo.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/{-private-D6Tw25AD.js → -private-DhiS6yOR.js} +2 -2
- package/dist/unpkg/dev-deprecated/{-private-D6Tw25AD.js.map → -private-DhiS6yOR.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/{-private-BoSTJwp9.js → -private-pNQae3qH.js} +3 -3
- package/dist/unpkg/{dev/-private-BoSTJwp9.js.map → dev-deprecated/-private-pNQae3qH.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-BbbzRou7.js} +2 -2
- package/dist/unpkg/dev-deprecated/{request-CwjpJB3r.js.map → request-BbbzRou7.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-CSuFUXv4.js} +5 -5
- package/dist/unpkg/dev-deprecated/{src-De8OV58h.js.map → src-CSuFUXv4.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/-private-8gd8hbwm.js +22 -0
- package/dist/unpkg/{prod-deprecated/-private-B36B1ztP.js.map → prod/-private-8gd8hbwm.js.map} +1 -1
- package/dist/unpkg/{prod-deprecated/-private-Dhl123OI.js → prod/-private-B6aLbrgV.js} +2 -2
- package/dist/unpkg/prod/{-private-Dhl123OI.js.map → -private-B6aLbrgV.js.map} +1 -1
- package/dist/unpkg/{prod-deprecated/-private-DHco-h0q.js → prod/-private-ggVX_Iob.js} +3 -3
- package/dist/unpkg/{prod-deprecated/-private-DHco-h0q.js.map → prod/-private-ggVX_Iob.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-BoeppjDj.js} +2 -2
- package/dist/unpkg/{prod-deprecated/request-BBdC1Sz7.js.map → prod/request-BoeppjDj.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-C0wuASrN.js} +5 -5
- package/dist/unpkg/prod/{src-nFHlZgKa.js.map → src-C0wuASrN.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-deprecated/{-private-B36B1ztP.js → -private-8gd8hbwm.js} +2 -2
- package/dist/unpkg/{dev/-private-CUkeqUhO.js.map → prod-deprecated/-private-8gd8hbwm.js.map} +1 -1
- package/dist/unpkg/{prod/-private-Dhl123OI.js → prod-deprecated/-private-B6aLbrgV.js} +2 -2
- package/dist/unpkg/prod-deprecated/{-private-Dhl123OI.js.map → -private-B6aLbrgV.js.map} +1 -1
- package/dist/unpkg/{prod/-private-DHco-h0q.js → prod-deprecated/-private-ggVX_Iob.js} +3 -3
- package/dist/unpkg/{prod/-private-DHco-h0q.js.map → prod-deprecated/-private-ggVX_Iob.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-BoeppjDj.js} +2 -2
- package/dist/unpkg/{prod/request-BBdC1Sz7.js.map → prod-deprecated/request-BoeppjDj.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-BXOgNqmz.js} +5 -5
- package/dist/unpkg/prod-deprecated/{src-Cku5ymUJ.js.map → src-BXOgNqmz.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
package/dist/unpkg/{prod-deprecated/-private-DHco-h0q.js.map → prod/-private-ggVX_Iob.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"-private-DHco-h0q.js","names":["getOrSetGlobal","peekTransient","setTransient","ARRAY_SIGNAL","Symbol","OBJECT_SIGNAL","setupSignals","buildConfig","hooks","wellknown","Array","createSignal","obj","key","signalHooks","consumeSignal","signal","notifySignal","createMemo","object","fn","willSyncFlushWatchers","waitFor","promise","getOrSetGlobal","ARRAY_SIGNAL","consumeSignal","createMemo","createSignal","notifySignal","OBJECT_SIGNAL","INITIALIZER_PROTO","isInitializer","makeInitializer","fn","Object","assign","create","value","obj","getPrototypeOf","Signals","Symbol","upgradeWithSignals","withSignalStore","initializeSignalStore","Map","createInternalSignal","signals","key","initialValue","warpDriveSignal","context","signal","call","isStale","set","getOrCreateInternalSignal","peekInternalSignal","createInternalMemo","object","memo","consumeInternalMemo","TrackingFrame","add","get","consumeInternalSignal","notifyInternalSignal","withFrame","frameSignals","Set","frameFn","size","clear","parent","isMemo","LightColors","red","green","reset","DarkColors","isLightMode","window","matchMedia","matches","RED","GREEN","RESET","EOL","colorizeLines","lines","Colors","colors","line","str","push","log","args","console","isDirty","isDirtyMemo","printSignal","depth","_dirty","padStart","String","printMemo","consumeInternalSignal","createInternalMemo","createInternalSignal","getOrCreateInternalSignal","makeInitializer","notifyInternalSignal","peekInternalSignal","withSignalStore","entangleSignal","signals","obj","key","initialValue","internalSignal","entangleInitiallyStaleSignal","isStale","createSignalDescriptor","intialValue","enumerable","configurable","get","value","set","defineSignal","v","Object","defineProperty","defineNonEnumerableSignal","desc","signal","target","descriptor","initializer","memoized","getter","memoSignal","bind","gate","_target","setter","isLocal","call","undefined","defineGate","options","assign","getPromiseResult","setPromiseResult","DOMError","defineNonEnumerableSignal","defineSignal","RequestCache","WeakMap","isAbortError","error","name","upgradeLoadingState","state","watchStream","stream","loadingState","reader","getReader","bytesLoaded","shouldForward","_stream","readable","locked","isForwarding","writer","writable","getWriter","buffer","_isPending","_isStarted","_startTime","performance","now","value","done","read","byteLength","_bytesLoaded","_lastPacketTime","item","ready","write","length","push","close","cancel","endTime","_endTime","_isComplete","RequestLoadingState","_future","_triggered","_trigger","future","promise","getStream","sizeHint","_sizeHint","then","_isCancelled","_isErrored","_error","isPending","TransformStream","isStarted","startTime","lastPacketTime","isComplete","isCancelled","isErrored","elapsedTime","completedRatio","remainingRatio","duration","speed","constructor","abort","prototype","RequestStateProto","performRefresh","requester","request","isReload","req","Object","assign","cacheOptions","reload","backgroundReload","defineProperty","get","isError","reason","_loadingState","_request","createRequestState","promiseState","create","refresh","usePolicy","result","status","isLoading","response","content","isSuccess","getRequestState","set","defineSignal","memoized","getRequestState","n","DEFAULT_DEADLINE","DISPOSE","Symbol","dispose","for","isNeverString","val","RequestSubscription","_requester","constructor","store","args","_args","_subscribedTo","_subscription","_intervalStart","_invalidated","_nextInterval","isDestroyed","_DISPOSE","_installListeners","_beginPolling","isIdle","request","_scheduleInterval","query","Boolean","prototype","autorefreshTypes","autorefresh","types","split","Set","autorefreshThreshold","hasValidThreshold","window","has","_latestRequest","Date","now","setTimeout","_maybeUpdate","_clearInterval","clearTimeout","_updateSubscriptions","requestId","_request","lid","_removeSubscriptions","_getRequester","isStore","notifications","subscribe","_id","op","_isUpdating","latest","requestManager","_deduped","get","priority","state","reqState","isRefreshing","blocking","isLoading","unsubscribe","hasWindow","hasDocument","document","hasWindowEvents","addEventListener","hasDocumentEvents","isOnline","navigator","onLine","_unavailableStart","isHidden","visibilityState","_onlineChanged","event","type","passive","capture","_backgroundChanged","mode","silent","isPending","canAttempt","size","Error","shouldAttempt","deadline","realMode","autorefreshBehavior","requester","reload","refresh","_localRequest","finally","retry","errorFeatures","contentFeatures","feat","latestRequest","abort","_originalRequest","_originalQuery","isOriginalRequest","result","undefined","createRequestSubscription","upgradeSubscription","sub","self","removeEventListener","memoized","signal","getRequestState","g","i","n","abs","Math","getHref","link","href","PageCache","prototype","request","state","selfLink","prevLink","nextLink","firstLink","lastLink","pageNumber","before","after","constructor","manager","url","value","data","isRequested","Boolean","isLoaded","isSuccess","isError","isLoading","isCancelled","reason","prev","getPageCache","next","first","last","isLinked","load","content","self","links","getPageNumber","firstPage","lastPage","prevPage","nextPage","setPageNumber","updateLinkage","totalPages","updateLinks","lookupLinkage","leftSide","rightSide","setAfter","setBefore","firstPageDelta","lastPageDelta","lookupLinkageForward","lookupLinkageBackwards","page","document","readPageHints","currentPage","PageCache","memoized","signal","g","i","n","PaginationCacheMap","Map","defaultPageHints","document","currentPage","meta","page","totalPages","PaginationCache","prototype","firstPage","isNumbered","pageHints","constructor","key","pagesCache","installPageHints","readPageHints","getPageCache","url","get","set","loadPage","request","isLoaded","isError","load","then","updateFirstPage","getTotalPages","maybeFirstPage","before","pageNumber","pages","self","Symbol","iterator","after","data","getPaginationCache","cache","clearPaginationCache","clear","getHref","getPaginationCache","defineSignal","memoized","n","PaginationState","constructor","request","pageHints","store","requester","_adoptTarget","setup","activePageRequest","activePage","prototype","totalPages","paginationCache","pages","self","Symbol","iterator","end","frontierEnd","page","frontierStart","after","data","hasNext","Boolean","nextLink","hasPrevious","prevLink","nextRequest","url","getPageCache","previousRequest","document","content","selfLink","links","firstLink","first","cacheKey","cache","installPageHints","getTotalPages","initialPage","loadPage","_activate","existing","adoptPage","key","value","loadPrev","_extend","loadNext","dir","frontier","isRequested","isError","method","cacheOptions","reload","isLoaded","PaginationStateCache","WeakMap","getPaginationState","state","get","set","memoized","n","PaginationLinksCache","WeakMap","RealPaginationLink","isReal","url","index","isCurrent","distanceFromActiveIndex","constructor","activeIndex","loadPage","Math","abs","_loadPage","text","setActive","PlaceholderPaginationLink","indexRange","rangeSize","start","end","min","_mergeRange","newRange","oldStart","oldEnd","newStart","newEnd","mergedRange","max","RelationalPaginationLink","rel","PaginationLinks","paginationState","first","activePage","firstLink","selfLink","prototype","prev","prevLink","next","nextLink","last","lastLink","links","cache","paginationCache","isNumbered","firstPage","totalPages","pageNumber","previousPage","currentPage","push","after","getPaginationLinks","state","get","set","getPaginationState","defineSignal","memoized","createRequestSubscription","DISPOSE","n","PaginationSubscription","constructor","store","args","_args","isDestroyed","_seedRequest","_navTarget","_DISPOSE","_requestSubscription","paginationState","request","active","_navRequest","pageHints","_resolveNavigation","prototype","adopted","adoptPage","isIdle","isLoading","reqState","paginationCache","isSuccess","isNavigating","loadingState","isError","isCancelled","reason","errorFeatures","isHidden","isOnline","retry","contentFeatures","feat","loadPrev","loadNext","loadPage","isRefreshing","abort","latestRequest","createPaginationSubscription","upgradeSubscription","sub","self","memoized","getPaginationLinks","DISPOSE","n","PaginationLinksSubscription","constructor","args","_args","isDestroyed","_DISPOSE","paginationLinks","pages","prototype","createPaginationLinksSubscription","upgradeSubscription","sub","self","getPromiseResult","setPromiseResult","defineSignal","PromiseCache","WeakMap","PromiseStateProto","createPromiseState","promise","state","promiseState","Object","create","isError","error","result","reason","status","isPending","isLoading","value","isSuccess","then","LegacyPromiseProxy","Symbol","for","isLegacyAwaitable","getPromise","getPromiseState","_promise","get","set"],"sources":["../../../src/signals/reactivity/configure.ts","../../../src/signals/reactivity/internal.ts","../../../src/signals/reactivity/signal.ts","../../../src/signals/request-state.ts","../../../../../node_modules/.pnpm/decorat_5d4eca388601a94e7fbc656401b751d1/node_modules/decorator-transforms/dist/runtime--fcdnjmJ.js","../../../src/signals/request-subscription.ts","../../../src/signals/page-cache.ts","../../../src/signals/pagination-cache.ts","../../../src/signals/pagination-state.ts","../../../src/signals/pagination-links.ts","../../../src/signals/pagination-subscription.ts","../../../src/signals/pagination-links-subscription.ts","../../../src/signals/promise-state.ts"],"sourcesContent":["import { assert } from '@warp-drive/core/build-config/macros';\n\n// oxlint-disable-next-line no-unused-vars\nimport type { NotificationManager } from '../../store/-private/managers/notification-manager.ts';\nimport { getOrSetGlobal, peekTransient, setTransient } from '../../types/-private.ts';\n\nexport const ARRAY_SIGNAL: '___(unique) Symbol(#[])' = getOrSetGlobal('#[]', Symbol('#[]'));\nexport const OBJECT_SIGNAL: '___(unique) Symbol(#{})' = getOrSetGlobal('#{}', Symbol('#{}'));\n\n/*\n * Requirements:\n *\n * Signal:\n *\n * - signal: a way of creating a reference that we can dirty when we desire to notify\n * - @signal: a way of creating an accessor on an object that subscribes to a signal on access\n * and notifies the signal on set, or of upgrading a descriptor to be such an accessor\n * - defineSignal: a way of creating a signal on an object\n * - notifySignal: a way of notifying the underlying signal that it has been dirtied\n * - peekSignal: a way of inspecting the signal without notifying it\n *\n * - gate: a memoized getter function that re-runs when on access if its signal is dirty\n * conceptually, a gate is a tightly coupled signal and memo\n * - @gate: a way of creating a gate on an object or upgrading a descriptor with a getter\n * to be a gate\n * - defineGate: a way of creating a gate on an object\n * - notifySignal: a way of notifying the signal for a gate that it has been dirtied\n *\n * - memo:\n * - @memo: a way of creating a memoized getter on an object or upgrading a descriptor with a getter\n * to be a memo\n * - defineMemo: a way of creating a memo on an object\n *\n * - signalStore: storage bucket for signals associated to an object\n * - withSignalStore: a way of pre-creating a signal store on an object\n */\n\n/**\n * An Opaque type that represents a framework specific or TC39 signal.\n *\n * It may be an array of signals or a single signal.\n *\n * @private\n */\nexport type SignalRef = unknown;\n/**\n * The hooks which MUST be configured in order to use reactive arrays,\n * resources and documents with framework specfic signals or TC39 signals.\n *\n * Support for multiple frameworks simultaneously can be done via\n * this abstraction by returning multiple signals from the `createSignal`\n * method, and consuming the correct one via the correct framework via\n * the `consumeSignal` and `notifySignal` methods.\n *\n * Unlike many signals implementations, WarpDrive does not wrap values as\n * signals directly, but instead uses signals to alert the reactive layer\n * to changes in the underlying cache. E.g. a signal is associated to a value,\n * but does not serve as the cache for that value directly. We refer to this as\n * a \"gate\", the pattern has also been called \"side-signals\".\n *\n * A no-op implementation is allowed, though it may lead to performance issues\n * in locations that use createMemo as no memoization would be done. This is\n * typically desirable only when integrating with a framework that does its own\n * memoization and does not integrate with any signals-like primitive. For these\n * scenarios you may also be interested in integrating with the {@link NotificationManager}\n * more directly.\n *\n * @public\n */\nexport interface SignalHooks<T = SignalRef> {\n /**\n * Create a signal for the given key associated to the given object.\n *\n * This method does *not* need to cache the signal, it will only be\n * called once for a given object and key. However, if your framework\n * will look for a signal cache on the object in a given location or may\n * have created its own signal on the object for some reason it may be\n * useful to ensure such cache is properly updated.\n */\n createSignal: (obj: object, key: string | symbol) => T;\n /**\n * Consume (mark as acccessed) a signal previously created via createSignal.\n */\n consumeSignal: (signal: T) => void;\n /**\n * Alert a signal previously created via createSignal that its associated value has changed.\n */\n notifySignal: (signal: T) => void;\n /**\n * Take the given function and wrap it in signals-based memoization. Analagous\n * to a Computed in the TC39 spec.\n *\n * Should return a function which when run provides the latest value of the original\n * function.\n */\n createMemo: <F>(obj: object, key: string | symbol, fn: () => F) => () => F;\n\n /**\n * If the signals implementation allows synchronous flushing of watchers, and\n * has scheduled such a flush (e.g. watchers will run before the current calling\n * context yields) this should return \"true\".\n *\n * This is generally something that should return false for anything but the few\n * frameworks that extensively handle their own reactivity => render scheduling.\n *\n * For an example, see EmberJS's backburner scheduler which functioned as a microtask\n * polyfill.\n */\n willSyncFlushWatchers: () => boolean;\n\n /**\n * An optional method that allows wrapping key promises within WarpDrive\n * for things like test-waiters.\n */\n waitFor?: <K>(promise: Promise<K>) => Promise<K>;\n}\n\n/**\n * Contains information a {@link SignalHooks} implementation may want\n * to use, such as the specialized key used for the signal\n * representing an array's contents / length.\n *\n * ```ts\n * interface HooksOptions {\n * wellknown: {\n * Array: symbol | string;\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface HooksOptions {\n /**\n * A list of specialized symbols/strings\n * used by WarpDrive to encapsulate key\n * reactivity concerns.\n */\n wellknown: {\n /**\n * The key used when the signal provides reactivity for the\n * `length` or \"contents\" of an array.\n *\n * Arrays only use a single signal for all accesses, regardless\n * of index, property or method: this one.\n */\n Array: symbol | string;\n };\n}\n\n/**\n * Configures the signals implementation to use. Supports multiple\n * implementations simultaneously.\n *\n * See {@link HooksOptions} for the options passed to the provided function\n * when called.\n *\n * See {@link SignalHooks} for the implementation the callback function should\n * return.\n *\n * @public\n * @param buildConfig - a function that takes options and returns a configuration object\n */\nexport function setupSignals<T>(buildConfig: (options: HooksOptions) => SignalHooks<T>): void {\n // We want to assert this but can't because too many package manager\n // and bundler bugs exist that cause this to be called multiple times\n // for what should be a single call.\n // assert(`Cannot override configured signal hooks`, peekTransient('signalHooks') === null);\n const hooks = buildConfig({\n wellknown: {\n Array: ARRAY_SIGNAL,\n },\n });\n setTransient('signalHooks', hooks);\n}\n\n/**\n * Internal method for consuming the configured `createSignal` hook\n *\n * @private\n */\nexport function createSignal(obj: object, key: string | symbol): SignalRef {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.createSignal(obj, key);\n}\n\n/**\n * Internal method for consuming the configured `consumeSignal` hook\n *\n * @private\n */\nexport function consumeSignal(signal: SignalRef): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.consumeSignal(signal);\n}\n\n/**\n * Internal method for consuming the configured `notifySignal` hook\n *\n * @private\n */\nexport function notifySignal(signal: SignalRef): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.notifySignal(signal);\n}\n\nexport function createMemo<T>(object: object, key: string | symbol, fn: () => T): () => T {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.createMemo(object, key, fn);\n}\n\nexport function willSyncFlushWatchers(): boolean {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.willSyncFlushWatchers();\n}\n\n/**\n * Wraps `promise` using the configured {@link SignalHooks.waitFor}, if any,\n * for things like test-waiters. Returns `promise` unchanged if no\n * `waitFor` hook is configured.\n */\nexport function waitFor<K>(promise: Promise<K>): Promise<K> {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n\n if (signalHooks?.waitFor) {\n return signalHooks.waitFor(promise);\n }\n return promise;\n}\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport {\n ARRAY_SIGNAL,\n consumeSignal,\n createMemo,\n createSignal,\n notifySignal,\n OBJECT_SIGNAL,\n type SignalRef,\n} from './configure.ts';\n\nexport type { SignalRef };\nexport { ARRAY_SIGNAL, OBJECT_SIGNAL };\n\nconst INITIALIZER_PROTO = { isInitializer: true } as const;\ninterface Initializer {\n value: () => unknown;\n}\n/**\n * Wraps `fn` so that a signal can recognize it as a lazy initializer\n * for its value rather than the value itself, deferring the call to\n * `fn` until the signal is first accessed.\n */\nexport function makeInitializer(fn: () => unknown): Initializer {\n // we use a prototype to ensure that the initializer is not enumerable\n // and does not interfere with the signal's value.\n return Object.assign(Object.create(INITIALIZER_PROTO), { value: fn }) as Initializer;\n}\n\nfunction isInitializer(obj: unknown): obj is Initializer {\n return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === INITIALIZER_PROTO;\n}\n\n/**\n * A WarpDriveSignal is a wrapper around a framework specific or TC39 signal\n * that enables us to store and manage the signal in a universal way.\n *\n * WarpDrive uses signals to manage three separate concepts:\n *\n * - as a `storage` for a value local to the object that we want to be reactive\n * (see `@local` schema field for an example)\n * - as a `gate` for a memoized getter that we want to act as a reactive property\n * but whose value is computed/pulled from a non-reactive source elsewhere\n * and whose latest value is stored in the signal\n * (see `field` schema field for an example)\n * - as a `gate` with a manually managed value updated on pull when `isStale` is true\n *\n *\n * It offers\n *\n * - a non-reactive way to access/update the current value\n * - a non-reactive way to mark the signal as dirtied\n * - a non-reactive way to store content for why the signal was dirtied\n * - access to the underlying Signal(s) in-use\n *\n * For debugging:\n * - the \"key\" or \"name\" of the signal\n * - the \"object identity\" or \"context\" to which the signal is attached\n *\n * @private\n */\nexport interface WarpDriveSignal {\n /**\n * The \"key\" or \"name\" of the signal.\n * This is usually (but not always) the name of a property\n * on the object to which the signal is attached.\n *\n * This is used for debugging purposes.\n * It is not used for any other purpose.\n *\n * @internal\n */\n key: string | symbol;\n\n /**\n * The \"object identity\" or \"context\" to which the\n * signal is attached.\n *\n * This is used for debugging purposes.\n * It is not used for any other purpose.\n *\n * @internal\n */\n context: object;\n\n /**\n * The underlying signal(s) in-use.\n *\n * Generally, this is a single signal.\n *\n * In some cases multiple signals need to be condensed,\n * such as to support legacy Ember Array APIs or to\n * support reactive-objects shared between the code of\n * multiple frameworks.\n *\n * In such cases, this value may be an array.\n *\n * e.g. (pseudo-code for Ember):\n *\n * setupSignals({\n * createSignal: (obj, key, initialValue) => {\n * if (isArraySignal(key)) {\n * return [\n * tagForProperty(obj, key),\n * tagForProperty(obj, '[]'),\n * tagForProperty(obj, 'length'),\n * ];\n * }\n * return tagForProperty(obj, key);\n * },\n *\n * consumeSignal: (signal) => {\n * if (Array.isArray(signal)) {\n * signal.forEach((s) => consumeTag(s));\n * } else {\n * consumeTag(signal);\n * }\n * },\n *\n * dirtySignal: (signal) => {\n * if (Array.isArray(signal)) {\n * signal.forEach((s) => dirtyTag(s));\n * } else {\n * dirtyTag(signal);\n * }\n * },\n * });\n *\n * @private\n */\n signal: SignalRef;\n\n /**\n * The last \"value\" computed for this signal when\n * a signal is also used for storage.\n *\n * @private\n */\n value: unknown;\n\n /**\n * Whether ths signal is known to have been dirtied.\n * This is useful *both* when manually managing the\n * `value` cache and when using the signal as a\n * \"gate\"\n *\n * @private\n */\n isStale: boolean;\n}\n\n/**\n * We attach signals to their context object via\n * a Map attached to the object via this symbol.\n *\n * This allows us to store multiple signals\n * on the same object with smaller memory\n * overhead and no WeakMap lookups.\n *\n * Performance sensitive objects should\n * pre-warm their shape by assigning this\n * during initialization.\n *\n * ```ts\n * initializeSignalStore(obj);\n * ```\n *\n * @private\n */\nexport const Signals: '___(unique) Symbol(Signals)' = getOrSetGlobal('Signals', Symbol('Signals'));\nexport type SignalStore = Map<string | symbol, WarpDriveSignal>;\n\n/**\n * A type util to recast the object as having a signal store.\n *\n * @private\n */\nexport function upgradeWithSignals<T extends object>(obj: T): asserts obj is T & { [Signals]: SignalStore } {}\n\n/**\n * A util that will create a signal store on the object\n * if it does not already exist and returns the associated\n * signal store.\n *\n * @private\n */\nexport function withSignalStore<T extends object>(obj: T): SignalStore {\n upgradeWithSignals(obj);\n if (!obj[Signals]) {\n initializeSignalStore(obj);\n }\n return obj[Signals];\n}\n\n/**\n * A util that will create a signal store on the object\n * if it does not already exist.\n *\n * Useful for pre-warming the shape of an object to ensure\n * a key-transition to add it is not required later.\n *\n * @private\n */\nexport function initializeSignalStore<T extends object>(obj: T): asserts obj is T & { [Signals]: SignalStore } {\n upgradeWithSignals(obj);\n assert(`Signal store already exists on object`, !obj[Signals]);\n obj[Signals] = new Map();\n}\n\nexport function createInternalSignal(\n signals: SignalStore,\n obj: object,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n const warpDriveSignal = {\n key,\n context: obj,\n signal: createSignal(obj, key),\n value: isInitializer(initialValue) ? initialValue.value.call(obj) : initialValue,\n isStale: false,\n };\n\n signals.set(key, warpDriveSignal);\n\n return warpDriveSignal;\n}\n\nexport function getOrCreateInternalSignal(\n signals: SignalStore,\n obj: object,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let signal = peekInternalSignal(signals, key);\n if (!signal) {\n signal = createInternalSignal(signals, obj, key, initialValue);\n }\n return signal;\n}\n\nexport function createInternalMemo<T>(\n signals: SignalStore,\n object: object,\n key: string | symbol,\n fn: () => T\n): () => T {\n assert(`Expected no signal/memo to exist for key \"${String(key)}\"`, !peekInternalSignal(signals, key));\n if (DEBUG) {\n return withFrame(signals, object, key, fn);\n } else {\n const memo = createMemo(object, key, fn);\n signals.set(key, memo as unknown as WarpDriveSignal);\n return memo;\n }\n}\n\nexport function consumeInternalMemo<T>(fn: () => T): T {\n TrackingFrame?.signals.add(fn as unknown as WarpDriveSignal);\n return fn();\n}\n\n/**\n * Looks up the {@link WarpDriveSignal} stored for `key` in `signals`,\n * if one has already been created, without creating or consuming it.\n */\nexport function peekInternalSignal(\n signals: SignalStore | undefined,\n key: string | symbol\n): WarpDriveSignal | undefined {\n return signals?.get(key);\n}\n\nexport function consumeInternalSignal(signal: WarpDriveSignal): void {\n TrackingFrame?.signals.add(signal);\n consumeSignal(signal.signal);\n}\n\n/**\n * Marks `signal` as stale and notifies its underlying framework/TC39\n * signal, scheduling any of its consumers for re-render/re-computation.\n */\nexport function notifyInternalSignal(signal: WarpDriveSignal | undefined): void {\n if (signal) {\n signal.isStale = true;\n notifySignal(signal.signal);\n }\n}\n\ninterface TrackingFrame {\n object: object;\n key: string | symbol;\n signals: Set<WarpDriveSignal>;\n parent: TrackingFrame | null;\n}\n\nlet TrackingFrame: TrackingFrame | null = null;\n\n/**\n * This is currently just for signals debugging, but it could be used in production\n * if we wanted to eliminate the need for frameworks to implement createMemo / to\n * allow us to add our own Watcher.\n *\n * @internal\n */\nfunction withFrame<T>(signals: SignalStore, object: object, key: string | symbol, fn: () => T): () => T {\n const frameSignals = new Set<WarpDriveSignal>();\n const frameFn = () => {\n if (frameSignals.size) {\n frameSignals.clear();\n }\n TrackingFrame = {\n object,\n key,\n signals: frameSignals,\n parent: TrackingFrame,\n };\n try {\n return fn();\n } finally {\n TrackingFrame = TrackingFrame.parent;\n }\n };\n const memo = createMemo(object, key, frameFn);\n // @ts-expect-error\n memo.signals = frameSignals;\n signals.set(key, memo as unknown as WarpDriveSignal);\n\n return memo;\n}\n\nfunction isMemo(obj: unknown): obj is { signals: Set<WarpDriveSignal> } {\n // @ts-expect-error\n return typeof obj === 'function' && obj.signals instanceof Set;\n}\n\nif (DEBUG) {\n // @ts-expect-error adding to global API\n globalThis.debugWarpDriveSignals = (obj: object, key?: string | symbol): boolean => {\n upgradeWithSignals(obj);\n const signals = obj[Signals];\n if (!signals) {\n log('The object has no associated signals');\n return false;\n }\n\n if (key) {\n const signal = signals.get(key);\n if (!signal) {\n log(`No signal found for key \"${String(key)}\"`);\n return false;\n }\n log(signal);\n if (isMemo(signal)) {\n colorizeLines(printMemo(signal, key));\n return true;\n } else {\n colorizeLines(printSignal(signal, key));\n return true;\n }\n }\n\n const lines: string[] = [];\n for (const [k, signal] of signals) {\n if (isMemo(signal)) continue;\n printSignal(signal, k, lines);\n }\n for (const [k, signal] of signals) {\n if (isMemo(signal)) {\n printMemo(signal, k, lines);\n }\n }\n\n log(signals);\n colorizeLines(lines);\n\n return true;\n };\n}\n\nconst LightColors = {\n red: 'color: red;',\n green: 'color: green;',\n reset: 'color: inherit;',\n};\nconst DarkColors = {\n red: 'color: red;',\n green: 'color: lightgreen;',\n reset: 'color: inherit;',\n};\nfunction isLightMode() {\n if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {\n return true;\n }\n return false;\n}\n\nconst RED = {} as unknown as string;\nconst GREEN = {} as unknown as string;\nconst RESET = {} as unknown as string;\nconst EOL = {} as unknown as string;\n\nfunction colorizeLines(lines: string[]): void {\n const Colors = isLightMode() ? LightColors : DarkColors;\n const colors = [];\n let line = '';\n\n for (const str of lines) {\n if (str === RED) {\n colors.push(Colors.red);\n line += '%c';\n } else if (str === GREEN) {\n colors.push(Colors.green);\n line += '%c';\n } else if (str === RESET) {\n colors.push(Colors.reset);\n line += '%c';\n } else if (str === EOL) {\n line += '\\n';\n } else {\n line += str;\n }\n }\n\n log(line, ...colors);\n}\n\nfunction log(...args: unknown[]): void {\n // oxlint-disable-next-line no-console\n console.log(...args);\n}\n\nfunction isDirty(signal: WarpDriveSignal): boolean {\n return signal.isStale;\n}\n\nfunction isDirtyMemo(memo: { signals: Set<WarpDriveSignal> }): boolean {\n // iterate simple signals first to get fastest answer\n for (const signal of memo.signals) {\n if (isMemo(signal)) continue;\n if (isDirty(signal)) {\n return true;\n }\n }\n for (const signal of memo.signals) {\n if (isMemo(signal)) {\n return isDirtyMemo(signal);\n }\n }\n return false;\n}\n\nfunction printSignal(signal: WarpDriveSignal, key: string | symbol, lines: string[] = [], depth = 0): string[] {\n const _dirty = isDirty(signal);\n lines.push(\n `${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `,\n _dirty ? RED : GREEN,\n `${String(key)}`,\n RESET,\n EOL\n );\n return lines;\n}\n\nfunction printMemo(\n memo: { signals: Set<WarpDriveSignal> },\n key: string | symbol,\n lines: string[] = [],\n depth = 0\n): string[] {\n const _dirty = isDirtyMemo(memo);\n lines.push(\n `${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `,\n _dirty ? RED : GREEN,\n `<memo> ${String(key)}`,\n RESET,\n `: (consumes ${memo.signals.size} signals)`,\n EOL\n );\n for (const signal of memo.signals) {\n if (isMemo(signal)) continue;\n printSignal(signal, signal.key, lines, depth + 1);\n }\n for (const signal of memo.signals) {\n if (isMemo(signal)) {\n printMemo(signal, signal.key, lines, depth + 1);\n }\n }\n return lines;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Signals, SignalStore, WarpDriveSignal } from './internal.ts';\nimport {\n consumeInternalSignal,\n createInternalMemo,\n createInternalSignal,\n getOrCreateInternalSignal,\n makeInitializer,\n notifyInternalSignal,\n peekInternalSignal,\n withSignalStore,\n} from './internal.ts';\n\n/**\n * Creates a signal for the key/object pairing and subscribes to the signal.\n *\n * Use when you need to ensure a signal exists and is subscribed to.\n *\n * @private\n */\nexport function entangleSignal<T extends object>(\n signals: SignalStore,\n obj: T,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, obj, key, initialValue);\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal;\n}\n\nexport function entangleInitiallyStaleSignal<T extends object>(\n signals: SignalStore,\n obj: T,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, obj, key, initialValue);\n internalSignal.isStale = true; // mark it as stale\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal;\n}\n\nexport function createSignalDescriptor(key: string | symbol, intialValue: unknown): PropertyDescriptor {\n return {\n enumerable: true,\n configurable: false,\n get(this: { [Signals]: SignalStore }) {\n const signals = withSignalStore(this);\n const internalSignal = entangleSignal(signals, this, key, intialValue);\n internalSignal.isStale = false; // reset stale state\n return internalSignal.value;\n },\n set(this: { [Signals]: SignalStore }, value: unknown) {\n const signals = withSignalStore(this);\n const internalSignal = getOrCreateInternalSignal(signals, this, key, intialValue);\n\n if (internalSignal.value !== value) {\n internalSignal.value = value;\n notifyInternalSignal(internalSignal);\n }\n },\n };\n}\n\n/**\n * define an enumerable signal property.\n *\n * Akin to Object.defineProperty.\n *\n * The signal will be lazily created when accessed and scoped to the\n * instance of the object.\n *\n * @private\n */\nexport function defineSignal<T extends object>(obj: T, key: string, v?: unknown): void {\n Object.defineProperty(obj, key, createSignalDescriptor(key, v));\n}\n\n/**\n * Define a non-enumerable signal property.\n *\n * @private\n */\nexport function defineNonEnumerableSignal<T extends object>(obj: T, key: string, v?: unknown): void {\n const desc = createSignalDescriptor(key, v);\n desc.enumerable = false;\n Object.defineProperty(obj, key, desc);\n}\n\ninterface DecoratorPropertyDescriptor extends PropertyDescriptor {\n initializer?: () => unknown;\n}\n\n/**\n * Decorator version of creating a signal.\n */\nexport function signal<T extends object, K extends keyof T & string>(\n target: T,\n key: K,\n descriptor?: DecoratorPropertyDescriptor\n): void {\n // Error on `@signal()`, `@signal(...args)``\n assert(\n 'You attempted to use @signal(), which is not necessary nor supported. Remove the parentheses and you will be good to go!',\n target !== undefined\n );\n assert(\n `You attempted to use @signal on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @signal(${Array.from(\n arguments\n )\n .map((d) => `'${d}'`)\n .join(\n ', '\n )}) ), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@signal`'}`,\n typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3\n );\n\n return createSignalDescriptor(\n key,\n descriptor.initializer ? makeInitializer(descriptor.initializer) : null\n ) as unknown as void;\n}\n\n/**\n * Decorator version of creating a memoized getter\n */\nexport function memoized<T extends object, K extends keyof T & string>(\n target: T,\n key: K,\n descriptor: PropertyDescriptor\n): PropertyDescriptor {\n // Error on `@memoized()`, `@memoized(...args)`, and `@memoized propName = value;`\n assert(\n 'You attempted to use @memoized(), which is not necessary nor supported. Remove the parentheses and you will be good to go!',\n target !== undefined\n );\n assert(\n `You attempted to use @memoized on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @memoized(${Array.from(\n arguments\n )\n .map((d) => `'${d}'`)\n .join(\n ', '\n )}), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@memoized`'}`,\n typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3\n );\n assert(\n `The @memoized decorator must be applied to getters. '${key}' is not a getter.`,\n typeof descriptor.get === 'function'\n );\n\n // oxlint-disable-next-line typescript/unbound-method\n const getter = descriptor.get;\n descriptor.get = function () {\n const signals = withSignalStore(this);\n\n let memoSignal = signals.get(key);\n if (!memoSignal) {\n memoSignal = createInternalMemo(signals, this, key, getter.bind(this)) as unknown as WarpDriveSignal;\n }\n return (memoSignal as unknown as () => unknown)();\n };\n\n return descriptor;\n}\n\n/**\n * Decorator version of creating a gate.\n *\n * @private\n */\nexport function gate<T extends object, K extends keyof T & string>(\n _target: T,\n key: K,\n desc: PropertyDescriptor\n): PropertyDescriptor {\n // oxlint-disable-next-line typescript/unbound-method\n const getter = desc.get as (this: T) => unknown;\n // oxlint-disable-next-line typescript/unbound-method\n const setter = desc.set as (this: T, v: unknown) => void;\n const isLocal = (desc as unknown as { isLocal?: boolean }).isLocal;\n\n desc.get = function (this: T) {\n const signals = withSignalStore(this);\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, this, key, getter.call(this));\n } else if (internalSignal.isStale) {\n internalSignal.isStale = false;\n internalSignal.value = getter.call(this);\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal.value;\n };\n\n if (setter) {\n desc.set = function (this: T, v: unknown) {\n const signals = withSignalStore(this);\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n // we can't use `v` as initialValue here because setters don't\n // return the value and the final value may be different\n // than what the setter was called with.\n internalSignal = createInternalSignal(signals, this, key, undefined);\n internalSignal.isStale = true;\n }\n setter.call(this, v);\n // when a gate is set, we do not notify the signal\n // as its update is controlled externally.\n // unless it specifically sets itself to be locally managed\n if (isLocal) {\n internalSignal.isStale = true;\n notifyInternalSignal(internalSignal);\n }\n };\n }\n return desc;\n}\n\n/**\n * Defines a reactive \"gated\" property on `obj` using `desc` as its\n * getter/setter descriptor.\n *\n * Unlike a signal defined with {@link defineSignal}, a gated property's\n * consumers are not notified when the property is set, since its update\n * is expected to be controlled externally (for instance, by a signal it\n * derives its value from) unless the descriptor opts into being locally\n * managed.\n *\n * Akin to `Object.defineProperty`.\n *\n * @private\n */\nexport function defineGate<T extends object>(obj: T, key: string, desc: PropertyDescriptor): void {\n const options = Object.assign({ enumerable: true, configurable: false }, gate(obj, key as keyof T & string, desc));\n Object.defineProperty(obj, key, options);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { Awaitable, Future } from '../request.ts';\nimport { getPromiseResult, setPromiseResult } from '../request.ts';\nimport type { RequestManager } from '../request/-private/manager.ts';\nimport { DOMError } from '../request/-private/utils.ts';\nimport type { Store } from '../store/-private/store-service.ts';\nimport type {\n ImmutableRequestInfo,\n RequestInfo,\n ResponseInfo,\n StructuredDataDocument,\n StructuredErrorDocument,\n} from '../types/request.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { PendingPromise, PromiseState, RejectedPromise, ResolvedPromise } from './promise-state.ts';\nimport { defineNonEnumerableSignal, defineSignal } from './reactivity/signal.ts';\n\nconst RequestCache = new WeakMap<Future<unknown>, RequestState>();\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMError && error.name === 'AbortError';\n}\n\ninterface PrivateLoadingState {\n _sizeHint: number;\n _bytesLoaded: number;\n _startTime: number;\n _endTime: number;\n _lastPacketTime: number;\n _isPending: boolean;\n _isStarted: boolean;\n _isComplete: boolean;\n _isCancelled: boolean;\n _isErrored: boolean;\n _error: Error | null;\n _stream: TransformStream | null;\n _future: Future<unknown>;\n _triggered: boolean;\n}\n\nfunction upgradeLoadingState(state: unknown): PrivateLoadingState {\n return state as PrivateLoadingState;\n}\n\nasync function watchStream(stream: ReadableStream<Uint8Array>, loadingState: RequestLoadingState): Promise<void> {\n const state = upgradeLoadingState(loadingState);\n const reader = stream.getReader();\n let bytesLoaded = 0;\n let shouldForward = state._stream !== null && state._stream.readable.locked;\n let isForwarding = shouldForward;\n let writer = state._stream?.writable.getWriter();\n const buffer = [];\n\n state._isPending = false;\n state._isStarted = true;\n state._startTime = performance.now();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n bytesLoaded += value.byteLength;\n state._bytesLoaded = bytesLoaded;\n state._lastPacketTime = performance.now();\n\n shouldForward = shouldForward || (state._stream !== null && state._stream.readable.locked);\n\n if (shouldForward) {\n if (!isForwarding) {\n isForwarding = true;\n writer = state._stream!.writable.getWriter();\n for (const item of buffer) {\n await writer.ready;\n await writer.write(item);\n }\n buffer.length = 0;\n }\n await writer!.ready;\n await writer!.write(value);\n } else {\n buffer.push(value);\n }\n }\n\n // if we are still forwarding, we need to close the writer\n if (isForwarding) {\n await writer!.ready;\n await writer!.close();\n } else if (state._stream) {\n // if we are not forwarding, we need to cancel the stream\n await state._stream.readable.cancel('The Stream Has Already Ended');\n state._stream = null;\n }\n\n const endTime = performance.now();\n state._endTime = endTime;\n state._isComplete = true;\n state._isStarted = false;\n}\n\n/**\n * Lazily consumes the stream of a request, providing a number of\n * reactive properties that can be used to build UIs that respond\n * to the progress of a request.\n *\n * @hideconstructor\n */\nexport class RequestLoadingState {\n /** @internal */\n declare private _sizeHint: number;\n /** @internal */\n declare private _bytesLoaded: number;\n /** @internal */\n declare private _startTime: number;\n /** @internal */\n declare private _endTime: number;\n /** @internal */\n declare private _lastPacketTime: number;\n /** @internal */\n declare private _isPending: boolean;\n /** @internal */\n declare private _isStarted: boolean;\n /** @internal */\n declare private _isComplete: boolean;\n /** @internal */\n declare private _isCancelled: boolean;\n /** @internal */\n declare private _isErrored: boolean;\n /** @internal */\n declare private _error: Error | null;\n\n /** @internal */\n private _stream: TransformStream | null = null;\n /** @internal */\n private _future: Future<unknown>;\n /** @internal */\n private _triggered = false;\n /** @internal */\n private _trigger() {\n if (this._triggered) {\n return;\n }\n this._triggered = true;\n const future = this._future;\n const promise: Promise<ReadableStream<Uint8Array> | null> & { sizeHint?: number } = future.getStream();\n if (promise.sizeHint) {\n this._sizeHint = promise.sizeHint;\n }\n this.promise = promise.then(\n (stream) => {\n if (!stream) {\n this._isPending = false;\n this._isComplete = true;\n return;\n }\n return watchStream(stream, this);\n },\n (error: Error) => {\n this._isPending = false;\n this._isStarted = false;\n if (isAbortError(error)) {\n this._isCancelled = true;\n this._isComplete = true;\n }\n this._isErrored = true;\n this._error = error;\n }\n );\n }\n\n /**\n * Resolves once the stream has finished being consumed, or rejects\n * if the request errors. `null` until first accessed.\n */\n promise: Promise<void> | null = null;\n\n /**\n * Whether the stream has not yet started being consumed.\n */\n get isPending(): boolean {\n this._trigger();\n return this._isPending;\n }\n\n /**\n * The total size of the response in bytes, if known ahead of time\n * (via a `Content-Length` header or similar).\n */\n get sizeHint(): number {\n this._trigger();\n return this._sizeHint;\n }\n\n /**\n * A readable stream of the response content. Accessing this property\n * begins consumption of the underlying request stream.\n */\n get stream(): ReadableStream | null {\n this._trigger();\n if (!this._stream) {\n if (this._isComplete || this._isCancelled || this._isErrored) {\n return null;\n }\n this._stream = new TransformStream();\n }\n return this._stream.readable;\n }\n\n /**\n * Whether the stream has started being consumed but has not yet completed.\n */\n get isStarted(): boolean {\n this._trigger();\n return this._isStarted;\n }\n\n /**\n * The number of bytes loaded so far.\n */\n get bytesLoaded(): number {\n this._trigger();\n return this._bytesLoaded;\n }\n\n /**\n * The `performance.now()` timestamp at which the stream started being consumed.\n */\n get startTime(): number {\n this._trigger();\n return this._startTime;\n }\n\n /**\n * The `performance.now()` timestamp at which the stream finished being consumed.\n */\n get endTime(): number {\n this._trigger();\n return this._endTime;\n }\n\n /**\n * The `performance.now()` timestamp at which the last chunk of data was received.\n */\n get lastPacketTime(): number {\n this._trigger();\n return this._lastPacketTime;\n }\n\n /**\n * Whether the stream has finished being consumed.\n */\n get isComplete(): boolean {\n this._trigger();\n return this._isComplete;\n }\n\n /**\n * Whether the request was aborted before the stream finished being consumed.\n */\n get isCancelled(): boolean {\n this._trigger();\n return this._isCancelled;\n }\n\n /**\n * Whether an error occurred while consuming the stream.\n */\n get isErrored(): boolean {\n this._trigger();\n return this._isErrored;\n }\n\n /**\n * The error that occurred while consuming the stream, if any.\n */\n get error(): Error | null {\n this._trigger();\n return this._error;\n }\n\n /**\n * The number of milliseconds elapsed since the stream started being\n * consumed, using the last packet time (or end time, once complete)\n * as the endpoint.\n */\n get elapsedTime(): number {\n return (this.endTime || this.lastPacketTime) - this.startTime;\n }\n\n /**\n * The ratio (0 to 1) of {@link RequestLoadingState.bytesLoaded | bytesLoaded}\n * to {@link RequestLoadingState.sizeHint | sizeHint}, or `0` if no size hint is available.\n */\n get completedRatio(): number {\n return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;\n }\n\n /**\n * The inverse of {@link RequestLoadingState.completedRatio | completedRatio}.\n */\n get remainingRatio(): number {\n return 1 - this.completedRatio;\n }\n\n /**\n * The total number of milliseconds elapsed between\n * {@link RequestLoadingState.startTime | startTime} and {@link RequestLoadingState.endTime | endTime}.\n */\n get duration(): number {\n return this.endTime - this.startTime;\n }\n\n /**\n * The average download speed in bytes per second.\n */\n get speed(): number {\n // bytes per second\n return this.bytesLoaded / (this.elapsedTime / 1000);\n }\n\n constructor(future: Future<unknown>) {\n this._future = future;\n }\n\n /**\n * Aborts the underlying request.\n */\n abort = (): void => {\n this._future.abort();\n };\n}\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isPending', true);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isStarted', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isComplete', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isCancelled', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isErrored', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_error', null);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_sizeHint', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_bytesLoaded', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_startTime', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_endTime', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_lastPacketTime', 0);\n\n/**\n * The state of a request in the \"pending\"\n * state. This is the default initial state.\n *\n * Extends the {@link PendingPromise} interface.\n *\n */\nexport interface PendingRequest extends PendingPromise {\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n loadingState: RequestLoadingState;\n request: null;\n response: null;\n}\n/**\n * The state of a request in the \"fulfilled\" state.\n * This is the state of a request that has resolved\n * successfully.\n *\n * Extends the {@link ResolvedPromise} interface.\n *\n */\nexport interface ResolvedRequest<RT> extends ResolvedPromise<RT> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n /**\n * A lazily created {@link RequestLoadingState} instance\n * which provides a number of reactive properties that can be used\n * to build UIs that respond to the progress of a request.\n */\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n/**\n * The state of a request in the \"rejected\" state.\n * This is the state of a request that has rejected\n * with an error.\n *\n * Extends the {@link RejectedPromise} interface.\n *\n */\nexport interface RejectedRequest<\n RT,\n E extends StructuredErrorDocument = StructuredErrorDocument,\n> extends RejectedPromise<E> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n/**\n * The state of a request in the \"cancelled\" state.\n * This is the state of a promise that has been\n * cancelled.\n *\n */\nexport interface CancelledRequest<RT, E extends StructuredErrorDocument = StructuredErrorDocument> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * The status of the request.\n *\n */\n status: 'cancelled';\n\n /**\n * Whether the request is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the request is pending.\n *\n */\n isLoading: false;\n\n /**\n * Whether the request has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the request has rejected\n * with an error.\n *\n */\n isError: true;\n\n /**\n * Once the request has resolved, this will\n * be the value the request resolved to.\n *\n */\n value: null;\n /**\n * Once the request has resolved, this will\n * be the value the request resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the request has rejected, this will\n * be the error the request rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: E;\n\n /**\n * Once the request has rejected, this will\n * be the error the request rejected with.\n *\n */\n reason: E;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: true;\n\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n\nexport interface PrivateRequestState {\n _loadingState?: RequestLoadingState;\n _request: Future<unknown>;\n}\n\n/**\n * RequestState extends the concept of {@link PromiseState} to provide a reactive\n * wrapper for a request {@link Future} which allows you write declarative code\n * around a Future's control flow.\n *\n * It is useful in both Template and JavaScript contexts, allowing you\n * to quickly derive behaviors and data from pending, error and success\n * states.\n *\n * The key difference between a {@link Promise} and a Future is that Futures provide\n * access to a {@link ReadableStream | stream} of their content, the {@link RequestKey} of the request (if any)\n * as well as the ability to attempt to {@link Future.abort | abort} the request.\n *\n * ```ts\n * interface Future<T> extends Promise<T>> {\n * getStream(): Promise<ReadableStream>;\n * abort(): void;\n * lid: RequestKey | null;\n * }\n * ```\n *\n * These additional APIs allow us to craft even richer state experiences.\n *\n * To get the state of a request, use {@link getRequestState}.\n *\n * See also:\n * - {@link PendingRequest}\n * - {@link ResolvedRequest}\n * - {@link RejectedRequest}\n * - {@link CancelledRequest}\n *\n */\nexport type RequestState<RT = unknown, E extends StructuredErrorDocument = StructuredErrorDocument> =\n | PendingRequest\n | ResolvedRequest<RT>\n | RejectedRequest<RT, E>\n | CancelledRequest<RT, E>;\n\nconst RequestStateProto = {};\n\nfunction performRefresh<RT = unknown>(\n requester: RequestManager | Store,\n request: RequestInfo<RT>,\n isReload: boolean | null\n): Future<RT> {\n const req = Object.assign({}, request);\n const cacheOptions = Object.assign({}, req.cacheOptions);\n if (isReload) {\n // force direct to network\n cacheOptions.reload = true;\n } else if (isReload === false) {\n // delete reload to ensure we use backgroundReload / policy\n delete cacheOptions.reload;\n cacheOptions.backgroundReload = true;\n } else {\n // delete props to ensure we use the policy\n delete cacheOptions.backgroundReload;\n delete cacheOptions.reload;\n }\n req.cacheOptions = cacheOptions;\n return requester.request(req);\n}\n\n// TODO introduce a new mechanism for defining multiple properties\n// that share a common signal\ndefineSignal(RequestStateProto, 'reason', null);\ndefineSignal(RequestStateProto, 'value', null);\ndefineSignal(RequestStateProto, 'result', null);\ndefineSignal(RequestStateProto, 'error', null);\ndefineSignal(RequestStateProto, 'status', 'pending');\ndefineSignal(RequestStateProto, 'isPending', true);\ndefineSignal(RequestStateProto, 'isLoading', true);\ndefineSignal(RequestStateProto, 'isSuccess', false);\ndefineSignal(RequestStateProto, 'isError', false);\ndefineSignal(RequestStateProto, 'request', null);\ndefineSignal(RequestStateProto, 'response', null);\n\nObject.defineProperty(RequestStateProto, 'isCancelled', {\n get(this: RequestState): boolean {\n return this.isError && isAbortError(this.reason);\n },\n});\nObject.defineProperty(RequestStateProto, 'loadingState', {\n get(this: RequestState & PrivateRequestState): RequestLoadingState {\n if (!this._loadingState) {\n this._loadingState = new RequestLoadingState(this._request);\n }\n\n return this._loadingState;\n },\n});\n\nexport function createRequestState<RT, E>(future: Future<RT>): Readonly<RequestState<RT, StructuredErrorDocument<E>>> {\n const state = getPromiseResult(\n future as unknown as Awaitable<StructuredDataDocument<RT>, StructuredErrorDocument<E>>\n );\n const promiseState = Object.create(RequestStateProto) as RequestState<RT, StructuredErrorDocument<E>> &\n PrivateRequestState;\n promiseState._request = future;\n // @ts-expect-error - we still attach it for PendingState\n promiseState.reload = (): Future<RT> => {\n assert(\n `Cannot reload a request that is still pending. Await or abort the original request first.`,\n !promiseState.isPending\n );\n\n return performRefresh<RT>(future.requester, promiseState.request!, true);\n };\n\n // @ts-expect-error - we still attach it for PendingState\n promiseState.refresh = (usePolicy: boolean = false): Future<RT> => {\n assert(\n `Cannot refresh a request that is still pending. Await or abort the original request first.`,\n !promiseState.isPending\n );\n\n return performRefresh<RT>(future.requester, promiseState.request!, usePolicy === true ? null : false);\n };\n\n if (state) {\n if (state.isError) {\n promiseState.error = state.result;\n promiseState.reason = state.result;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = state.result.request as ImmutableRequestInfo<RT>;\n promiseState.response = state.result.response;\n } else {\n promiseState.result = state.result.content;\n promiseState.value = state.result.content;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = state.result.request as ImmutableRequestInfo<RT>;\n promiseState.response = state.result.response;\n }\n } else {\n void future.then(\n (result) => {\n setPromiseResult(future, { isError: false, result });\n promiseState.result = result.content;\n promiseState.value = result.content;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = result.request as ImmutableRequestInfo<RT>;\n promiseState.response = result.response;\n },\n (error: StructuredErrorDocument<E>) => {\n setPromiseResult(future, { isError: true, result: error });\n promiseState.error = error;\n promiseState.reason = error;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = error.request as ImmutableRequestInfo<RT>;\n promiseState.response = error.response;\n }\n );\n }\n\n return promiseState;\n}\n\n/**\n * `getRequestState` can be used in both JavaScript and Template contexts.\n *\n * ```ts\n * import { getRequestState } from '@warp-drive/ember';\n *\n * const state = getRequestState(future);\n * ```\n *\n * For instance, we could write a getter on a component that updates whenever\n * the request state advances or the future changes, by combining the function\n * with the use of `@cached`\n *\n * ```ts\n * class Component {\n * @cached\n * get title() {\n * const state = getRequestState(this.args.request);\n * if (state.isPending) {\n * return 'loading...';\n * }\n * if (state.isError) { return null; }\n * return state.result.title;\n * }\n * }\n * ```\n *\n * Or in a template as a helper:\n *\n * ```gjs\n * import { getRequestState } from '@warp-drive/ember';\n *\n * <template>\n * {{#let (getRequestState @request) as |state|}}\n * {{#if state.isPending}}\n * <Spinner />\n * {{else if state.isError}}\n * <ErrorForm @error={{state.error}} />\n * {{else}}\n * <h1>{{state.result.title}}</h1>\n * {{/if}}\n * {{/let}}\n * </template>\n * ```\n *\n * If looking to use in a template, consider also the `<Request />` component\n * which offers a number of additional capabilities for requests *beyond* what\n * `RequestState` provides.\n *\n */\nexport function getRequestState<RT, E>(future: Future<RT>): Readonly<RequestState<RT, StructuredErrorDocument<E>>> {\n let state = RequestCache.get(future);\n\n if (!state) {\n state = createRequestState<RT, E>(future);\n RequestCache.set(future, state);\n }\n\n return state as Readonly<RequestState<RT, StructuredErrorDocument<E>>>;\n}\n","const deferred = /* @__PURE__ */ new WeakMap();\nfunction deferDecorator(proto, prop, desc) {\n let map = deferred.get(proto);\n if (!map) {\n map = /* @__PURE__ */ new Map();\n deferred.set(proto, map);\n }\n map.set(prop, desc);\n}\nfunction findDeferredDecorator(target, prop) {\n var _a;\n let cursor = target.prototype;\n while (cursor) {\n let desc = (_a = deferred.get(cursor)) == null ? void 0 : _a.get(prop);\n if (desc) {\n return desc;\n }\n cursor = Object.getPrototypeOf(cursor);\n }\n}\nfunction decorateFieldV1(target, prop, decorators, initializer) {\n return decorateFieldV2(target.prototype, prop, decorators, initializer);\n}\nfunction decorateFieldV2(prototype, prop, decorators, initializer) {\n let desc = {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n };\n if (initializer) {\n desc.initializer = initializer;\n }\n for (let decorator of decorators) {\n desc = decorator(prototype, prop, desc) || desc;\n }\n if (desc.initializer === void 0) {\n Object.defineProperty(prototype, prop, desc);\n } else {\n deferDecorator(prototype, prop, desc);\n }\n}\nfunction decorateMethodV1({ prototype }, prop, decorators) {\n return decorateMethodV2(prototype, prop, decorators);\n}\nfunction decorateMethodV2(prototype, prop, decorators) {\n const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);\n let desc = { ...origDesc };\n for (let decorator of decorators) {\n desc = decorator(prototype, prop, desc) || desc;\n }\n if (desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;\n desc.initializer = void 0;\n }\n Object.defineProperty(prototype, prop, desc);\n}\nfunction initializeDeferredDecorator(target, prop) {\n let desc = findDeferredDecorator(target.constructor, prop);\n if (desc) {\n Object.defineProperty(target, prop, {\n enumerable: desc.enumerable,\n configurable: desc.configurable,\n writable: desc.writable,\n value: desc.initializer ? desc.initializer.call(target) : void 0\n });\n }\n}\nfunction decorateClass(target, decorators) {\n return decorators.reduce(\n (accum, decorator) => decorator(accum) || accum,\n target\n );\n}\nfunction decoratePOJO(pojo, decorated) {\n for (let [type, prop, decorators] of decorated) {\n if (type === \"field\") {\n decoratePojoField(pojo, prop, decorators);\n } else {\n decorateMethodV2(pojo, prop, decorators);\n }\n }\n return pojo;\n}\nfunction decoratePojoField(pojo, prop, decorators) {\n let desc = {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: () => {\n var _a;\n return (_a = Object.getOwnPropertyDescriptor(pojo, prop)) == null ? void 0 : _a.value;\n }\n };\n for (let decorator of decorators) {\n desc = decorator(pojo, prop, desc) || desc;\n }\n if (desc.initializer) {\n desc.value = desc.initializer.call(pojo);\n delete desc.initializer;\n }\n Object.defineProperty(pojo, prop, desc);\n}\nconst runtime = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({\n __proto__: null,\n c: decorateClass,\n f: decorateFieldV1,\n g: decorateFieldV2,\n i: initializeDeferredDecorator,\n m: decorateMethodV1,\n n: decorateMethodV2,\n p: decoratePOJO\n}, Symbol.toStringTag, { value: \"Module\" }));\nexport {\n decorateFieldV1 as a,\n decorateFieldV2 as b,\n decorateMethodV1 as c,\n decorateClass as d,\n decorateMethodV2 as e,\n decoratePOJO as f,\n initializeDeferredDecorator as i,\n runtime as r\n};\n//# sourceMappingURL=runtime--fcdnjmJ.js.map\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { RequestManager, Store, StoreRequestInput } from '../index.ts';\nimport type { Future } from '../request.ts';\nimport type { RequestKey } from '../types/identifier.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\nimport type { PrivateRequestState, RequestState } from './request-state.ts';\nimport { getRequestState } from './request-state.ts';\n\n// default to 30 seconds unavailable before we refresh\nconst DEFAULT_DEADLINE = 30_000;\n/**\n * A symbol used to dispose of a {@link RequestSubscription} when the\n * component or context using it is torn down.\n */\nexport const DISPOSE = (Symbol.dispose || Symbol.for('dispose')) as unknown as '(symbol) dispose';\n\nfunction isNeverString(val: never): string {\n return val;\n}\n\n/**\n * The individual autorefresh strategies a {@link RequestSubscription}\n * may combine, see {@link AutorefreshBehaviorCombos}.\n */\nexport type AutorefreshBehaviorType = 'online' | 'interval' | 'invalid';\n\n/**\n * The value accepted by {@link SubscriptionArgs.autorefresh}: either a\n * boolean, a single {@link AutorefreshBehaviorType}, or a comma-separated\n * combination of up to three of them.\n */\nexport type AutorefreshBehaviorCombos =\n | boolean\n | AutorefreshBehaviorType\n | `${AutorefreshBehaviorType},${AutorefreshBehaviorType}`\n | `${AutorefreshBehaviorType},${AutorefreshBehaviorType},${AutorefreshBehaviorType}`;\n\n/**\n * Utilities to assist in recovering from the error.\n */\nexport interface RecoveryFeatures {\n /**\n * Whether the browser reports that the network is online.\n */\n isOnline: boolean;\n /**\n * Whether the browser reports that the tab is hidden.\n */\n isHidden: boolean;\n /**\n * Retries the request, reloading it from the server.\n */\n retry: () => Promise<void>;\n}\n\n/** @deprecated use {@link RecoveryFeatures} */\nexport type ErrorFeatures = RecoveryFeatures;\n\n/**\n * Utilities for keeping the request fresh\n */\nexport interface ContentFeatures<RT> {\n /**\n * Whether the browser reports that the network is online.\n */\n isOnline: boolean;\n /**\n * Whether the browser reports that the tab is hidden.\n */\n isHidden: boolean;\n /**\n * Whether the subscription is currently refreshing the request.\n */\n isRefreshing: boolean;\n /**\n * Refreshes the request, updating it in the background.\n */\n refresh: () => Promise<void>;\n /**\n * Retries the request, reloading it from the server.\n */\n reload: () => Promise<void>;\n /**\n * Aborts the in-flight refresh/reload request, if any.\n */\n abort?: () => void;\n /**\n * The most recent refresh/reload request that was made, if any.\n */\n latestRequest?: Future<RT>;\n}\n\n/**\n * The args accepted by the `<Request />` component.\n */\nexport interface RequestArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * The {@link RequestSubscription} instance backing the component, if any.\n */\n subscription?: RequestSubscription<RT, E>;\n\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n/**\n * The args accepted by a {@link RequestSubscription}.\n */\n// oxlint-disable-next-line no-unused-vars\nexport interface SubscriptionArgs<RT, E> {\n /**\n * The request to monitor. This should be a `Future` instance returned\n * by either the `store.request` or `store.requestManager.request` methods.\n *\n */\n request?: Future<RT> | undefined | null;\n\n /**\n * A query to use for the request. This should be an object that can be\n * passed to `store.request`. Use this in place of `@request` if you would\n * like the component to also initiate the request.\n *\n */\n query?: StoreRequestInput<RT> | undefined | null;\n\n /**\n * The autorefresh behavior for the request. This can be a boolean, or any\n * combination of the following values: `'online'`, `'interval'`, `'invalid'`.\n *\n * - `'online'`: Refresh the request when the browser comes back online\n * - `'interval'`: Refresh the request at a specified interval\n * - `'invalid'`: Refresh the request when the store emits an invalidation\n *\n * If `true`, this is equivalent to `'online,invalid'`.\n *\n * Defaults to `false`.\n *\n */\n autorefresh?: AutorefreshBehaviorCombos;\n\n /**\n * The number of milliseconds to wait before refreshing the request when the\n * browser comes back online or the network becomes available.\n *\n * This also controls the interval at which the request will be refreshed if\n * the `interval` autorefresh type is enabled.\n *\n * Defaults to `30_000` (30 seconds).\n *\n */\n autorefreshThreshold?: number;\n\n /**\n * The behavior of the request initiated by autorefresh. This can be one of\n * the following values:\n *\n * - `'refresh'`: Refresh the request in the background\n * - `'reload'`: Force a reload of the request\n * - `'policy'` (**default**): Let the store's configured CachePolicy decide whether to\n * reload, refresh, or do nothing.\n *\n * Defaults to `'policy'`.\n *\n */\n autorefreshBehavior?: 'refresh' | 'reload' | 'policy';\n}\n\nexport interface RequestComponentArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n// oxlint-disable-next-line no-unused-vars\nexport interface RequestSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\n/**\n * A reactive class\n *\n * @hideconstructor\n */\nexport class RequestSubscription<RT, E> {\n /**\n * Whether the browser reports that the network is online.\n */\n declare isOnline: boolean;\n\n /**\n * Whether the browser reports that the tab is hidden.\n */\n declare isHidden: boolean;\n\n /**\n * Whether the component is currently refreshing the request.\n */\n declare isRefreshing: boolean;\n\n /**\n * The most recent blocking request that was made, typically\n * the result of a reload.\n *\n * This will never be the original request passed as an arg to\n * the component.\n *\n * @internal\n */\n declare private _localRequest: Future<RT> | undefined;\n\n /**\n * The most recent request that was made, typically due to either a\n * reload or a refresh.\n *\n * This will never be the original request passed as an arg to\n * the component.\n *\n * @internal\n */\n declare private _latestRequest: Future<RT> | undefined;\n\n /**\n * The time at which the network was reported as offline.\n *\n * @internal\n */\n declare private _unavailableStart: number | null;\n /** @internal */\n declare private _intervalStart: number | null;\n /** @internal */\n declare private _nextInterval: number | null;\n /** @internal */\n declare private _invalidated: boolean;\n /** @internal */\n declare private _isUpdating: boolean;\n /** @internal */\n declare private isDestroyed: boolean;\n\n /**\n * The event listener for network status changes,\n * cached to use the reference for removal.\n *\n * @internal\n */\n declare private _onlineChanged: (event: Event) => void;\n\n /**\n * The event listener for visibility status changes,\n * cached to use the reference for removal.\n *\n * @internal\n */\n declare private _backgroundChanged: (event: Event) => void;\n\n /**\n * The last request passed as an arg to the component,\n * cached for comparison.\n *\n * @internal\n */\n declare private _originalRequest: Future<RT> | undefined | null;\n\n /**\n * The last query passed as an arg to the component,\n * cached for comparison.\n *\n * @internal\n */\n declare private _originalQuery: StoreRequestInput<RT> | undefined | null;\n /** @internal */\n declare private _subscription: object | null;\n /** @internal */\n declare private _subscribedTo: object | null;\n /** @internal */\n declare private _args: SubscriptionArgs<RT, E>;\n /**\n * The Store this subscription subscribes to or the RequestManager\n * which issues this request.\n */\n declare store: Store | RequestManager;\n /**\n * The Store or RequestManager that the last subscription is attached to.\n *\n * This differs from 'store' because a <Request /> may be passed a\n * request originating from a different store than the <Request />\n * component would use if it were to issue the request itself.\n *\n * @internal\n */\n private _requester: Store | RequestManager | null;\n\n constructor(store: Store | RequestManager, args: SubscriptionArgs<RT, E>) {\n this._args = args;\n this.store = store;\n this._subscribedTo = null;\n this._subscription = null;\n this._intervalStart = null;\n this._invalidated = false;\n this._nextInterval = null;\n this._requester = null;\n this.isDestroyed = false;\n this[DISPOSE] = _DISPOSE;\n\n this._installListeners();\n void this._beginPolling();\n }\n\n /**\n * @internal\n */\n private async _beginPolling() {\n // await the initial request\n try {\n if (!this.isIdle) {\n await this.request;\n }\n } catch {\n // ignore errors here, we just want to wait for the request to finish\n } finally {\n if (!this.isDestroyed) {\n void this._scheduleInterval();\n }\n }\n }\n\n /**\n * Whether neither a `request` nor a `query` arg was provided, and so\n * this subscription has nothing to fetch or monitor.\n */\n @memoized\n get isIdle(): boolean {\n const { request, query } = this._args;\n\n return Boolean(!request && !query);\n }\n\n /**\n * The set of {@link AutorefreshBehaviorType}s this subscription is\n * configured to autorefresh for, derived from {@link SubscriptionArgs.autorefresh}.\n */\n @memoized\n get autorefreshTypes(): Set<AutorefreshBehaviorType> {\n const { autorefresh } = this._args;\n let types: AutorefreshBehaviorType[];\n\n if (autorefresh === true) {\n types = ['online', 'invalid'];\n } else if (typeof autorefresh === 'string') {\n types = autorefresh.split(',') as AutorefreshBehaviorType[];\n } else {\n types = [];\n }\n\n return new Set(types);\n }\n\n // we only run this function on component creation\n // and when an update is triggered, so it does not\n // react to changes in the autorefreshThreshold\n // or autorefresh args.\n //\n // if we need to react to those changes, we can\n // use a modifier or internal component or some\n // such to trigger a re-run of this function.\n /** @internal */\n private async _scheduleInterval() {\n const { autorefreshThreshold } = this._args;\n const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;\n if (\n // dont schedule in SSR\n typeof window === 'undefined' ||\n // dont schedule without a threshold\n !hasValidThreshold ||\n // dont schedule if we weren't told to\n !this.autorefreshTypes.has('interval') ||\n // dont schedule if we're already scheduled\n this._intervalStart !== null\n ) {\n return;\n }\n\n // if we have a current request, wait for it to finish\n // before scheduling the next one\n if (this._latestRequest) {\n try {\n await this._latestRequest;\n } catch {\n // ignore errors here, we just want to wait for the request to finish\n }\n\n if (this.isDestroyed) {\n return;\n }\n }\n\n // setup the next interval\n this._intervalStart = Date.now();\n this._nextInterval = setTimeout(() => {\n this._maybeUpdate();\n }, autorefreshThreshold);\n }\n\n /** @internal */\n private _clearInterval() {\n if (this._nextInterval) {\n clearTimeout(this._nextInterval);\n this._intervalStart = null;\n }\n }\n /**\n * @internal\n */\n private _updateSubscriptions() {\n if (this.isIdle) {\n return;\n }\n const requestId = this._request.lid;\n\n // if we're already subscribed to this request, we don't need to do anything\n if (this._subscribedTo === requestId) {\n return;\n }\n\n // if we're subscribed to a different request, we need to unsubscribe\n this._removeSubscriptions();\n\n // if we have a request, we need to subscribe to it\n const store = this._getRequester();\n this._requester = store;\n if (requestId && isStore(store)) {\n this._subscribedTo = requestId;\n\n this._subscription = store.notifications.subscribe(\n requestId,\n (_id: RequestKey, op: 'invalidated' | 'state' | 'added' | 'updated' | 'removed') => {\n // ignore subscription events that occur while our own component's request\n // is occurring\n if (this._isUpdating) {\n return;\n }\n switch (op) {\n case 'invalidated': {\n // if we're subscribed to invalidations, we need to update\n if (this.autorefreshTypes.has('invalid')) {\n this._invalidated = true;\n this._maybeUpdate();\n }\n break;\n }\n case 'state': {\n const latest = store.requestManager._deduped.get(requestId);\n const priority = latest?.priority;\n const state = this.reqState;\n if (!priority) {\n // if there is no priority, we have completed whatever request\n // was occurring and so we are no longer refreshing (if we were)\n this.isRefreshing = false;\n } else if (priority.blocking && !state.isLoading) {\n // if we are blocking, there is an active request for this identity\n // that MUST be fulfilled from network (not cache).\n // Thus this is not \"refreshing\" because we should clear out and\n // block on this request.\n //\n // we receive state notifications when either a request initiates\n // or completes.\n //\n // In the completes case: we may receive the state notification\n // slightly before the request is finalized because the NotificationManager\n // may sync flush it (and thus deliver it before the microtask completes)\n //\n // In the initiates case: we aren't supposed to receive one unless there\n // is no other request in flight for this identity.\n //\n // However, there is a race condition here where the completed\n // notification can trigger an update that generates a new request\n // thus giving us an initiated notification before the older request\n // finalizes.\n //\n // When this occurs, if the triggered update happens to have caused\n // a new request to be made for the same identity AND that request\n // is the one passed into this component as the @request arg, then\n // getRequestState will return the state of the new request.\n // We can detect this by checking if the request state is \"loading\"\n // as outside of this case we would have a completed request.\n //\n // That is the reason for the `&& !state.isLoading` check above.\n\n // TODO should we just treat this as refreshing?\n this.isRefreshing = false;\n this._maybeUpdate('policy', true);\n } else {\n this.isRefreshing = true;\n }\n }\n }\n }\n );\n }\n }\n\n /**\n * @internal\n */\n private _removeSubscriptions() {\n const store = this._requester;\n if (this._subscription && store && isStore(store)) {\n store.notifications.unsubscribe(this._subscription);\n this._subscribedTo = null;\n this._subscription = null;\n this._requester = null;\n }\n }\n\n /**\n * Install the event listeners for network and visibility changes.\n *\n * This is only done in environments that provide a fully-featured global\n * `window` and/or `document`. Some non-DOM environments (e.g. React Native,\n * SSR/Node, workers) may provide a `window` global without the APIs we\n * rely on here (or no `window`/`document` at all), in which case we skip\n * attaching the corresponding listeners rather than throwing.\n *\n * @internal\n */\n private _installListeners() {\n const hasWindow = typeof window !== 'undefined';\n const hasDocument = typeof document !== 'undefined';\n const hasWindowEvents = hasWindow && typeof window.addEventListener === 'function';\n const hasDocumentEvents = hasDocument && typeof document.addEventListener === 'function';\n\n this.isOnline = hasWindow && typeof window.navigator?.onLine === 'boolean' ? window.navigator.onLine : true;\n this._unavailableStart = this.isOnline ? null : Date.now();\n this.isHidden =\n hasDocument && typeof document.visibilityState === 'string' && document.visibilityState === 'hidden';\n\n if (hasWindowEvents) {\n this._onlineChanged = (event: Event) => {\n this.isOnline = event.type === 'online';\n if (event.type === 'offline' && this._unavailableStart === null) {\n this._unavailableStart = Date.now();\n }\n this._maybeUpdate();\n };\n\n window.addEventListener('online', this._onlineChanged, { passive: true, capture: true });\n window.addEventListener('offline', this._onlineChanged, { passive: true, capture: true });\n }\n\n if (hasDocumentEvents) {\n this._backgroundChanged = () => {\n const isHidden = document.visibilityState === 'hidden';\n this.isHidden = isHidden;\n\n if (isHidden && this._unavailableStart === null) {\n this._unavailableStart = Date.now();\n }\n\n this._maybeUpdate();\n };\n\n document.addEventListener('visibilitychange', this._backgroundChanged, { passive: true, capture: true });\n }\n }\n\n /**\n * If the network is online and the tab is visible, either reload or refresh the request\n * based on the component's configuration and the requested update mode.\n *\n * Valid modes are:\n *\n * - `'reload'`: Force a reload of the request.\n * - `'refresh'`: Refresh the request in the background.\n * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.\n * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.\n *\n * @internal\n */\n private _maybeUpdate(mode?: 'reload' | 'refresh' | 'policy' | '_invalidated', silent?: boolean): void {\n if (this.isIdle) {\n return;\n }\n\n const { reqState } = this;\n if (reqState.isPending) {\n return;\n }\n\n const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));\n\n if (!canAttempt) {\n if (!silent && mode && mode !== '_invalidated') {\n throw new Error(`Reload not available: the network is not online or the tab is hidden`);\n }\n\n return;\n }\n\n const { autorefreshTypes } = this;\n let shouldAttempt = this._invalidated || Boolean(mode);\n\n if (!shouldAttempt && autorefreshTypes.has('online')) {\n const { _unavailableStart } = this;\n const { autorefreshThreshold } = this._args;\n const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;\n shouldAttempt = Boolean(_unavailableStart && Date.now() - _unavailableStart > deadline);\n }\n\n if (!shouldAttempt && autorefreshTypes.has('interval')) {\n const { _intervalStart } = this;\n const { autorefreshThreshold } = this._args;\n\n if (_intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {\n shouldAttempt = Boolean(Date.now() - _intervalStart >= autorefreshThreshold);\n }\n }\n\n this._unavailableStart = null;\n this._invalidated = false;\n\n if (shouldAttempt) {\n this._clearInterval();\n this._isUpdating = true;\n\n const realMode = mode === '_invalidated' ? null : mode;\n const val = realMode ?? this._args.autorefreshBehavior ?? 'policy';\n\n // if the future was generated by an older store version, it may not have\n // a requester set. In this case we append it to ensure that reload and\n // refresh will work appropriately.\n const requester = this._getRequester();\n if (!(reqState as unknown as PrivateRequestState)._request.requester) {\n (reqState as unknown as PrivateRequestState)._request.requester = requester;\n }\n\n switch (val) {\n case 'reload':\n this._latestRequest = reqState.reload();\n break;\n case 'refresh':\n this._latestRequest = reqState.refresh();\n break;\n case 'policy':\n this._latestRequest = reqState.refresh(true);\n break;\n default:\n assert(`Invalid ${mode ? 'update mode' : '@autorefreshBehavior'} for <Request />: ${isNeverString(val)}`);\n }\n\n if (val !== 'refresh') {\n this._localRequest = this._latestRequest;\n }\n\n void this._scheduleInterval();\n void this._latestRequest.finally(() => {\n this._isUpdating = false;\n });\n } else {\n // TODO probably want this\n // void this.scheduleInterval();\n }\n }\n\n /**\n * @internal\n */\n private _getRequester(): Store | RequestManager {\n // Note: we check for the requester's presence\n // as well as the request's presence because we may\n // be subscribed to a request issued by a store from an older\n // version of the library that didn't yet set requester.\n if (this._args.request?.requester) {\n return this._args.request.requester;\n }\n\n return this.store;\n }\n\n /**\n * Retry the request, reloading it from the server.\n */\n retry = async (): Promise<void> => {\n this._maybeUpdate('reload');\n await this._localRequest;\n };\n\n /**\n * Refresh the request, updating it in the background.\n */\n refresh = async (): Promise<void> => {\n this._maybeUpdate('refresh');\n await this._latestRequest;\n };\n\n /**\n * features to yield to the error slot of a component\n */\n @memoized\n get errorFeatures(): RecoveryFeatures {\n return {\n isHidden: this.isHidden,\n isOnline: this.isOnline,\n retry: this.retry,\n };\n }\n\n /**\n * features to yield to the content slot of a component\n */\n @memoized\n get contentFeatures(): ContentFeatures<RT> {\n const feat: ContentFeatures<RT> = {\n isHidden: this.isHidden,\n isOnline: this.isOnline,\n reload: this.retry,\n refresh: this.refresh,\n isRefreshing: this.isRefreshing,\n latestRequest: this._latestRequest,\n };\n\n if (feat.isRefreshing) {\n feat.abort = () => {\n this._latestRequest?.abort();\n };\n }\n\n return feat;\n }\n\n /**\n * @internal\n */\n @memoized\n get _request(): Future<RT> {\n const { request, query } = this._args;\n assert(`Cannot use both @request and @query args with the <Request> component`, !request || !query);\n const { _localRequest, _originalRequest, _originalQuery } = this;\n const isOriginalRequest = request === _originalRequest && query === _originalQuery;\n\n if (_localRequest && isOriginalRequest) {\n return _localRequest;\n }\n\n // update state checks for the next time\n this._originalQuery = query;\n this._originalRequest = request;\n\n if (request) {\n return request;\n }\n assert(`You must provide either @request or an @query arg with the <Request> component`, query);\n return (this.store as Store).request(query);\n }\n\n /**\n * The {@link Future} this subscription is currently monitoring, and\n * (re-)subscribes to notifications for as a side effect of access.\n */\n @memoized\n get request(): Future<RT> {\n if (DEBUG) {\n try {\n const request = this._request;\n this._updateSubscriptions();\n return request;\n } catch (e) {\n // oxlint-disable-next-line no-console\n console.log(e);\n throw new Error(`Unable to initialize the request`, { cause: e });\n }\n } else {\n const request = this._request;\n this._updateSubscriptions();\n return request;\n }\n }\n\n /**\n * The {@link RequestState} for {@link RequestSubscription.request | request}.\n */\n get reqState(): RequestState<RT, StructuredErrorDocument<E>> {\n return getRequestState<RT, E>(this.request);\n }\n\n /**\n * The resolved content of the request, once it has succeeded.\n */\n get result() {\n return this.reqState.result as RT;\n }\n}\n\ndefineSignal(RequestSubscription.prototype, 'isOnline', true);\ndefineSignal(RequestSubscription.prototype, 'isHidden', false);\ndefineSignal(RequestSubscription.prototype, 'isRefreshing', false);\ndefineSignal(RequestSubscription.prototype, '_localRequest', undefined);\ndefineSignal(RequestSubscription.prototype, '_latestRequest', undefined);\n\nfunction isStore(store: Store | RequestManager): store is Store {\n return 'requestManager' in store;\n}\n\n/**\n * Creates a {@link RequestSubscription}, the reactive class powering the\n * `<Request />` component's autorefresh, retry, and refresh behaviors.\n */\nexport function createRequestSubscription<RT, E>(\n store: Store | RequestManager,\n args: SubscriptionArgs<RT, E>\n): RequestSubscription<RT, E> {\n return new RequestSubscription(store, args);\n}\n\ninterface PrivateRequestSubscription {\n isDestroyed: boolean;\n _removeSubscriptions(): void;\n _clearInterval(): void;\n _onlineChanged: () => void;\n _backgroundChanged: () => void;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivateRequestSubscription {\n return sub as PrivateRequestSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: RequestSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n self._removeSubscriptions();\n self._clearInterval();\n\n if (self._onlineChanged && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {\n window.removeEventListener('online', self._onlineChanged, { passive: true, capture: true } as unknown as boolean);\n window.removeEventListener('offline', self._onlineChanged, {\n passive: true,\n capture: true,\n } as unknown as boolean);\n }\n\n if (\n self._backgroundChanged &&\n typeof document !== 'undefined' &&\n typeof document.removeEventListener === 'function'\n ) {\n document.removeEventListener('visibilitychange', self._backgroundChanged, {\n passive: true,\n capture: true,\n } as unknown as boolean);\n }\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport type { Link } from '../types/spec/json-api-raw.ts';\nimport type { PaginationCache } from './pagination-cache.ts';\nimport { memoized, signal } from './reactivity/signal';\nimport type { RequestState } from './request-state.ts';\nimport { getRequestState } from './request-state.ts';\n\nconst { abs } = Math;\n\n/**\n * Extracts the `data` member of a document type, or the document type itself\n * when it has no `data` member.\n */\nexport type ContentData<RT> = RT extends { data: infer D } ? D : RT;\n\n/**\n * The element type of a collection document's `data` array — the item type an\n * infinite view renders. See {@link PaginationState.data}.\n */\nexport type ContentItem<RT> = ContentData<RT> extends readonly (infer I)[] ? I : ContentData<RT>;\n\n/** @internal */\nexport function 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\ntype Links = {\n prev?: string | null;\n next?: string | null;\n first?: string | null;\n last?: string | null;\n};\n\n/**\n * A single page of a paginated collection: its request, its loaded document, and\n * its links to neighboring pages in the shared page graph.\n *\n * Pages are yielded to consumers as `Readonly<PageCache>` — through\n * {@link PaginationState.activePage}, {@link PaginationState.pages}, and the\n * relational getters below — to read a page's data and request status when\n * building pagination UIs:\n *\n * ```ts\n * const page = paginationState.activePage;\n *\n * if (page?.isLoading) {\n * // show a spinner\n * } else if (page?.isError) {\n * // show page.reason\n * } else {\n * // render page.data\n * }\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PageCache<RT = unknown, E = unknown> {\n /** @internal */\n declare manager: PaginationCache<RT, E>;\n\n /**\n * The request that loaded (or is loading) this page, or `null` if the page is\n * known from links but was never requested. Wrap it in a `<Request>` component\n * to render the page's loading, error, and content states.\n */\n @signal declare request: Future<RT> | null;\n\n /** @internal */\n @signal declare state: Readonly<RequestState<RT, StructuredErrorDocument<E>>> | null;\n\n /** The `self` link of this page — the URL that identifies it in the collection. */\n @signal declare selfLink: string | null;\n\n /** The `prev` link of this page, or `null` at the start of the collection. */\n @signal declare prevLink: string | null;\n\n /** The `next` link of this page, or `null` at the end of the collection. */\n @signal declare nextLink: string | null;\n\n /** The `first` link of the collection, when the response exposed one. */\n @signal declare firstLink: string | null;\n\n /** The `last` link of the collection, when the response exposed one. */\n @signal declare lastLink: string | null;\n\n /**\n * The 1-based page number, or `0` when unknown (for example cursor-based\n * pagination, where pages have no ordinal position). Derived from the\n * collection's {@link PageHints}.\n */\n @signal declare pageNumber: number;\n\n /** @internal */\n @signal declare before: Readonly<PageCache<RT, E>> | null;\n /** @internal */\n @signal declare after: Readonly<PageCache<RT, E>> | null;\n\n constructor(manager: PaginationCache<RT, E>, url: string) {\n this.manager = manager;\n this.pageNumber = 0;\n this.selfLink = url;\n }\n\n /**\n * The document this page's request resolved to, or `null` while it has not\n * resolved.\n */\n @memoized\n get value(): RT | null {\n return this.state?.value as RT | null;\n }\n\n /**\n * The `data` member of the loaded document — the page's items — or `null`\n * while the page has not loaded.\n */\n @memoized\n get data(): ContentData<RT> | null {\n return ((this.value as { data?: unknown } | null)?.data ?? null) as ContentData<RT> | null;\n }\n\n /**\n * Whether a request has ever been issued for this page. `false` for pages that\n * are known only from links.\n */\n @memoized\n get isRequested(): boolean {\n return Boolean(this.state);\n }\n\n /** Whether this page's request has settled (successfully or with an error). */\n @memoized\n get isLoaded(): boolean {\n return this.isSuccess || this.isError;\n }\n\n /** Whether this page's request is currently in flight. */\n @memoized\n get isLoading(): boolean {\n return Boolean(this.state?.isLoading);\n }\n\n /** Whether this page's request resolved successfully. */\n @memoized\n get isSuccess(): boolean {\n return Boolean(this.state?.isSuccess);\n }\n\n /** Whether this page's request was cancelled (aborted). */\n @memoized\n get isCancelled(): boolean {\n return Boolean(this.state?.isCancelled);\n }\n\n /** Whether this page's request rejected with an error. */\n @memoized\n get isError(): boolean {\n return Boolean(this.state?.isError);\n }\n\n /** The error this page's request rejected with, or `null` if it did not reject. */\n @memoized\n get reason(): StructuredErrorDocument<E> | null {\n return this.state?.reason ?? null;\n }\n\n /** The page at this page's `prev` link, or `null` at the start of the collection. */\n @memoized\n get prev(): PageCache<RT, E> | null {\n const url = this.prevLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The page at this page's `next` link, or `null` at the end of the collection. */\n @memoized\n get next(): PageCache<RT, E> | null {\n const url = this.nextLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The first page of the collection, when the response exposed a `first` link. */\n @memoized\n get first(): PageCache<RT, E> | null {\n const url = this.firstLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The last page of the collection, when the response exposed a `last` link. */\n @memoized\n get last(): PageCache<RT, E> | null {\n const url = this.lastLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** @internal */\n @memoized\n get isLinked(): boolean {\n return Boolean(this.before || this.after);\n }\n\n /** @internal */\n async load(request: Future<RT>): Promise<ReactiveDocument<unknown> | null> {\n try {\n this.request = request;\n this.state = getRequestState<RT, E>(this.request);\n const value = await this.request;\n const content = value.content as ReactiveDocument<unknown>;\n\n const self = getHref(content?.links?.self);\n const first = getHref(content?.links?.first);\n const last = getHref(content?.links?.last);\n const next = getHref(content?.links?.next);\n const prev = getHref(content?.links?.prev);\n\n assert('Expected the page to have a self link', self);\n\n // The page number is a hint. When the response exposes it, rely on it. When\n // absent (`0`, e.g. cursor pagination), keep whatever relative number a\n // neighbor already assigned via `setPageNumber` rather than clobbering it.\n const pageNumber = this.getPageNumber(content);\n if (pageNumber) {\n this.pageNumber = pageNumber;\n }\n\n const firstPage = first ? this.manager.getPageCache(first) : null;\n const lastPage = last ? this.manager.getPageCache(last) : null;\n const prevPage = prev ? this.manager.getPageCache(prev) : null;\n const nextPage = next ? this.manager.getPageCache(next) : null;\n\n if (firstPage) {\n this.firstLink = first;\n firstPage.setPageNumber(1);\n if (!firstPage.after) {\n firstPage.updateLinkage({ after: this });\n }\n }\n\n if (lastPage) {\n this.lastLink = last;\n lastPage.setPageNumber(this.manager.totalPages);\n if (!lastPage.before) {\n lastPage.updateLinkage({ before: this });\n }\n }\n\n if (nextPage) {\n this.nextLink = next;\n nextPage.setPageNumber(this.pageNumber + 1);\n nextPage.updateLinks({ prev: self });\n }\n\n if (prevPage) {\n this.prevLink = prev;\n prevPage.setPageNumber(this.pageNumber - 1);\n prevPage.updateLinks({ next: self });\n }\n\n if (this.isLinked) {\n if (prevPage) prevPage.updateLinkage({ after: this });\n if (nextPage) nextPage.updateLinkage({ before: this });\n } else if (prevPage?.isLinked) {\n this.updateLinkage({ before: prevPage });\n if (nextPage) nextPage.updateLinkage({ before: this });\n } else if (nextPage?.isLinked) {\n this.updateLinkage({ after: nextPage });\n if (prevPage) prevPage.updateLinkage({ after: this });\n } else if ((prevPage || nextPage) && (firstPage || lastPage)) {\n this.lookupLinkage(firstPage, lastPage);\n } else if (prevPage || nextPage) {\n this.updateLinkage({ before: prevPage, after: nextPage });\n }\n\n return content;\n } catch {\n // no-op\n }\n\n return null;\n }\n\n /** @internal */\n updateLinkage({ before, after }: { before?: PageCache<RT, E> | null; after?: PageCache<RT, E> | null }): void {\n assert('Expected at least one of before or after page states to link to this page', before || after);\n\n const leftSide = before ?? after?.before;\n const rightSide = after ?? before?.after;\n\n if (leftSide && leftSide !== this) {\n leftSide.setAfter(this);\n this.setBefore(leftSide);\n }\n\n if (rightSide && rightSide !== this) {\n rightSide.setBefore(this);\n this.setAfter(rightSide);\n }\n }\n\n /** @internal */\n lookupLinkage(firstPage: PageCache<RT, E> | null, lastPage: PageCache<RT, E> | null): void {\n assert('Expected at least one of firstPage or lastPage to lookup linkage against', firstPage || lastPage);\n\n if (firstPage && lastPage) {\n const firstPageDelta = abs(this.pageNumber - firstPage.pageNumber);\n const lastPageDelta = abs(this.pageNumber - lastPage.pageNumber);\n\n if (firstPageDelta <= lastPageDelta) {\n this.lookupLinkageForward(firstPage);\n } else {\n this.lookupLinkageBackwards(lastPage);\n }\n } else if (firstPage) {\n this.lookupLinkageForward(firstPage);\n } else if (lastPage) {\n this.lookupLinkageBackwards(lastPage);\n }\n }\n\n /** @internal */\n lookupLinkageForward(page: PageCache<RT, E>): void {\n while (page.after && page.after.pageNumber < this.pageNumber) {\n page = page.after;\n }\n\n this.updateLinkage({ before: page });\n }\n\n /** @internal */\n lookupLinkageBackwards(page: PageCache<RT, E>): void {\n while (page.before && page.before.pageNumber > this.pageNumber) {\n page = page.before;\n }\n\n this.updateLinkage({ after: page });\n }\n\n /** @internal */\n setBefore(page: Readonly<PageCache<RT, E>> | null): void {\n assert('Expected the before page to be a different page, got the same page', page !== this);\n this.before = page;\n }\n\n /** @internal */\n setAfter(page: Readonly<PageCache<RT, E>> | null): void {\n assert('Expected the after page to be a different page, got the same page', page !== this);\n this.after = page;\n }\n\n /** @internal */\n getPageNumber(document: ReactiveDocument<unknown>): number {\n return this.manager.readPageHints(document).currentPage;\n }\n\n /** @internal */\n updateLinks = ({ prev, next, first, last }: Links): void => {\n if (prev) {\n this.prevLink = prev;\n }\n if (next) {\n this.nextLink = next;\n }\n if (first) {\n this.firstLink = first;\n }\n if (last) {\n this.lastLink = last;\n }\n };\n\n /** @internal */\n setPageNumber = (pageNumber: number): void => {\n if (!this.pageNumber) {\n this.pageNumber = pageNumber;\n }\n };\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { ContentItem } from './page-cache.ts';\nimport { PageCache } from './page-cache.ts';\nimport { memoized, signal } from './reactivity/signal';\n\nconst PaginationCacheMap = new Map<string, PaginationCache>();\n\n/**\n * A hint function for extracting the `currentPage` and `totalPages` from a loaded\n * document, for when the response does not expose these values through the\n * default `meta` locations. Provided by the consumer via `<Paginate />`'s\n * `@pageHints` arg:\n *\n * ```gts\n * <Paginate @pageHints={{...}} />\n * ```\n *\n * Since these values are attached to the shared {@link PaginationCache}, the hint is\n * a property of the *collection*, not the component. Every `<Paginate />` sharing a\n * collection must provide the same function reference — define it once at module\n * scope and import it everywhere.\n *\n * @since 5.9.0\n * @public\n */\nexport interface PageHints {\n (document: ReactiveDocument<unknown>): { currentPage: number; totalPages: number };\n}\n\n/**\n * The default {@link PageHints}. Reads `currentPage`/`page` and `totalPages` from the\n * document `meta`, matching the behavior used before `pageHints` was configurable.\n * Used whenever the consumer does not provide a `pageHints` function.\n *\n * @since 5.9.0\n * @public\n */\nexport const defaultPageHints: PageHints = (document) => {\n const currentPage = (document.meta?.page ?? document.meta?.currentPage ?? 0) as number;\n const totalPages = (document.meta?.totalPages ?? 0) as number;\n return { currentPage, totalPages };\n};\n\n/**\n * The global, shared cache for a paginated collection. Keyed by the collection's\n * `first` (or `self`) link, so that multiple components paging the same collection\n * share loaded pages, the page graph, and `totalPages`.\n *\n * This holds only shared, request-agnostic data. Per-component state (the active\n * page, navigation) lives on {@link PaginationState}, which is the API consumers\n * interact with — the cache itself is plumbing shared between the pagination\n * classes.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationCache<RT = unknown, E = unknown> {\n /**\n * The cache key this collection is stored under in the module-level cache —\n * its `first` (or `self`) link. This is the collection's identity: two\n * requests whose documents resolve to the same key are pages of the same\n * collection.\n *\n * @internal\n */\n declare readonly key: string;\n\n /** @internal */\n @signal declare firstPage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The total number of pages in the collection, or `0` when unknown. Consumers\n * should read this via {@link PaginationState.totalPages}.\n */\n @signal declare totalPages: number;\n /**\n * Whether this collection has server-known page numbers. Stays `false` for\n * cursor-based collections (opaque `prev`/`next`, no index/total), which drives\n * whether numbered links are produced. Set once a {@link PageHints} yields a real\n * `currentPage`/`totalPages`.\n *\n * @internal\n */\n @signal declare isNumbered: boolean;\n /** @internal */\n declare private pagesCache: Map<string, PageCache>;\n /** @internal */\n private pageHints: PageHints = defaultPageHints;\n\n constructor(key: string) {\n this.key = key;\n this.pagesCache = new Map<string, PageCache>();\n this.firstPage = null;\n this.totalPages = 0;\n this.isNumbered = false;\n }\n\n /**\n * Installs the consumer-provided {@link PageHints} onto the shared cache. The first\n * explicit hint wins; passing `undefined` (no hint) is a no-op that preserves the\n * default. In dev, asserts that components sharing a collection do not provide\n * diverging hint functions.\n *\n * @internal\n */\n installPageHints(pageHints: PageHints | undefined): void {\n if (!pageHints) {\n return;\n }\n if (this.pageHints === defaultPageHints) {\n this.pageHints = pageHints;\n return;\n }\n assert(\n 'Received diverging `pageHints` functions for the same paginated collection. Provide the same function reference to every <Paginate /> sharing a collection (define it once at module scope).',\n this.pageHints === pageHints\n );\n }\n\n /**\n * Runs the active {@link PageHints} against a document.\n *\n * Both values are *hints*, not requirements. A value of `0` means \"unknown\" —\n * the response did not expose it and no `pageHints` function derived it. When a\n * value is present (`> 0`) it is relied upon (numbered links, total, sparse\n * placement of jumped-to pages); when absent the page graph falls back to pure\n * `prev`/`next` adjacency (as in cursor/infinite streams).\n *\n * @internal\n */\n readPageHints(document: ReactiveDocument<unknown>): { currentPage: number; totalPages: number } {\n const { currentPage, totalPages } = this.pageHints(document);\n if (currentPage > 0 || totalPages > 0) {\n this.isNumbered = true;\n }\n return { currentPage, totalPages };\n }\n\n /** @internal */\n getPageCache(url: string): Readonly<PageCache<RT, E>> {\n let page = this.pagesCache.get(url);\n if (!page) {\n page = new PageCache<RT, E>(this, url);\n this.pagesCache.set(url, page);\n }\n\n return page as Readonly<PageCache<RT, E>>;\n }\n\n /** @internal */\n loadPage(url: string, request: Future<RT> | null): Readonly<PageCache<RT, E>> {\n const page = this.getPageCache(url);\n if ((!page.isLoaded || page.isError) && request) {\n assert('Expected a request to a load a page', request);\n void page.load(request).then((document) => {\n this.updateFirstPage(page);\n if (document) {\n this.totalPages = this.getTotalPages(document);\n }\n });\n }\n return page;\n }\n\n /** @internal */\n private updateFirstPage(page: Readonly<PageCache<RT, E>>): void {\n let maybeFirstPage = page;\n while (maybeFirstPage.before) {\n maybeFirstPage = maybeFirstPage.before;\n }\n if (!this.firstPage || this.firstPage.pageNumber > maybeFirstPage.pageNumber) {\n this.firstPage = maybeFirstPage;\n }\n }\n\n /** @internal */\n getTotalPages(document: ReactiveDocument<unknown>): number {\n return this.readPageHints(document).totalPages;\n }\n\n /**\n * Every page known to the shared graph, in order — loaded pages and pages\n * known only from links — across all components sharing the collection.\n *\n * This is the whole-collection view. For the run a single component is\n * viewing, use {@link PaginationState.pages}.\n *\n * ```ts\n * const cache = getPaginationCache(firstLink);\n * for (const page of cache.pages) {\n * // page.isLoaded, page.pageNumber, page.data, ...\n * }\n * ```\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n let page: Readonly<PageCache<RT, E>> | null = self.firstPage;\n while (page) {\n yield page;\n page = page.after;\n }\n },\n };\n }\n\n /**\n * The items of every loaded page in the shared graph, flattened into one\n * contiguous iterable in page order. Pages that are known but not loaded\n * contribute nothing.\n *\n * This is the whole-collection view. For the run a single component is\n * viewing, use {@link PaginationState.data}.\n */\n @memoized\n get data(): Iterable<ContentItem<RT>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n for (const page of self.pages) {\n if (page.data) {\n yield* page.data as ContentItem<RT>[];\n }\n }\n },\n };\n }\n}\n\n/**\n * Get the shared {@link PaginationCache} for a given cache key (the collection's\n * `first` or `self` link). Returns the same instance for the same key for the\n * lifetime of the module.\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationCache<RT, E>(key: string): PaginationCache<RT, E> {\n let cache = PaginationCacheMap.get(key);\n\n if (!cache) {\n cache = new PaginationCache<RT, E>(key);\n PaginationCacheMap.set(key, cache);\n }\n\n return cache as PaginationCache<RT, E>;\n}\n\n/**\n * Clears the module-level pagination cache used by {@link getPaginationCache}.\n * Primarily intended for test isolation, since the cache is keyed by url and\n * otherwise persists for the lifetime of the module.\n *\n * @since 5.9.0\n * @public\n */\nexport function clearPaginationCache(): void {\n PaginationCacheMap.clear();\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { RequestManager, Store } from '../index.ts';\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { ContentItem, PageCache } from './page-cache.ts';\nimport { getHref } from './page-cache.ts';\nimport { getPaginationCache, type PageHints, type PaginationCache } from './pagination-cache.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\n\n/**\n * The two navigation surfaces a `<Paginate />` component can drive. Selecting\n * one (via the component's `@mode` arg) narrows the yielded state so the two\n * APIs cannot be mixed:\n *\n * - `'paged'` — single-page view, see {@link PagedPaginationState}.\n * - `'infinite'` — accumulated view, see {@link InfinitePaginationState}.\n */\nexport type PaginateMode = 'paged' | 'infinite';\n\n/**\n * The part of a {@link PaginationState} available to both navigation surfaces.\n */\nexport interface SharedPaginationState<RT = unknown, E = unknown> {\n /** See {@link PaginationState.totalPages}. */\n readonly totalPages: number;\n /** See {@link PaginationState.adoptPage}. */\n adoptPage(request: Future<RT>): Promise<RT | null>;\n /**\n * The shared page graph and data this component reads from.\n *\n * @internal\n */\n readonly paginationCache: PaginationCache<RT, E> | null;\n}\n\n/**\n * The paged (single-page view) surface of a {@link PaginationState}: render\n * {@link PaginationState.activePageRequest | activePageRequest}, navigate with\n * {@link PaginationState.loadPage | loadPage}. This is what the `<Paginate />`\n * component yields in `'paged'` mode (the default).\n */\nexport interface PagedPaginationState<RT = unknown, E = unknown> extends SharedPaginationState<RT, E> {\n /** See {@link PaginationState.activePage}. */\n readonly activePage: Readonly<PageCache<RT, E>> | null;\n /** See {@link PaginationState.activePageRequest}. */\n readonly activePageRequest: Future<RT> | null;\n /** See {@link PaginationState.loadPage}. */\n loadPage: (url: string) => Promise<RT | null>;\n}\n\n/**\n * The infinite (accumulated view) surface of a {@link PaginationState}: render\n * {@link PaginationState.data | data}, grow it with\n * {@link PaginationState.loadNext | loadNext}/{@link PaginationState.loadPrev | loadPrev}.\n * This is what the `<Paginate />` component yields in `'infinite'` mode.\n */\nexport interface InfinitePaginationState<RT = unknown, E = unknown> extends SharedPaginationState<RT, E> {\n /** See {@link PaginationState.data}. */\n readonly data: Iterable<ContentItem<RT>>;\n /** See {@link PaginationState.pages}. */\n readonly pages: Iterable<Readonly<PageCache<RT, E>>>;\n /** See {@link PaginationState.hasNext}. */\n readonly hasNext: boolean;\n /** See {@link PaginationState.hasPrevious}. */\n readonly hasPrevious: boolean;\n /** See {@link PaginationState.nextRequest}. */\n readonly nextRequest: Future<RT> | null;\n /** See {@link PaginationState.previousRequest}. */\n readonly previousRequest: Future<RT> | null;\n /** See {@link PaginationState.loadNext}. */\n loadNext: () => Promise<RT | null>;\n /** See {@link PaginationState.loadPrev}. */\n loadPrev: () => Promise<RT | null>;\n}\n\n/**\n * Resolves a {@link PaginateMode} to the surface it exposes, so a component\n * generic over the mode can yield only that surface.\n */\nexport type PaginationStateFor<RT = unknown, E = unknown, M extends PaginateMode = 'paged'> = M extends 'infinite'\n ? InfinitePaginationState<RT, E>\n : PagedPaginationState<RT, E>;\n\n/**\n * The per-component, local pagination state. It houses the state that is unique\n * to a single component instance — the active page and navigation — while\n * referencing a shared {@link PaginationCache} for the page graph and data.\n *\n * This is the object yielded by the `<Paginate />` component, narrowed by the\n * component's `@mode` arg to one of its two navigation surfaces so the two\n * APIs cannot be mixed:\n *\n * - **Paged** (`@mode=\"paged\"`, the default): {@link PagedPaginationState} —\n * render {@link activePageRequest}, navigate with {@link loadPage} (what the\n * numbered/relational links call). Reads {@link activePage}.\n * - **Infinite** (`@mode=\"infinite\"`): {@link InfinitePaginationState} — render\n * {@link data}, wrap {@link nextRequest}/{@link previousRequest} in `<Request>`\n * for loading state, and grow the view with {@link loadNext}/{@link loadPrev}.\n *\n * Both surfaces read the same shared page graph; the mode only selects which\n * API is exposed.\n *\n * Instances are created via {@link getPaginationState} (or by the `<Paginate />`\n * component on your behalf), never constructed directly.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationState<RT = unknown, E = unknown>\n implements PagedPaginationState<RT, E>, InfinitePaginationState<RT, E>\n{\n /** @internal */\n declare private store: Store | RequestManager;\n /** @internal */\n declare private request: Future<RT>;\n /** @internal */\n declare private pageHints: PageHints | undefined;\n\n /**\n * The shared page graph and data this component reads from.\n *\n * @internal\n */\n declare paginationCache: PaginationCache<RT, E> | null;\n\n /**\n * The page the paged surface is currently showing. Starts at the page this\n * component first loaded and moves whenever {@link loadPage} runs (for\n * example a numbered link is clicked).\n */\n declare activePage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The page this component first loaded, used to seed the active page and frontier.\n *\n * @internal\n */\n declare private initialPage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The first and last loaded pages of the contiguous run this component is\n * viewing. Drives the infinite surface — {@link data} walks from\n * `frontierStart` to `frontierEnd`, and {@link loadPrev}/{@link loadNext} extend\n * them backward/forward. Both seed to {@link initialPage}; a purely paged\n * consumer never extends them, so they stay put and are effectively unused.\n *\n * @internal\n */\n declare private frontierStart: Readonly<PageCache<RT, E>> | null;\n /** @internal */\n declare private frontierEnd: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The request of the latest {@link adoptPage} call — only that call may\n * commit. Later calls (or a {@link loadPage} navigation) claim the slot,\n * superseding in-flight adoptions so the newest navigation always wins.\n * Untracked bookkeeping.\n *\n * @internal\n */\n declare private _adoptTarget: Future<RT> | null;\n\n constructor(request: Future<RT>, pageHints?: PageHints) {\n this.store = request.requester;\n this.request = request;\n this.pageHints = pageHints;\n this._adoptTarget = null;\n\n void this.setup();\n }\n\n /**\n * The request for the {@link activePage}, for the paged surface to render. This\n * is what a single-page view wraps in a `<Request>` to show the active page's\n * loading, error, and content states:\n *\n * ```gts\n * <Paginate @request={{this.request}}>\n * <:content as |pages|>\n * <Request @request={{pages.activePageRequest}}>\n * <:content as |result|>\n * {{#each result.data as |item|}}...{{/each}}\n * </:content>\n * </Request>\n * </:content>\n * </Paginate>\n * ```\n */\n @memoized\n get activePageRequest(): Future<RT> | null {\n return this.activePage?.request ?? null;\n }\n\n /**\n * The total number of pages in the collection, or `0` when it is unknown (for\n * example a cursor-based collection that reports no total).\n *\n * ```gts\n * <p>Page {{pages.activePage.pageNumber}} of {{pages.totalPages}}</p>\n * ```\n */\n @memoized\n get totalPages(): number {\n return this.paginationCache?.totalPages ?? 0;\n }\n\n /**\n * The pages of the run this component is viewing, from the backward frontier\n * to the forward frontier inclusive, in order. Part of the infinite surface:\n * it is the same run as {@link data}, yielding the {@link PageCache} objects\n * instead of their flattened items — use it when the UI needs per-page\n * boundaries or request states.\n *\n * Grows as {@link loadNext}/{@link loadPrev} extend the frontier. Scoped to\n * this component's frontier (not the shared cache), so components paging the\n * same collection to different extents each see only what they have scrolled\n * through. For every page known to the whole collection, see\n * {@link PaginationCache.pages}.\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n const end = self.frontierEnd;\n let page: Readonly<PageCache<RT, E>> | null = self.frontierStart;\n while (page) {\n yield page;\n if (page === end) {\n break;\n }\n page = page.after;\n }\n },\n };\n }\n\n /**\n * The accumulated items across the loaded run, from the backward frontier to\n * the forward frontier inclusive — the single set an infinite collection renders.\n * Grows as {@link loadNext}/{@link loadPrev} extend the frontier. Scoped to this\n * component's frontier (not the shared cache), so components paging the same\n * collection to different extents each see only what they have scrolled through.\n *\n * The flattened items of {@link pages}, as one contiguous iterable. For the\n * items of every loaded page in the whole collection, see\n * {@link PaginationCache.data}.\n *\n * ```gts\n * <Paginate @request={{this.request}} @mode=\"infinite\">\n * <:content as |pages features|>\n * {{#each pages.data as |item|}}...{{/each}}\n * {{#if pages.hasNext}}\n * <button {{on \"click\" features.loadNext}}>Load more</button>\n * {{/if}}\n * </:content>\n * </Paginate>\n * ```\n */\n @memoized\n get data(): Iterable<ContentItem<RT>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n for (const page of self.pages) {\n if (page.data) {\n yield* page.data as ContentItem<RT>[];\n }\n }\n },\n };\n }\n\n /**\n * Whether a page exists after the forward frontier — i.e. there is more to load\n * going forward. Use to hide the trailing load-more sentinel at end-of-list:\n *\n * ```gts\n * {{#if pages.hasNext}}\n * <button {{on \"click\" features.loadNext}}>Load more</button>\n * {{/if}}\n * ```\n */\n @memoized\n get hasNext(): boolean {\n return Boolean(this.frontierEnd?.nextLink);\n }\n\n /**\n * Whether a page exists before the backward frontier.\n */\n @memoized\n get hasPrevious(): boolean {\n return Boolean(this.frontierStart?.prevLink);\n }\n\n /**\n * The request for the page just after the forward frontier, for the infinite\n * surface. `null` until {@link loadNext} fires it (so a `<Request>` wrapping it\n * renders its idle block), the in-flight `Future` while that page loads, then\n * `null` again once the frontier advances onto it. Also `null` at end-of-list.\n *\n * ```gts\n * {{#if pages.hasNext}}\n * <Request @request={{pages.nextRequest}}>\n * <:idle><button {{on \"click\" features.loadNext}}>Load more</button></:idle>\n * <:loading><Spinner /></:loading>\n * </Request>\n * {{/if}}\n * ```\n */\n @memoized\n get nextRequest(): Future<RT> | null {\n const url = this.frontierEnd?.nextLink;\n if (!url) {\n return null;\n }\n return this.paginationCache?.getPageCache(url).request ?? null;\n }\n\n /**\n * The request for the page just before the backward frontier. Mirror of\n * {@link nextRequest} for {@link loadPrev}.\n */\n @memoized\n get previousRequest(): Future<RT> | null {\n const url = this.frontierStart?.prevLink;\n if (!url) {\n return null;\n }\n return this.paginationCache?.getPageCache(url).request ?? null;\n }\n\n /** @internal */\n private async setup(): Promise<void> {\n let document;\n try {\n document = await this.request;\n } catch {\n // a failed (or aborted) initial request leaves the pagination state\n // empty. Rendering the failure is the request subscription's job, and\n // recovery (retry) produces a new request and with it a new state.\n return;\n }\n const content = document.content as ReactiveDocument<unknown>;\n const selfLink = getHref(content.links?.self);\n const firstLink = getHref(content.links?.first);\n assert('Expected the initial document to have a self link', selfLink);\n\n const cacheKey = firstLink ?? selfLink ?? '';\n const cache = getPaginationCache<RT, E>(cacheKey);\n cache.installPageHints(this.pageHints);\n this.paginationCache = cache;\n cache.totalPages = cache.getTotalPages(content);\n this.activePage = this.initialPage = cache.loadPage(selfLink, this.request);\n this.frontierStart = this.frontierEnd = this.initialPage;\n }\n\n /**\n * Commits a resolved, membership-proven page into this state, making it the\n * {@link activePage}. The synchronous commit step under {@link adoptPage},\n * which is where the resolution and membership verification live.\n *\n * It only activates the page and keeps the infinite surface's frontier\n * coherent — a page already inside the run leaves the frontier untouched,\n * an adjacent page extends it, and a disjoint page resets the run to the\n * adopted page (jump semantics).\n *\n * @internal\n */\n private _activate(page: Readonly<PageCache<RT, E>>, url: string): void {\n this.activePage = page;\n\n for (const existing of this.pages) {\n if (existing === page) {\n return;\n }\n }\n\n if (this.frontierEnd?.nextLink === url) {\n this.frontierEnd = page;\n } else if (this.frontierStart?.prevLink === url) {\n this.frontierStart = page;\n } else {\n this.frontierStart = this.frontierEnd = page;\n }\n }\n\n /**\n * Adopts an externally-issued request into this pagination, making its page\n * the {@link activePage} — the programmatic entry point for route-driven\n * navigation when managing a `PaginationState` directly (the `<Paginate />`\n * component uses the same mechanism for a changed `@request` arg).\n *\n * Awaits the request and verifies that its document is a page of this\n * state's collection (same `first` — or `self` — link). On a match, the\n * page is loaded (a page already in the shared cache is reused) and — once\n * its request settles — committed: it becomes the active page, and the\n * infinite surface's run is kept coherent (a page already inside the run\n * leaves it untouched, an adjacent page extends it, a disjoint page resets\n * the run to the adopted page). The commit happens only after the page has\n * loaded, so the previous page stays active — and rendered — while the\n * adoption resolves. Returns the page's document.\n *\n * Concurrent calls race safely: the latest call wins. An earlier in-flight\n * adoption is superseded and commits nothing, and a {@link loadPage}\n * navigation also supersedes a pending adoption (the user's click is the\n * newer intent).\n *\n * Returns `null` — leaving the state untouched — whenever the adoption does\n * not commit:\n *\n * - the request (or its page's load) rejected\n * - the document is a page of a *different* collection\n * - this state has not finished setting up its own collection yet\n * - the call was superseded by a newer navigation\n *\n * ```ts\n * const pages = getPaginationState(initialRequest);\n * // later, e.g. in a route model hook reacting to a ?page= param:\n * const adopted = await pages.adoptPage(store.request(query));\n * if (adopted === null) {\n * // not part of this collection — start a fresh pagination\n * }\n * ```\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler.\n */\n adoptPage = async (request: Future<RT>): Promise<RT | null> => {\n this._adoptTarget = request;\n\n let content;\n try {\n content = (await request).content as ReactiveDocument<unknown>;\n } catch {\n return null;\n }\n if (this._adoptTarget !== request) {\n // a newer navigation claimed the slot while the request resolved\n return null;\n }\n\n const cache = this.paginationCache;\n if (!cache) {\n return null;\n }\n\n const selfLink = getHref(content.links?.self);\n const firstLink = getHref(content.links?.first);\n assert('Expected the adopted document to have a self link', selfLink);\n if (!selfLink || (firstLink ?? selfLink) !== cache.key) {\n return null;\n }\n\n const page = cache.loadPage(selfLink, request);\n try {\n // wait for the page's request state to settle its value; adopting an\n // already-settled future still needs this microtask\n await page.request;\n } catch {\n return null;\n }\n if (this._adoptTarget !== request) {\n // a newer navigation claimed the slot while the page loaded\n return null;\n }\n\n this._activate(page, selfLink);\n return page.value;\n };\n\n /**\n * Extends the backward frontier by one page, prepending it to {@link data}.\n * The frontier advances only once the page has loaded, so\n * {@link previousRequest} tracks the in-flight page meanwhile. Returns the\n * loaded value, or `null` when there is no previous page or the load fails.\n *\n * On failure the frontier stays put and {@link previousRequest} keeps\n * resolving to the failed page, so a wrapping `<Request>` renders its error\n * block. Calling again retries: the failed page is re-requested with a\n * forced reload.\n *\n * In templates it is also available as the `loadPrev` content feature\n * ({@link InfinitePaginationContentFeatures.loadPrev}) yielded by\n * `<Paginate />`; the two are the same function.\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler.\n */\n loadPrev = async (): Promise<RT | null> => {\n return this._extend('prev');\n };\n\n /**\n * Extends the forward frontier by one page, appending it to {@link data}.\n * Mirror of {@link loadPrev}.\n *\n * In templates it is also available as the `loadNext` content feature\n * ({@link InfinitePaginationContentFeatures.loadNext}) yielded by\n * `<Paginate />`; the two are the same function.\n *\n * ```gts\n * <button {{on \"click\" pages.loadNext}}>Load more</button>\n * ```\n */\n loadNext = async (): Promise<RT | null> => {\n return this._extend('next');\n };\n\n /** @internal */\n private _extend = async (dir: 'prev' | 'next'): Promise<RT | null> => {\n const cache = this.paginationCache;\n assert('Expected the pagination cache to be set up before loading a page', cache);\n\n const frontier = dir === 'next' ? this.frontierEnd : this.frontierStart;\n const url = dir === 'next' ? frontier?.nextLink : frontier?.prevLink;\n if (!url) {\n return null;\n }\n\n const page = cache.getPageCache(url);\n if (!page.isRequested || page.isError) {\n // re-requesting a page that previously failed is the retry path: force\n // a reload so a cached error response is not replayed.\n const request = this.store.request(\n page.isError ? { method: 'GET', url, cacheOptions: { reload: true } } : { method: 'GET', url }\n );\n cache.loadPage(url, request as Future<RT>);\n }\n\n try {\n await page.request;\n } catch {\n // the failure is surfaced reactively: the frontier stays put, so\n // `nextRequest`/`previousRequest` resolves to the failed page and a\n // wrapping `<Request>` renders its error block. Calling again retries.\n return null;\n }\n\n // Advance the frontier only after the load resolves. While loading, the\n // frontier still points at the previous page, so `nextRequest`/`prevRequest`\n // resolves to this in-flight page and a wrapping `<Request>` shows loading.\n if (dir === 'next') {\n this.frontierEnd = page;\n } else {\n this.frontierStart = page;\n }\n\n return page.value;\n };\n\n /**\n * Loads a specific page by its URL and makes it the {@link activePage},\n * requesting it first if it is not already loaded. This is the paged surface's\n * navigation entry point, called by the numbered and relational links.\n *\n * In templates it is also available as the `loadPage` content feature\n * ({@link PagedPaginationContentFeatures.loadPage}) yielded by `<Paginate />`;\n * the two are the same function.\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler. Returns the page's value, or `null` if it has none or\n * the load fails.\n *\n * On failure the page stays active and {@link activePageRequest} resolves to\n * it, so a wrapping `<Request>` renders its error block. Calling again (for\n * example clicking the page's link a second time) retries: the failed page\n * is re-requested with a forced reload.\n *\n * ```gts\n * <EachLink @pages={{pages}}>\n * <:link as |link|>\n * <button {{on \"click\" (fn features.loadPage link.url)}}>{{link.text}}</button>\n * </:link>\n * </EachLink>\n * ```\n */\n loadPage = async (url: string): Promise<RT | null> => {\n const cache = this.paginationCache;\n assert('Expected the pagination cache to be set up before loading a page', cache);\n\n // an explicit navigation supersedes any in-flight adoption\n this._adoptTarget = null;\n\n const page = cache.getPageCache(url);\n this.activePage = page;\n\n if (!page.isLoaded || page.isError) {\n // re-requesting a page that previously failed is the retry path: force\n // a reload so a cached error response is not replayed.\n const request = this.store.request(\n page.isError ? { method: 'GET', url, cacheOptions: { reload: true } } : { method: 'GET', url }\n );\n cache.loadPage(url, request as Future<RT>);\n try {\n await page.request;\n } catch {\n // the failure is surfaced reactively: the page stays active, so\n // `activePageRequest` resolves to it and a wrapping `<Request>`\n // renders its error block. Calling again retries.\n return null;\n }\n }\n\n return page.value;\n };\n}\n\ndefineSignal(PaginationState.prototype, 'paginationCache', null);\ndefineSignal(PaginationState.prototype, 'activePage', null);\ndefineSignal(PaginationState.prototype, 'initialPage', null);\ndefineSignal(PaginationState.prototype, 'frontierStart', null);\ndefineSignal(PaginationState.prototype, 'frontierEnd', null);\n\nconst PaginationStateCache = new WeakMap<Future<unknown>, PaginationState>();\n\n/**\n * Get the {@link PaginationState} for a given request. Returns the same instance\n * for the same request future, so that repeated calls (e.g. in a template, or\n * alongside the `<Paginate />` component using the same request) share the same\n * local pagination state. Keyed by request identity, just like\n * {@link getRequestState}.\n *\n * ```ts\n * const future = store.request(query);\n * const pages = getPaginationState(future);\n *\n * await future;\n * pages.totalPages; // now known, if the response exposed it\n * await pages.loadNext();\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationState<RT, E>(request: Future<RT>, pageHints?: PageHints): PaginationState<RT, E> {\n let state = PaginationStateCache.get(request);\n\n if (!state) {\n // the cache is heterogeneous over RT/E (mirrored by the cast on return)\n state = new PaginationState<RT, E>(request, pageHints) as unknown as PaginationState;\n PaginationStateCache.set(request, state);\n }\n\n return state as PaginationState<RT, E>;\n}\n","import type { PageCache } from './page-cache.ts';\nimport type { PagedPaginationState } from './pagination-state.ts';\nimport { memoized } from './reactivity/signal';\n\nconst PaginationLinksCache = new WeakMap<PagedPaginationState, PaginationLinks>();\n\n/**\n * A single numbered link, e.g. page `3`. Loads its page and makes it active when\n * {@link setActive} runs. Carries its {@link index} and its\n * {@link distanceFromActiveIndex} so a UI can style links by how far they sit\n * from the current page.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#each state.links as |link|}}\n * {{#if link.isReal}}\n * <button class={{if link.isCurrent \"active\"}} {{on \"click\" link.setActive}}>\n * {{link.text}}\n * </button>\n * {{/if}}\n * {{/each}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class RealPaginationLink {\n readonly isReal = true as const;\n\n readonly url: string;\n readonly index: number;\n readonly isCurrent: boolean;\n readonly distanceFromActiveIndex: number;\n /** @internal */\n declare private _loadPage: (url: string) => Promise<unknown>;\n\n constructor(url: string, index: number, activeIndex: number, loadPage: (url: string) => Promise<unknown>) {\n this.url = url;\n this.index = index;\n this.isCurrent = index === activeIndex;\n this.distanceFromActiveIndex = Math.abs(index - activeIndex);\n this._loadPage = loadPage;\n }\n\n get text(): string {\n return `${this.index}`;\n }\n\n /**\n * Loads this link's page and makes it the active page on the associated\n * {@link PaginationState}. It is a stable reference, so it is safe to pass\n * around as an \"action\" or \"event\" handler:\n *\n * ```gts\n * <button {{on \"click\" link.setActive}}>{{link.text}}</button>\n * ```\n */\n setActive = (): Promise<unknown> => {\n return this._loadPage(this.url);\n };\n}\n\n/**\n * A stand-in for a run of pages that have not been loaded yet, rendered as an\n * ellipsis between numbered links. It covers an {@link indexRange} rather than a\n * single page and has no page to navigate to.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#each state.links as |link|}}\n * {{#unless link.isReal}}\n * <span title=\"{{link.rangeSize}} more pages\">{{link.text}}</span>\n * {{/unless}}\n * {{/each}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PlaceholderPaginationLink {\n readonly isReal = false as const;\n\n /**\n * The inclusive `[start, end]` page-number range of not-yet-loaded pages this\n * placeholder stands in for.\n */\n indexRange: [start: number, end: number];\n /** @internal */\n private readonly activeIndex: number;\n\n text = '.';\n\n constructor(index: [start: number, end: number], activeIndex: number) {\n this.indexRange = index;\n this.activeIndex = activeIndex;\n }\n\n /** The number of pages this placeholder covers. */\n get rangeSize(): number {\n return this.indexRange[1] - this.indexRange[0] + 1;\n }\n\n /**\n * The distance between the active page and the nearest edge of this\n * placeholder's index range.\n */\n get distanceFromActiveIndex(): number {\n const [start, end] = this.indexRange;\n return Math.min(Math.abs(start - this.activeIndex), Math.abs(end - this.activeIndex));\n }\n\n /** @internal */\n private _mergeRange(newRange: [start: number, end: number]): void {\n const [oldStart, oldEnd] = this.indexRange;\n const [newStart, newEnd] = newRange;\n const mergedRange: [start: number, end: number] = [Math.min(oldStart, newStart), Math.max(oldEnd, newEnd)];\n this.indexRange = mergedRange;\n }\n}\n\n/**\n * A relational (`first`/`prev`/`next`/`last`) navigation link, relative to the\n * active page. Unlike {@link RealPaginationLink} these carry no ordinal index —\n * they are the only links available for cursor-based pagination, where pages are\n * chained purely by opaque relational links with no page number or total. They\n * are also available in numbered pagination as a convenience.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#if state.prev}}<button {{on \"click\" state.prev.setActive}}>Previous</button>{{/if}}\n * {{#if state.next}}<button {{on \"click\" state.next.setActive}}>Next</button>{{/if}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class RelationalPaginationLink {\n readonly isReal = true as const;\n\n readonly rel: 'first' | 'prev' | 'next' | 'last';\n readonly url: string;\n /**\n * Whether this link points at the page that is already active — for example\n * the `first` link while the first page is being viewed. Useful for\n * disabling the control.\n */\n readonly isCurrent: boolean;\n /** @internal */\n declare private _loadPage: (url: string) => Promise<unknown>;\n\n constructor(\n rel: 'first' | 'prev' | 'next' | 'last',\n url: string,\n isCurrent: boolean,\n loadPage: (url: string) => Promise<unknown>\n ) {\n this.rel = rel;\n this.url = url;\n this.isCurrent = isCurrent;\n this._loadPage = loadPage;\n }\n\n get text(): string {\n return this.rel;\n }\n\n /**\n * Loads this link's page and makes it the active page on the associated\n * {@link PaginationState}. It is a stable reference, so it is safe to pass\n * around as an \"action\" or \"event\" handler:\n *\n * ```gts\n * <button {{on \"click\" link.setActive}}>{{link.text}}</button>\n * ```\n */\n setActive = (): Promise<unknown> => {\n return this._loadPage(this.url);\n };\n}\n\n/**\n * A member of {@link PaginationLinks.links}: either a numbered\n * {@link RealPaginationLink} or a {@link PlaceholderPaginationLink} standing in\n * for a gap. Discriminate with {@link RealPaginationLink.isReal | isReal}:\n *\n * ```ts\n * for (const link of links.links) {\n * if (link.isReal) {\n * // numbered link: link.index, link.setActive\n * } else {\n * // gap: link.indexRange\n * }\n * }\n * ```\n */\nexport type PaginationLink = RealPaginationLink | PlaceholderPaginationLink;\n\n/**\n * The reactive set of navigation links derived from a {@link PaginationState}.\n * Where `PaginationState` tracks which pages are loaded and which one is active,\n * `PaginationLinks` turns that page graph into the links a UI renders to move\n * between pages.\n *\n * It provides two kinds of link:\n *\n * - {@link links}: the numbered links, with {@link PlaceholderPaginationLink}\n * placeholders standing in for gaps of not-yet-loaded pages. Only numbered\n * collections (where the server exposes page numbers) produce these.\n * - {@link prev} and {@link next}: the relational links for the active page.\n * Available in both numbered and cursor-based pagination, and the only links a\n * cursor-based collection has.\n * - {@link first} and {@link last}: the relational links to the collection's\n * edges, when the response exposes them. Usually present on every page —\n * including the edge page itself, where the link's\n * {@link RelationalPaginationLink.isCurrent | isCurrent} is `true`.\n *\n * Every link updates as pages load and as the active page changes, since they\n * read straight from the state's shared page graph. To get the links for a\n * state, use {@link getPaginationLinks}.\n *\n * See also:\n * - {@link RealPaginationLink}\n * - {@link PlaceholderPaginationLink}\n * - {@link RelationalPaginationLink}\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationLinks<RT = unknown, E = unknown> {\n /** @internal */\n declare private paginationState: PagedPaginationState<RT, E>;\n\n constructor(paginationState: PagedPaginationState<RT, E>) {\n this.paginationState = paginationState;\n }\n\n /**\n * The relational `first` link of the collection, or `null` when the active\n * page's response did not expose one. Unlike {@link prev}/{@link next} it is\n * usually present on every page — including the first page itself, where the\n * link's {@link RelationalPaginationLink.isCurrent | isCurrent} is `true`\n * (useful for disabling the control).\n */\n @memoized\n get first(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.firstLink;\n return url\n ? new RelationalPaginationLink('first', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `prev` link for the active page, or `null` at the start of the\n * collection. Available in both numbered and cursor pagination.\n */\n @memoized\n get prev(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.prevLink;\n return url\n ? new RelationalPaginationLink('prev', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `next` link for the active page, or `null` at the end of the\n * collection. Available in both numbered and cursor pagination.\n */\n @memoized\n get next(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.nextLink;\n return url\n ? new RelationalPaginationLink('next', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `last` link of the collection, or `null` when the active\n * page's response did not expose one. Mirror of {@link first} for the end of\n * the collection.\n */\n @memoized\n get last(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.lastLink;\n return url\n ? new RelationalPaginationLink('last', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The numbered links and placeholders, derived from the shared page graph.\n *\n * Only produced for numbered pagination (where the server exposes page numbers).\n * Cursor-based collections have no page numbers, so this is empty — use\n * {@link prev}/{@link next} for cursor navigation.\n */\n @memoized\n get links(): PaginationLink[] {\n const links: PaginationLink[] = [];\n\n const cache = this.paginationState.paginationCache;\n if (!cache || !cache.isNumbered) {\n return links;\n }\n\n const { firstPage, totalPages } = cache;\n const activeIndex = this.paginationState.activePage?.pageNumber ?? 0;\n\n if (firstPage) {\n let previousPage: Readonly<PageCache<RT, E>> | null = null;\n let currentPage: Readonly<PageCache<RT, E>> | null = firstPage;\n while (currentPage) {\n if (previousPage && currentPage.pageNumber - previousPage.pageNumber > 1) {\n links.push(\n new PlaceholderPaginationLink([previousPage.pageNumber + 1, currentPage.pageNumber - 1], activeIndex)\n );\n }\n links.push(\n new RealPaginationLink(\n currentPage.selfLink ?? '',\n currentPage.pageNumber,\n activeIndex,\n this.paginationState.loadPage\n )\n );\n previousPage = currentPage;\n currentPage = currentPage.after;\n }\n\n if (previousPage && previousPage.pageNumber < totalPages) {\n links.push(new PlaceholderPaginationLink([previousPage.pageNumber + 1, totalPages], activeIndex));\n }\n }\n\n return links;\n }\n}\n\n/**\n * Get the {@link PaginationLinks} for a given {@link PaginationState}. Returns\n * the same instance for the same state, so repeated calls (for example a\n * `<Paginate />` component and a separate links component reading the same state)\n * share one set of links. Keyed by state identity, the same way\n * {@link getPaginationState} is keyed by request and {@link getRequestState} by\n * future.\n *\n * ```ts\n * const links = getPaginationLinks(paginationState);\n *\n * for (const link of links.links) {\n * if (link.isReal) {\n * // render a numbered link, using link.setActive as the click handler\n * } else {\n * // render an ellipsis for the gap link.indexRange covers\n * }\n * }\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationLinks<RT, E>(state: PagedPaginationState<RT, E>): Readonly<PaginationLinks<RT, E>> {\n let links = PaginationLinksCache.get(state);\n\n if (!links) {\n links = new PaginationLinks<RT, E>(state);\n PaginationLinksCache.set(state, links);\n }\n\n return links;\n}\n","import type { RequestManager, Store } from '../index.ts';\nimport type { Future } from '../request.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport type { PageHints } from './pagination-cache.ts';\nimport { getPaginationState, type PaginateMode, type PaginationState } from './pagination-state.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\nimport type { RequestLoadingState } from './request-state.ts';\nimport type { RequestSubscription, SubscriptionArgs } from './request-subscription.ts';\nimport { createRequestSubscription, DISPOSE } from './request-subscription.ts';\n\ninterface ErrorFeatures {\n isHidden: boolean;\n isOnline: boolean;\n retry: () => Promise<void>;\n}\n\n/**\n * The content features available in both pagination modes: the state and\n * controls of the initial request.\n */\nexport interface SharedPaginationContentFeatures<RT> {\n isOnline: boolean;\n isHidden: boolean;\n isRefreshing: boolean;\n /**\n * Whether a changed `@request` arg is currently resolving against the\n * loaded collection — e.g. a route-driven navigation (browser back button).\n * The existing content stays rendered while this is `true`; once the\n * request resolves it either becomes the active page (same collection) or\n * the component resets to the new collection.\n */\n isNavigating: boolean;\n refresh: () => Promise<void>;\n reload: () => Promise<void>;\n abort?: () => void;\n latestRequest?: Future<RT>;\n}\n\n/**\n * The content features yielded in `'paged'` mode: navigation happens by\n * loading a specific page.\n */\nexport interface PagedPaginationContentFeatures<RT> extends SharedPaginationContentFeatures<RT> {\n loadPage: (url: string) => Promise<RT | null>;\n}\n\n/**\n * The content features yielded in `'infinite'` mode: navigation happens by\n * extending the loaded run at either end.\n */\nexport interface InfinitePaginationContentFeatures<RT> extends SharedPaginationContentFeatures<RT> {\n loadNext: () => Promise<RT | null>;\n loadPrev: () => Promise<RT | null>;\n}\n\n/**\n * The full set of content features a {@link PaginationSubscription} builds —\n * both modes' surfaces. The `<Paginate />` component narrows this to one mode\n * via {@link PaginationContentFeaturesFor} before yielding.\n */\nexport type PaginationContentFeatures<RT> = PagedPaginationContentFeatures<RT> & InfinitePaginationContentFeatures<RT>;\n\n/**\n * Resolves a {@link PaginateMode} to the content features it exposes. Mirror of\n * {@link PaginationStateFor}.\n */\nexport type PaginationContentFeaturesFor<RT = unknown, M extends PaginateMode = 'paged'> = M extends 'infinite'\n ? InfinitePaginationContentFeatures<RT>\n : PagedPaginationContentFeatures<RT>;\n\nexport interface PaginationSubscriptionArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * A function to extract the `currentPage` and `totalPages` from a loaded document\n * when they are not available in the default `meta` locations. Must be the same\n * reference across all `<Paginate />` components sharing a collection.\n */\n pageHints?: PageHints;\n}\n\nexport interface PaginateArgs<RT, E> extends PaginationSubscriptionArgs<RT, E> {\n /**\n * Which navigation surface the component yields: `'paged'` (the default) or\n * `'infinite'`. Type-only — it narrows the yielded state and features so the\n * two surfaces cannot be mixed, and is never read at runtime.\n */\n mode?: PaginateMode;\n\n subscription?: PaginationSubscription<RT, E>;\n\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n// oxlint-disable-next-line no-unused-vars\nexport interface PaginationSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\n/**\n * Lifecycle glue for the `<Paginate />` component. Owns the initial\n * {@link RequestSubscription} (loading/error state, autorefresh, disposal) and\n * the per-component {@link PaginationState} that it hands to the component.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationSubscription<RT, E> {\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _subscribedTo: object | null;\n /** @internal */\n declare private _args: PaginationSubscriptionArgs<RT, E>;\n /**\n * The Store this subscription subscribes to or the RequestManager\n * which issues this request.\n */\n declare store: Store | RequestManager;\n\n /**\n * The wrapped {@link RequestSubscription} monitoring the initial request.\n * Created eagerly: constructing one consumes reactive state (its own\n * signals), so building it lazily inside a tracked getter would cause the\n * getter to invalidate — and the subscription to be recreated, losing its\n * reloaded request — whenever `retry`/`reload` runs.\n *\n * @internal\n */\n declare private _requestSubscription: RequestSubscription<RT, E>;\n\n /**\n * The first request this subscription saw — the one that keys the\n * {@link PaginationState} until a navigation resolves to a different\n * collection. Plain (untracked) because it is written during the first\n * computation of {@link paginationState}.\n *\n * @internal\n */\n declare private _seedRequest: Future<RT> | null;\n\n /**\n * The request a resolved navigation swapped the {@link PaginationState} to,\n * when the navigation turned out to target a different collection. A signal:\n * writing it (always outside of render, from {@link _resolveNavigation})\n * invalidates {@link paginationState} so the fresh state takes over.\n *\n * @internal\n */\n declare private _navRequest: Future<RT> | null;\n\n /**\n * The changed request currently being resolved by {@link _resolveNavigation},\n * both to avoid kicking the same navigation twice and as the latest-wins\n * guard when several changes race. Untracked bookkeeping.\n *\n * @internal\n */\n declare private _navTarget: Future<RT> | null;\n\n constructor(store: Store | RequestManager, args: PaginationSubscriptionArgs<RT, E>) {\n this._args = args;\n this.store = store;\n this.isDestroyed = false;\n this._seedRequest = null;\n this._navTarget = null;\n this[DISPOSE] = _DISPOSE;\n this._requestSubscription = createRequestSubscription<RT, E>(store, args);\n }\n\n /**\n * The per-component pagination state yielded to the component.\n *\n * Keyed to the request that started the collection, not the current\n * `@request` arg: when the arg changes, the existing state keeps rendering\n * while {@link _resolveNavigation} resolves the new request in the\n * background. A request that resolves to a page of the same collection is\n * adopted into this state as the new active page (route-driven navigation,\n * e.g. the browser back button); one that resolves to a different\n * collection swaps in a fresh state (a true reset).\n *\n * A background `refresh` does not swap the request, so the pagination\n * state is stable across refreshes.\n */\n @memoized\n get paginationState(): PaginationState<RT, E> {\n const request = this._requestSubscription.request;\n const active = this._navRequest ?? this._seedRequest;\n\n if (!active) {\n // first access: this request starts the collection\n this._seedRequest = request;\n return getPaginationState<RT, E>(request, this._args.pageHints);\n }\n\n if (request !== active && request !== this._navTarget) {\n this._navTarget = request;\n void this._resolveNavigation(request);\n }\n\n return getPaginationState<RT, E>(active, this._args.pageHints);\n }\n\n /**\n * Resolves a changed `@request` arg against the current collection via\n * {@link PaginationState.adoptPage}: a request that resolves to a page of\n * the same collection is adopted into the existing state; one that resolves\n * to a different collection (or arrives before a collection is loaded) swaps\n * the state for a fresh one keyed to this request.\n *\n * A rejected request changes nothing here — the request subscription\n * already surfaces the failure (error/cancelled states), and the existing\n * pagination state is kept for recovery. The request is awaited before\n * `adoptPage` so that rejection and the latest-wins guard are handled\n * before anything is adopted.\n *\n * @internal\n */\n private async _resolveNavigation(request: Future<RT>): Promise<void> {\n try {\n await request;\n } catch {\n return;\n }\n\n // latest wins: a newer navigation or disposal superseded this one\n if (this.isDestroyed || this._navTarget !== request) {\n return;\n }\n\n const adopted = await this.paginationState.adoptPage(request);\n if (this.isDestroyed || this._navTarget !== request) {\n // a newer navigation claimed the slot while `adoptPage` resolved — its\n // own resolution decides the outcome. Without this check a superseded\n // `null` would be mistaken for a foreign collection and wrongly reset.\n return;\n }\n if (adopted === null) {\n // this call is still the latest navigation, so `null` means the page is\n // not part of the current collection (or the collection has not set up\n // yet): reset to a fresh state\n this._navRequest = request;\n }\n // `_navTarget` intentionally stays set: it marks this request as\n // processed so the getter does not re-kick it, and a newer navigation\n // may already have claimed the field while `adoptPage` was awaited.\n }\n\n /**\n * Whether there is no request or query to monitor, so the component has\n * nothing to load.\n */\n @memoized\n get isIdle(): boolean {\n return this._requestSubscription.isIdle;\n }\n\n /**\n * Whether the collection is still blocking-loading: no {@link PaginationState}\n * has finished setting up yet. Only the very first page load (or the reset\n * to a different collection) blocks here — extending the collection with\n * `loadNext`/`loadPrev` does not, and neither does a changed `@request` arg\n * while a collection is already on screen (that is {@link isNavigating}).\n *\n * Remains `true` for the moment between the request resolving and the\n * {@link paginationState} finishing its setup from the response, so that\n * {@link isSuccess} consumers never see a success state with an empty\n * pagination surface.\n */\n @memoized\n get isLoading(): boolean {\n const { reqState } = this._requestSubscription;\n return this.paginationState.paginationCache === null && (reqState.isLoading || reqState.isSuccess);\n }\n\n /**\n * Whether a changed `@request` arg is resolving while a collection is\n * already on screen — route-driven navigation, e.g. the browser back\n * button. The content stays rendered (see {@link isSuccess}); consumers can\n * use this to show a lightweight navigation indicator, the same way a\n * `loadPage` call surfaces through the active page's request state.\n */\n @memoized\n get isNavigating(): boolean {\n return this.paginationState.paginationCache !== null && this._requestSubscription.reqState.isLoading;\n }\n\n /**\n * The {@link RequestLoadingState} for the initial request, for building UIs\n * that respond to download progress.\n */\n @memoized\n get loadingState(): RequestLoadingState {\n return this._requestSubscription.reqState.loadingState;\n }\n\n /**\n * Whether the component has a set-up {@link paginationState} to render and\n * the current request did not fail. Stays `true` while a changed `@request`\n * arg resolves ({@link isNavigating}), so the existing content keeps\n * rendering instead of falling back to a blocking loading state.\n */\n @memoized\n get isSuccess(): boolean {\n const { reqState } = this._requestSubscription;\n return this.paginationState.paginationCache !== null && !reqState.isError && !reqState.isCancelled;\n }\n\n /**\n * Whether the initial request was cancelled (aborted).\n */\n @memoized\n get isCancelled(): boolean {\n return this._requestSubscription.reqState.isCancelled;\n }\n\n /**\n * Whether the initial request rejected with an error.\n */\n @memoized\n get isError(): boolean {\n return this._requestSubscription.reqState.isError;\n }\n\n /**\n * The error the initial request rejected with, or `null` if it did not reject.\n */\n @memoized\n get reason(): StructuredErrorDocument<E> | null {\n return this._requestSubscription.reqState.reason;\n }\n\n /**\n * Error features to yield to the error slot of a component\n */\n @memoized\n get errorFeatures(): ErrorFeatures {\n return {\n isHidden: this._requestSubscription.isHidden,\n isOnline: this._requestSubscription.isOnline,\n retry: this._requestSubscription.retry,\n };\n }\n\n /**\n * Content features to yield to the content slot of a component\n */\n @memoized\n get contentFeatures(): PaginationContentFeatures<RT> {\n const contentFeatures = this._requestSubscription.contentFeatures;\n const { paginationState } = this;\n const feat: PaginationContentFeatures<RT> = {\n ...contentFeatures,\n isNavigating: this.isNavigating,\n loadPrev: paginationState.loadPrev,\n loadNext: paginationState.loadNext,\n loadPage: paginationState.loadPage,\n };\n\n if (feat.isRefreshing) {\n feat.abort = () => {\n contentFeatures.latestRequest?.abort();\n };\n }\n\n return feat;\n }\n\n /**\n * The initial request `Future` this subscription is monitoring, i.e. the first\n * page load. This is the future the {@link paginationState} is built from.\n *\n * @internal\n */\n @memoized\n get request(): Future<RT> {\n return this._requestSubscription.request;\n }\n}\n\ndefineSignal(PaginationSubscription.prototype, '_navRequest', null);\n\n/**\n * Creates the {@link PaginationSubscription} a `<Paginate />` component uses to\n * manage its request lifecycle and pagination state. Pass the result back into\n * the component via `@subscription` to manage the lifecycle externally.\n *\n * ```ts\n * const subscription = createPaginationSubscription(store, { request });\n *\n * subscription.paginationState; // the per-component PaginationState\n * subscription[DISPOSE](); // tear down when the owning component unmounts\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function createPaginationSubscription<RT, E>(\n store: Store | RequestManager,\n args: PaginationSubscriptionArgs<RT, E>\n): PaginationSubscription<RT, E> {\n return new PaginationSubscription(store, args);\n}\n\ninterface PrivatePaginationSubscription {\n isDestroyed: boolean;\n _requestSubscription: RequestSubscription<unknown, unknown>;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivatePaginationSubscription {\n return sub as PrivatePaginationSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: PaginationSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n self._requestSubscription?.[DISPOSE]?.();\n}\n","import { memoized } from './-private.ts';\nimport type { PaginationLinks } from './pagination-links.ts';\nimport { getPaginationLinks } from './pagination-links.ts';\nimport type { PagedPaginationState } from './pagination-state.ts';\nimport { DISPOSE } from './request-subscription.ts';\n\n// oxlint-disable-next-line no-unused-vars\nexport interface PaginationLinksSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\nexport interface PaginationLinksSubscriptionArgs<RT, E> {\n pages: PagedPaginationState<RT, E>;\n}\n\n/**\n * The framework-agnostic core of a pagination links component (for example the\n * `<EachLink />` component of `@warp-drive/ember`): it owns the component\n * lifecycle, while the links themselves live on the {@link PaginationLinks}\n * it exposes.\n *\n * Given the {@link PagedPaginationState} a `<Paginate />` component is driving,\n * {@link paginationLinks} derives that state's `PaginationLinks` — the numbered\n * links (with placeholders for gaps) and the relational\n * `first`/`prev`/`next`/`last` links a component yields for the consumer to\n * render. All of them read from the same shared page graph as the\n * `<Paginate />` component, so they stay in sync as pages load and the active\n * page changes.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationLinksSubscription<RT, E> {\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _args: PaginationLinksSubscriptionArgs<RT, E>;\n\n constructor(args: PaginationLinksSubscriptionArgs<RT, E>) {\n this._args = args;\n this.isDestroyed = false;\n this[DISPOSE] = _DISPOSE;\n }\n\n /**\n * The {@link PaginationLinks} derived from the {@link PagedPaginationState}\n * passed as an arg — the surface a links component yields to its consumer:\n * the numbered {@link PaginationLinks.links | links} (empty for cursor-based\n * collections) and the relational {@link PaginationLinks.first | first}/\n * {@link PaginationLinks.prev | prev}/{@link PaginationLinks.next | next}/\n * {@link PaginationLinks.last | last} links.\n *\n * Recomputes when the `pages` arg changes, so a component whose pagination\n * resets to a different collection derives fresh links automatically.\n */\n @memoized\n get paginationLinks(): Readonly<PaginationLinks<RT, E>> {\n return getPaginationLinks<RT, E>(this._args.pages);\n }\n}\n\n/**\n * Creates the {@link PaginationLinksSubscription} a links component (such as\n * `<EachLink />`) uses to derive its links from a {@link PagedPaginationState}.\n *\n * ```ts\n * const subscription = createPaginationLinksSubscription({ pages: paginationState });\n *\n * subscription.paginationLinks; // the derived PaginationLinks\n * subscription[DISPOSE](); // tear down when the owning component unmounts\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function createPaginationLinksSubscription<RT, E>(\n args: PaginationLinksSubscriptionArgs<RT, E>\n): PaginationLinksSubscription<RT, E> {\n return new PaginationLinksSubscription(args);\n}\n\ninterface PrivatePaginationLinksSubscription {\n isDestroyed: boolean;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivatePaginationLinksSubscription {\n return sub as PrivatePaginationLinksSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: PaginationLinksSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { Awaitable } from '../request.ts';\nimport { getPromiseResult, setPromiseResult } from '../request.ts';\nimport { defineSignal } from './reactivity/signal.ts';\n\nconst PromiseCache = new WeakMap<Awaitable, PromiseState>();\n\n/**\n * The state of a promise in the \"pending\"\n * state. This is the default initial state.\n *\n */\nexport interface PendingPromise {\n /**\n * The status of the promise.\n *\n */\n status: 'pending';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: true;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: true;\n\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: false;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: null;\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: null;\n}\n\n/**\n * The state of a promise in the \"fulfilled\" state.\n * This is the state of a promise that has resolved\n * successfully.\n *\n */\nexport interface ResolvedPromise<T> {\n /**\n * The status of the promise.\n *\n */\n status: 'fulfilled';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: false;\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: true;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: false;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: T;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: T;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: null;\n}\n\n/**\n * The state of a promise in the \"rejected\" state.\n * This is the state of a promise that has rejected\n * with an error.\n *\n */\nexport interface RejectedPromise<E> {\n /**\n * The status of the promise.\n *\n */\n status: 'rejected';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: false;\n\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: true;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: null;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: E;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: E;\n}\n\n/**\n * The state of a promise. This is the type that is returned\n * from `getPromiseState`.\n *\n * See also:\n * - {@link PendingPromise}\n * - {@link ResolvedPromise}\n * - {@link RejectedPromise}\n *\n */\nexport type PromiseState<T = unknown, E = unknown> = PendingPromise | ResolvedPromise<T> | RejectedPromise<E>;\n\nconst PromiseStateProto = {};\n\n// TODO introduce a new mechanism for defining multiple properties\n// that share a common signal\ndefineSignal(PromiseStateProto, 'reason', null);\ndefineSignal(PromiseStateProto, 'value', null);\ndefineSignal(PromiseStateProto, 'result', null);\ndefineSignal(PromiseStateProto, 'error', null);\ndefineSignal(PromiseStateProto, 'status', 'pending');\ndefineSignal(PromiseStateProto, 'isPending', true);\ndefineSignal(PromiseStateProto, 'isLoading', true);\ndefineSignal(PromiseStateProto, 'isSuccess', false);\ndefineSignal(PromiseStateProto, 'isError', false);\n\nexport function createPromiseState<T, E>(promise: Promise<T> | Awaitable<T, E>): Readonly<PromiseState<T, E>> {\n const state = getPromiseResult<T, E>(promise);\n const promiseState = Object.create(PromiseStateProto) as PromiseState<T, E>;\n\n if (state) {\n if (state.isError) {\n promiseState.error = state.result;\n promiseState.reason = state.result;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n } else {\n promiseState.result = state.result;\n promiseState.value = state.result;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n }\n } else {\n void promise.then(\n (result) => {\n setPromiseResult(promise, { isError: false, result });\n promiseState.result = result;\n promiseState.value = result;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n },\n (error: E) => {\n setPromiseResult(promise, { isError: true, result: error });\n promiseState.error = error;\n promiseState.reason = error;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n }\n );\n }\n\n return promiseState;\n}\n\nconst LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');\ntype LegacyAwaitable<T, E> = { promise: Promise<T> | Awaitable<T, E>; [LegacyPromiseProxy]: true };\n\nfunction isLegacyAwaitable<T, E>(promise: object): promise is LegacyAwaitable<T, E> {\n return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;\n}\n\nfunction getPromise<T, E>(promise: Promise<T> | Awaitable<T, E> | LegacyAwaitable<T, E>): Promise<T> | Awaitable<T, E> {\n return isLegacyAwaitable(promise) ? promise.promise : promise;\n}\n\n/**\n * Returns a reactive state-machine for the provided promise or awaitable.\n *\n * Repeat calls to `getPromiseState` with the same promise will return the same state object\n * making is safe and easy to use in templates and JavaScript code to produce reactive\n * behaviors around promises.\n *\n * `getPromiseState` can be used in both JavaScript and Template contexts.\n *\n * ```ts\n * import { getPromiseState } from '@warp-drive/ember';\n *\n * const state = getPromiseState(promise);\n * ```\n *\n * For instance, we could write a getter on a component that updates whenever\n * the promise state advances or the promise changes, by combining the function\n * with the use of `@cached`\n *\n * ```ts\n * class Component {\n * @cached\n * get title() {\n * const state = getPromiseState(this.args.request);\n * if (state.isPending) {\n * return 'loading...';\n * }\n * if (state.isError) { return null; }\n * return state.result.title;\n * }\n * }\n * ```\n *\n * Or in a template as a helper:\n *\n * ```gjs\n * import { getPromiseState } from '@warp-drive/ember';\n *\n * <template>\n * {{#let (getPromiseState @request) as |state|}}\n * {{#if state.isPending}} <Spinner />\n * {{else if state.isError}} <ErrorForm @error={{state.error}} />\n * {{else}}\n * <h1>{{state.result.title}}</h1>\n * {{/if}}\n * {{/let}}\n * </template>\n * ```\n *\n * If looking to use in a template, consider also the `<Await />` component.\n *\n * See also {@link PromiseState}\n */\nexport function getPromiseState<T = unknown, E = unknown>(\n promise: Promise<T> | Awaitable<T, E>\n): Readonly<PromiseState<T, E>> {\n assert(`getPromiseState expects to be called with a promise: called with ${String(promise)}`, promise);\n const _promise = getPromise(promise);\n let state = PromiseCache.get(_promise) as PromiseState<T, E> | undefined;\n\n if (!state) {\n state = createPromiseState(_promise);\n PromiseCache.set(_promise, state);\n }\n\n return state;\n}\n"],"x_google_ignoreList":[4],"mappings":";;;;AAMA,MAAaG,eAA0CH,eAAe,OAAOI,OAAO,KAAK,CAAC;AAC1F,MAAaC,gBAA2CL,eAAe,OAAOI,OAAO,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4J3F,SAAgBE,aAAgBC,aAA8D;CAK5F,MAAMC,QAAQD,YAAY,EACxBE,WAAW,EACTC,OAAOP,aACT,EACF,CAAC;CACDD,aAAa,eAAeM,KAAK;AACnC;;;;;;AAOA,SAAgBG,aAAaC,KAAaC,KAAiC;CAGzE,OAFwCZ,cAAc,aAE/Ca,CAAW,CAACH,aAAaC,KAAKC,GAAG;AAC1C;;;;;;AAOA,SAAgBE,cAAcC,QAAyB;CAIrD,OAHwCf,cAAc,aAG/Ca,CAAW,CAACC,cAAcC,MAAM;AACzC;;;;;;AAOA,SAAgBC,aAAaD,QAAyB;CAGpD,OAFwCf,cAAc,aAE/Ca,CAAW,CAACG,aAAaD,MAAM;AACxC;AAEA,SAAgBE,WAAcC,QAAgBN,KAAsBO,IAAsB;CAGxF,OAFwCnB,cAAc,aAE/Ca,CAAW,CAACI,WAAWC,QAAQN,KAAKO,EAAE;AAC/C;AAEA,SAAgBC,wBAAiC;CAG/C,OAFwCpB,cAAc,aAE/Ca,CAAW,CAACO,sBAA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QD;EAAM,CAAC;EAC1DJ,aAAaI,QAAQA;EACrBJ,aAAaM,SAASF;EACtBJ,aAAaO,SAAS;EACtBP,aAAaG,UAAU;EACvBH,aAAaQ,YAAY;EACzBR,aAAaS,YAAY;CAC3B,CACF;CAGF,OAAOT;AACT;AAEA,MAAMa,qBAAqBC,OAAOC,IAAI,oBAAoB;AAG1D,SAASC,kBAAwBlB,SAAmD;CAClF,OAAOe,sBAAsBf,WAAW,aAAaA,WAAWA,QAAQe,wBAAwB;AAClG;AAEA,SAASI,WAAiBnB,SAA6F;CACrH,OAAOkB,kBAAkBlB,OAAO,IAAIA,QAAQA,UAAUA;AACxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgBoB,gBACdpB,SAC8B;CAE9B,MAAMqB,WAAWF,WAAWnB,OAAO;CACnC,IAAIC,QAAQL,aAAa0B,IAAID,QAAQ;CAErC,IAAI,CAACpB,OAAO;EACVA,QAAQF,mBAAmBsB,QAAQ;EACnCzB,aAAa2B,IAAIF,UAAUpB,KAAK;CAClC;CAEA,OAAOA;AACT"}
|
|
1
|
+
{"version":3,"file":"-private-ggVX_Iob.js","names":["getOrSetGlobal","peekTransient","setTransient","ARRAY_SIGNAL","Symbol","OBJECT_SIGNAL","setupSignals","buildConfig","hooks","wellknown","Array","createSignal","obj","key","signalHooks","consumeSignal","signal","notifySignal","createMemo","object","fn","willSyncFlushWatchers","waitFor","promise","getOrSetGlobal","ARRAY_SIGNAL","consumeSignal","createMemo","createSignal","notifySignal","OBJECT_SIGNAL","INITIALIZER_PROTO","isInitializer","makeInitializer","fn","Object","assign","create","value","obj","getPrototypeOf","Signals","Symbol","upgradeWithSignals","withSignalStore","initializeSignalStore","Map","createInternalSignal","signals","key","initialValue","warpDriveSignal","context","signal","call","isStale","set","getOrCreateInternalSignal","peekInternalSignal","createInternalMemo","object","memo","consumeInternalMemo","TrackingFrame","add","get","consumeInternalSignal","notifyInternalSignal","withFrame","frameSignals","Set","frameFn","size","clear","parent","isMemo","LightColors","red","green","reset","DarkColors","isLightMode","window","matchMedia","matches","RED","GREEN","RESET","EOL","colorizeLines","lines","Colors","colors","line","str","push","log","args","console","isDirty","isDirtyMemo","printSignal","depth","_dirty","padStart","String","printMemo","consumeInternalSignal","createInternalMemo","createInternalSignal","getOrCreateInternalSignal","makeInitializer","notifyInternalSignal","peekInternalSignal","withSignalStore","entangleSignal","signals","obj","key","initialValue","internalSignal","entangleInitiallyStaleSignal","isStale","createSignalDescriptor","intialValue","enumerable","configurable","get","value","set","defineSignal","v","Object","defineProperty","defineNonEnumerableSignal","desc","signal","target","descriptor","initializer","memoized","getter","memoSignal","bind","gate","_target","setter","isLocal","call","undefined","defineGate","options","assign","getPromiseResult","setPromiseResult","DOMError","defineNonEnumerableSignal","defineSignal","RequestCache","WeakMap","isAbortError","error","name","upgradeLoadingState","state","watchStream","stream","loadingState","reader","getReader","bytesLoaded","shouldForward","_stream","readable","locked","isForwarding","writer","writable","getWriter","buffer","_isPending","_isStarted","_startTime","performance","now","value","done","read","byteLength","_bytesLoaded","_lastPacketTime","item","ready","write","length","push","close","cancel","endTime","_endTime","_isComplete","RequestLoadingState","_future","_triggered","_trigger","future","promise","getStream","sizeHint","_sizeHint","then","_isCancelled","_isErrored","_error","isPending","TransformStream","isStarted","startTime","lastPacketTime","isComplete","isCancelled","isErrored","elapsedTime","completedRatio","remainingRatio","duration","speed","constructor","abort","prototype","RequestStateProto","performRefresh","requester","request","isReload","req","Object","assign","cacheOptions","reload","backgroundReload","defineProperty","get","isError","reason","_loadingState","_request","createRequestState","promiseState","create","refresh","usePolicy","result","status","isLoading","response","content","isSuccess","getRequestState","set","defineSignal","memoized","getRequestState","n","DEFAULT_DEADLINE","DISPOSE","Symbol","dispose","for","isNeverString","val","RequestSubscription","_requester","constructor","store","args","_args","_subscribedTo","_subscription","_intervalStart","_invalidated","_nextInterval","isDestroyed","_DISPOSE","_installListeners","_beginPolling","isIdle","request","_scheduleInterval","query","Boolean","prototype","autorefreshTypes","autorefresh","types","split","Set","autorefreshThreshold","hasValidThreshold","window","has","_latestRequest","Date","now","setTimeout","_maybeUpdate","_clearInterval","clearTimeout","_updateSubscriptions","requestId","_request","lid","_removeSubscriptions","_getRequester","isStore","notifications","subscribe","_id","op","_isUpdating","latest","requestManager","_deduped","get","priority","state","reqState","isRefreshing","blocking","isLoading","unsubscribe","hasWindow","hasDocument","document","hasWindowEvents","addEventListener","hasDocumentEvents","isOnline","navigator","onLine","_unavailableStart","isHidden","visibilityState","_onlineChanged","event","type","passive","capture","_backgroundChanged","mode","silent","isPending","canAttempt","size","Error","shouldAttempt","deadline","realMode","autorefreshBehavior","requester","reload","refresh","_localRequest","finally","retry","errorFeatures","contentFeatures","feat","latestRequest","abort","_originalRequest","_originalQuery","isOriginalRequest","result","undefined","createRequestSubscription","upgradeSubscription","sub","self","removeEventListener","memoized","signal","getRequestState","g","i","n","abs","Math","getHref","link","href","PageCache","prototype","request","state","selfLink","prevLink","nextLink","firstLink","lastLink","pageNumber","before","after","constructor","manager","url","value","data","isRequested","Boolean","isLoaded","isSuccess","isError","isLoading","isCancelled","reason","prev","getPageCache","next","first","last","isLinked","load","content","self","links","getPageNumber","firstPage","lastPage","prevPage","nextPage","setPageNumber","updateLinkage","totalPages","updateLinks","lookupLinkage","leftSide","rightSide","setAfter","setBefore","firstPageDelta","lastPageDelta","lookupLinkageForward","lookupLinkageBackwards","page","document","readPageHints","currentPage","PageCache","memoized","signal","g","i","n","PaginationCacheMap","Map","defaultPageHints","document","currentPage","meta","page","totalPages","PaginationCache","prototype","firstPage","isNumbered","pageHints","constructor","key","pagesCache","installPageHints","readPageHints","getPageCache","url","get","set","loadPage","request","isLoaded","isError","load","then","updateFirstPage","getTotalPages","maybeFirstPage","before","pageNumber","pages","self","Symbol","iterator","after","data","getPaginationCache","cache","clearPaginationCache","clear","getHref","getPaginationCache","defineSignal","memoized","n","PaginationState","constructor","request","pageHints","store","requester","_adoptTarget","setup","activePageRequest","activePage","prototype","totalPages","paginationCache","pages","self","Symbol","iterator","end","frontierEnd","page","frontierStart","after","data","hasNext","Boolean","nextLink","hasPrevious","prevLink","nextRequest","url","getPageCache","previousRequest","document","content","selfLink","links","firstLink","first","cacheKey","cache","installPageHints","getTotalPages","initialPage","loadPage","_activate","existing","adoptPage","key","value","loadPrev","_extend","loadNext","dir","frontier","isRequested","isError","method","cacheOptions","reload","isLoaded","PaginationStateCache","WeakMap","getPaginationState","state","get","set","memoized","n","PaginationLinksCache","WeakMap","RealPaginationLink","isReal","url","index","isCurrent","distanceFromActiveIndex","constructor","activeIndex","loadPage","Math","abs","_loadPage","text","setActive","PlaceholderPaginationLink","indexRange","rangeSize","start","end","min","_mergeRange","newRange","oldStart","oldEnd","newStart","newEnd","mergedRange","max","RelationalPaginationLink","rel","PaginationLinks","paginationState","first","activePage","firstLink","selfLink","prototype","prev","prevLink","next","nextLink","last","lastLink","links","cache","paginationCache","isNumbered","firstPage","totalPages","pageNumber","previousPage","currentPage","push","after","getPaginationLinks","state","get","set","getPaginationState","defineSignal","memoized","createRequestSubscription","DISPOSE","n","PaginationSubscription","constructor","store","args","_args","isDestroyed","_seedRequest","_navTarget","_DISPOSE","_requestSubscription","paginationState","request","active","_navRequest","pageHints","_resolveNavigation","prototype","adopted","adoptPage","isIdle","isLoading","reqState","paginationCache","isSuccess","isNavigating","loadingState","isError","isCancelled","reason","errorFeatures","isHidden","isOnline","retry","contentFeatures","feat","loadPrev","loadNext","loadPage","isRefreshing","abort","latestRequest","createPaginationSubscription","upgradeSubscription","sub","self","memoized","getPaginationLinks","DISPOSE","n","PaginationLinksSubscription","constructor","args","_args","isDestroyed","_DISPOSE","paginationLinks","pages","prototype","createPaginationLinksSubscription","upgradeSubscription","sub","self","getPromiseResult","setPromiseResult","defineSignal","PromiseCache","WeakMap","PromiseStateProto","createPromiseState","promise","state","promiseState","Object","create","isError","error","result","reason","status","isPending","isLoading","value","isSuccess","then","LegacyPromiseProxy","Symbol","for","isLegacyAwaitable","getPromise","getPromiseState","_promise","get","set"],"sources":["../../../src/signals/reactivity/configure.ts","../../../src/signals/reactivity/internal.ts","../../../src/signals/reactivity/signal.ts","../../../src/signals/request-state.ts","../../../../../node_modules/.pnpm/decorat_5d4eca388601a94e7fbc656401b751d1/node_modules/decorator-transforms/dist/runtime--fcdnjmJ.js","../../../src/signals/request-subscription.ts","../../../src/signals/page-cache.ts","../../../src/signals/pagination-cache.ts","../../../src/signals/pagination-state.ts","../../../src/signals/pagination-links.ts","../../../src/signals/pagination-subscription.ts","../../../src/signals/pagination-links-subscription.ts","../../../src/signals/promise-state.ts"],"sourcesContent":["import { assert } from '@warp-drive/core/build-config/macros';\n\n// oxlint-disable-next-line no-unused-vars\nimport type { NotificationManager } from '../../store/-private/managers/notification-manager.ts';\nimport { getOrSetGlobal, peekTransient, setTransient } from '../../types/-private.ts';\n\nexport const ARRAY_SIGNAL: '___(unique) Symbol(#[])' = getOrSetGlobal('#[]', Symbol('#[]'));\nexport const OBJECT_SIGNAL: '___(unique) Symbol(#{})' = getOrSetGlobal('#{}', Symbol('#{}'));\n\n/*\n * Requirements:\n *\n * Signal:\n *\n * - signal: a way of creating a reference that we can dirty when we desire to notify\n * - @signal: a way of creating an accessor on an object that subscribes to a signal on access\n * and notifies the signal on set, or of upgrading a descriptor to be such an accessor\n * - defineSignal: a way of creating a signal on an object\n * - notifySignal: a way of notifying the underlying signal that it has been dirtied\n * - peekSignal: a way of inspecting the signal without notifying it\n *\n * - gate: a memoized getter function that re-runs when on access if its signal is dirty\n * conceptually, a gate is a tightly coupled signal and memo\n * - @gate: a way of creating a gate on an object or upgrading a descriptor with a getter\n * to be a gate\n * - defineGate: a way of creating a gate on an object\n * - notifySignal: a way of notifying the signal for a gate that it has been dirtied\n *\n * - memo:\n * - @memo: a way of creating a memoized getter on an object or upgrading a descriptor with a getter\n * to be a memo\n * - defineMemo: a way of creating a memo on an object\n *\n * - signalStore: storage bucket for signals associated to an object\n * - withSignalStore: a way of pre-creating a signal store on an object\n */\n\n/**\n * An Opaque type that represents a framework specific or TC39 signal.\n *\n * It may be an array of signals or a single signal.\n *\n * @private\n */\nexport type SignalRef = unknown;\n/**\n * The hooks which MUST be configured in order to use reactive arrays,\n * resources and documents with framework specfic signals or TC39 signals.\n *\n * Support for multiple frameworks simultaneously can be done via\n * this abstraction by returning multiple signals from the `createSignal`\n * method, and consuming the correct one via the correct framework via\n * the `consumeSignal` and `notifySignal` methods.\n *\n * Unlike many signals implementations, WarpDrive does not wrap values as\n * signals directly, but instead uses signals to alert the reactive layer\n * to changes in the underlying cache. E.g. a signal is associated to a value,\n * but does not serve as the cache for that value directly. We refer to this as\n * a \"gate\", the pattern has also been called \"side-signals\".\n *\n * A no-op implementation is allowed, though it may lead to performance issues\n * in locations that use createMemo as no memoization would be done. This is\n * typically desirable only when integrating with a framework that does its own\n * memoization and does not integrate with any signals-like primitive. For these\n * scenarios you may also be interested in integrating with the {@link NotificationManager}\n * more directly.\n *\n * @public\n */\nexport interface SignalHooks<T = SignalRef> {\n /**\n * Create a signal for the given key associated to the given object.\n *\n * This method does *not* need to cache the signal, it will only be\n * called once for a given object and key. However, if your framework\n * will look for a signal cache on the object in a given location or may\n * have created its own signal on the object for some reason it may be\n * useful to ensure such cache is properly updated.\n */\n createSignal: (obj: object, key: string | symbol) => T;\n /**\n * Consume (mark as acccessed) a signal previously created via createSignal.\n */\n consumeSignal: (signal: T) => void;\n /**\n * Alert a signal previously created via createSignal that its associated value has changed.\n */\n notifySignal: (signal: T) => void;\n /**\n * Take the given function and wrap it in signals-based memoization. Analagous\n * to a Computed in the TC39 spec.\n *\n * Should return a function which when run provides the latest value of the original\n * function.\n */\n createMemo: <F>(obj: object, key: string | symbol, fn: () => F) => () => F;\n\n /**\n * If the signals implementation allows synchronous flushing of watchers, and\n * has scheduled such a flush (e.g. watchers will run before the current calling\n * context yields) this should return \"true\".\n *\n * This is generally something that should return false for anything but the few\n * frameworks that extensively handle their own reactivity => render scheduling.\n *\n * For an example, see EmberJS's backburner scheduler which functioned as a microtask\n * polyfill.\n */\n willSyncFlushWatchers: () => boolean;\n\n /**\n * An optional method that allows wrapping key promises within WarpDrive\n * for things like test-waiters.\n */\n waitFor?: <K>(promise: Promise<K>) => Promise<K>;\n}\n\n/**\n * Contains information a {@link SignalHooks} implementation may want\n * to use, such as the specialized key used for the signal\n * representing an array's contents / length.\n *\n * ```ts\n * interface HooksOptions {\n * wellknown: {\n * Array: symbol | string;\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface HooksOptions {\n /**\n * A list of specialized symbols/strings\n * used by WarpDrive to encapsulate key\n * reactivity concerns.\n */\n wellknown: {\n /**\n * The key used when the signal provides reactivity for the\n * `length` or \"contents\" of an array.\n *\n * Arrays only use a single signal for all accesses, regardless\n * of index, property or method: this one.\n */\n Array: symbol | string;\n };\n}\n\n/**\n * Configures the signals implementation to use. Supports multiple\n * implementations simultaneously.\n *\n * See {@link HooksOptions} for the options passed to the provided function\n * when called.\n *\n * See {@link SignalHooks} for the implementation the callback function should\n * return.\n *\n * @public\n * @param buildConfig - a function that takes options and returns a configuration object\n */\nexport function setupSignals<T>(buildConfig: (options: HooksOptions) => SignalHooks<T>): void {\n // We want to assert this but can't because too many package manager\n // and bundler bugs exist that cause this to be called multiple times\n // for what should be a single call.\n // assert(`Cannot override configured signal hooks`, peekTransient('signalHooks') === null);\n const hooks = buildConfig({\n wellknown: {\n Array: ARRAY_SIGNAL,\n },\n });\n setTransient('signalHooks', hooks);\n}\n\n/**\n * Internal method for consuming the configured `createSignal` hook\n *\n * @private\n */\nexport function createSignal(obj: object, key: string | symbol): SignalRef {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.createSignal(obj, key);\n}\n\n/**\n * Internal method for consuming the configured `consumeSignal` hook\n *\n * @private\n */\nexport function consumeSignal(signal: SignalRef): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.consumeSignal(signal);\n}\n\n/**\n * Internal method for consuming the configured `notifySignal` hook\n *\n * @private\n */\nexport function notifySignal(signal: SignalRef): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.notifySignal(signal);\n}\n\nexport function createMemo<T>(object: object, key: string | symbol, fn: () => T): () => T {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.createMemo(object, key, fn);\n}\n\nexport function willSyncFlushWatchers(): boolean {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n assert(`Signal hooks not configured`, signalHooks);\n return signalHooks.willSyncFlushWatchers();\n}\n\n/**\n * Wraps `promise` using the configured {@link SignalHooks.waitFor}, if any,\n * for things like test-waiters. Returns `promise` unchanged if no\n * `waitFor` hook is configured.\n */\nexport function waitFor<K>(promise: Promise<K>): Promise<K> {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n\n if (signalHooks?.waitFor) {\n return signalHooks.waitFor(promise);\n }\n return promise;\n}\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport { getOrSetGlobal } from '../../types/-private.ts';\nimport {\n ARRAY_SIGNAL,\n consumeSignal,\n createMemo,\n createSignal,\n notifySignal,\n OBJECT_SIGNAL,\n type SignalRef,\n} from './configure.ts';\n\nexport type { SignalRef };\nexport { ARRAY_SIGNAL, OBJECT_SIGNAL };\n\nconst INITIALIZER_PROTO = { isInitializer: true } as const;\ninterface Initializer {\n value: () => unknown;\n}\n/**\n * Wraps `fn` so that a signal can recognize it as a lazy initializer\n * for its value rather than the value itself, deferring the call to\n * `fn` until the signal is first accessed.\n */\nexport function makeInitializer(fn: () => unknown): Initializer {\n // we use a prototype to ensure that the initializer is not enumerable\n // and does not interfere with the signal's value.\n return Object.assign(Object.create(INITIALIZER_PROTO), { value: fn }) as Initializer;\n}\n\nfunction isInitializer(obj: unknown): obj is Initializer {\n return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === INITIALIZER_PROTO;\n}\n\n/**\n * A WarpDriveSignal is a wrapper around a framework specific or TC39 signal\n * that enables us to store and manage the signal in a universal way.\n *\n * WarpDrive uses signals to manage three separate concepts:\n *\n * - as a `storage` for a value local to the object that we want to be reactive\n * (see `@local` schema field for an example)\n * - as a `gate` for a memoized getter that we want to act as a reactive property\n * but whose value is computed/pulled from a non-reactive source elsewhere\n * and whose latest value is stored in the signal\n * (see `field` schema field for an example)\n * - as a `gate` with a manually managed value updated on pull when `isStale` is true\n *\n *\n * It offers\n *\n * - a non-reactive way to access/update the current value\n * - a non-reactive way to mark the signal as dirtied\n * - a non-reactive way to store content for why the signal was dirtied\n * - access to the underlying Signal(s) in-use\n *\n * For debugging:\n * - the \"key\" or \"name\" of the signal\n * - the \"object identity\" or \"context\" to which the signal is attached\n *\n * @private\n */\nexport interface WarpDriveSignal {\n /**\n * The \"key\" or \"name\" of the signal.\n * This is usually (but not always) the name of a property\n * on the object to which the signal is attached.\n *\n * This is used for debugging purposes.\n * It is not used for any other purpose.\n *\n * @internal\n */\n key: string | symbol;\n\n /**\n * The \"object identity\" or \"context\" to which the\n * signal is attached.\n *\n * This is used for debugging purposes.\n * It is not used for any other purpose.\n *\n * @internal\n */\n context: object;\n\n /**\n * The underlying signal(s) in-use.\n *\n * Generally, this is a single signal.\n *\n * In some cases multiple signals need to be condensed,\n * such as to support legacy Ember Array APIs or to\n * support reactive-objects shared between the code of\n * multiple frameworks.\n *\n * In such cases, this value may be an array.\n *\n * e.g. (pseudo-code for Ember):\n *\n * setupSignals({\n * createSignal: (obj, key, initialValue) => {\n * if (isArraySignal(key)) {\n * return [\n * tagForProperty(obj, key),\n * tagForProperty(obj, '[]'),\n * tagForProperty(obj, 'length'),\n * ];\n * }\n * return tagForProperty(obj, key);\n * },\n *\n * consumeSignal: (signal) => {\n * if (Array.isArray(signal)) {\n * signal.forEach((s) => consumeTag(s));\n * } else {\n * consumeTag(signal);\n * }\n * },\n *\n * dirtySignal: (signal) => {\n * if (Array.isArray(signal)) {\n * signal.forEach((s) => dirtyTag(s));\n * } else {\n * dirtyTag(signal);\n * }\n * },\n * });\n *\n * @private\n */\n signal: SignalRef;\n\n /**\n * The last \"value\" computed for this signal when\n * a signal is also used for storage.\n *\n * @private\n */\n value: unknown;\n\n /**\n * Whether ths signal is known to have been dirtied.\n * This is useful *both* when manually managing the\n * `value` cache and when using the signal as a\n * \"gate\"\n *\n * @private\n */\n isStale: boolean;\n}\n\n/**\n * We attach signals to their context object via\n * a Map attached to the object via this symbol.\n *\n * This allows us to store multiple signals\n * on the same object with smaller memory\n * overhead and no WeakMap lookups.\n *\n * Performance sensitive objects should\n * pre-warm their shape by assigning this\n * during initialization.\n *\n * ```ts\n * initializeSignalStore(obj);\n * ```\n *\n * @private\n */\nexport const Signals: '___(unique) Symbol(Signals)' = getOrSetGlobal('Signals', Symbol('Signals'));\nexport type SignalStore = Map<string | symbol, WarpDriveSignal>;\n\n/**\n * A type util to recast the object as having a signal store.\n *\n * @private\n */\nexport function upgradeWithSignals<T extends object>(obj: T): asserts obj is T & { [Signals]: SignalStore } {}\n\n/**\n * A util that will create a signal store on the object\n * if it does not already exist and returns the associated\n * signal store.\n *\n * @private\n */\nexport function withSignalStore<T extends object>(obj: T): SignalStore {\n upgradeWithSignals(obj);\n if (!obj[Signals]) {\n initializeSignalStore(obj);\n }\n return obj[Signals];\n}\n\n/**\n * A util that will create a signal store on the object\n * if it does not already exist.\n *\n * Useful for pre-warming the shape of an object to ensure\n * a key-transition to add it is not required later.\n *\n * @private\n */\nexport function initializeSignalStore<T extends object>(obj: T): asserts obj is T & { [Signals]: SignalStore } {\n upgradeWithSignals(obj);\n assert(`Signal store already exists on object`, !obj[Signals]);\n obj[Signals] = new Map();\n}\n\nexport function createInternalSignal(\n signals: SignalStore,\n obj: object,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n const warpDriveSignal = {\n key,\n context: obj,\n signal: createSignal(obj, key),\n value: isInitializer(initialValue) ? initialValue.value.call(obj) : initialValue,\n isStale: false,\n };\n\n signals.set(key, warpDriveSignal);\n\n return warpDriveSignal;\n}\n\nexport function getOrCreateInternalSignal(\n signals: SignalStore,\n obj: object,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let signal = peekInternalSignal(signals, key);\n if (!signal) {\n signal = createInternalSignal(signals, obj, key, initialValue);\n }\n return signal;\n}\n\nexport function createInternalMemo<T>(\n signals: SignalStore,\n object: object,\n key: string | symbol,\n fn: () => T\n): () => T {\n assert(`Expected no signal/memo to exist for key \"${String(key)}\"`, !peekInternalSignal(signals, key));\n if (DEBUG) {\n return withFrame(signals, object, key, fn);\n } else {\n const memo = createMemo(object, key, fn);\n signals.set(key, memo as unknown as WarpDriveSignal);\n return memo;\n }\n}\n\nexport function consumeInternalMemo<T>(fn: () => T): T {\n TrackingFrame?.signals.add(fn as unknown as WarpDriveSignal);\n return fn();\n}\n\n/**\n * Looks up the {@link WarpDriveSignal} stored for `key` in `signals`,\n * if one has already been created, without creating or consuming it.\n */\nexport function peekInternalSignal(\n signals: SignalStore | undefined,\n key: string | symbol\n): WarpDriveSignal | undefined {\n return signals?.get(key);\n}\n\nexport function consumeInternalSignal(signal: WarpDriveSignal): void {\n TrackingFrame?.signals.add(signal);\n consumeSignal(signal.signal);\n}\n\n/**\n * Marks `signal` as stale and notifies its underlying framework/TC39\n * signal, scheduling any of its consumers for re-render/re-computation.\n */\nexport function notifyInternalSignal(signal: WarpDriveSignal | undefined): void {\n if (signal) {\n signal.isStale = true;\n notifySignal(signal.signal);\n }\n}\n\ninterface TrackingFrame {\n object: object;\n key: string | symbol;\n signals: Set<WarpDriveSignal>;\n parent: TrackingFrame | null;\n}\n\nlet TrackingFrame: TrackingFrame | null = null;\n\n/**\n * This is currently just for signals debugging, but it could be used in production\n * if we wanted to eliminate the need for frameworks to implement createMemo / to\n * allow us to add our own Watcher.\n *\n * @internal\n */\nfunction withFrame<T>(signals: SignalStore, object: object, key: string | symbol, fn: () => T): () => T {\n const frameSignals = new Set<WarpDriveSignal>();\n const frameFn = () => {\n if (frameSignals.size) {\n frameSignals.clear();\n }\n TrackingFrame = {\n object,\n key,\n signals: frameSignals,\n parent: TrackingFrame,\n };\n try {\n return fn();\n } finally {\n TrackingFrame = TrackingFrame.parent;\n }\n };\n const memo = createMemo(object, key, frameFn);\n // @ts-expect-error\n memo.signals = frameSignals;\n signals.set(key, memo as unknown as WarpDriveSignal);\n\n return memo;\n}\n\nfunction isMemo(obj: unknown): obj is { signals: Set<WarpDriveSignal> } {\n // @ts-expect-error\n return typeof obj === 'function' && obj.signals instanceof Set;\n}\n\nif (DEBUG) {\n // @ts-expect-error adding to global API\n globalThis.debugWarpDriveSignals = (obj: object, key?: string | symbol): boolean => {\n upgradeWithSignals(obj);\n const signals = obj[Signals];\n if (!signals) {\n log('The object has no associated signals');\n return false;\n }\n\n if (key) {\n const signal = signals.get(key);\n if (!signal) {\n log(`No signal found for key \"${String(key)}\"`);\n return false;\n }\n log(signal);\n if (isMemo(signal)) {\n colorizeLines(printMemo(signal, key));\n return true;\n } else {\n colorizeLines(printSignal(signal, key));\n return true;\n }\n }\n\n const lines: string[] = [];\n for (const [k, signal] of signals) {\n if (isMemo(signal)) continue;\n printSignal(signal, k, lines);\n }\n for (const [k, signal] of signals) {\n if (isMemo(signal)) {\n printMemo(signal, k, lines);\n }\n }\n\n log(signals);\n colorizeLines(lines);\n\n return true;\n };\n}\n\nconst LightColors = {\n red: 'color: red;',\n green: 'color: green;',\n reset: 'color: inherit;',\n};\nconst DarkColors = {\n red: 'color: red;',\n green: 'color: lightgreen;',\n reset: 'color: inherit;',\n};\nfunction isLightMode() {\n if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {\n return true;\n }\n return false;\n}\n\nconst RED = {} as unknown as string;\nconst GREEN = {} as unknown as string;\nconst RESET = {} as unknown as string;\nconst EOL = {} as unknown as string;\n\nfunction colorizeLines(lines: string[]): void {\n const Colors = isLightMode() ? LightColors : DarkColors;\n const colors = [];\n let line = '';\n\n for (const str of lines) {\n if (str === RED) {\n colors.push(Colors.red);\n line += '%c';\n } else if (str === GREEN) {\n colors.push(Colors.green);\n line += '%c';\n } else if (str === RESET) {\n colors.push(Colors.reset);\n line += '%c';\n } else if (str === EOL) {\n line += '\\n';\n } else {\n line += str;\n }\n }\n\n log(line, ...colors);\n}\n\nfunction log(...args: unknown[]): void {\n // oxlint-disable-next-line no-console\n console.log(...args);\n}\n\nfunction isDirty(signal: WarpDriveSignal): boolean {\n return signal.isStale;\n}\n\nfunction isDirtyMemo(memo: { signals: Set<WarpDriveSignal> }): boolean {\n // iterate simple signals first to get fastest answer\n for (const signal of memo.signals) {\n if (isMemo(signal)) continue;\n if (isDirty(signal)) {\n return true;\n }\n }\n for (const signal of memo.signals) {\n if (isMemo(signal)) {\n return isDirtyMemo(signal);\n }\n }\n return false;\n}\n\nfunction printSignal(signal: WarpDriveSignal, key: string | symbol, lines: string[] = [], depth = 0): string[] {\n const _dirty = isDirty(signal);\n lines.push(\n `${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `,\n _dirty ? RED : GREEN,\n `${String(key)}`,\n RESET,\n EOL\n );\n return lines;\n}\n\nfunction printMemo(\n memo: { signals: Set<WarpDriveSignal> },\n key: string | symbol,\n lines: string[] = [],\n depth = 0\n): string[] {\n const _dirty = isDirtyMemo(memo);\n lines.push(\n `${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `,\n _dirty ? RED : GREEN,\n `<memo> ${String(key)}`,\n RESET,\n `: (consumes ${memo.signals.size} signals)`,\n EOL\n );\n for (const signal of memo.signals) {\n if (isMemo(signal)) continue;\n printSignal(signal, signal.key, lines, depth + 1);\n }\n for (const signal of memo.signals) {\n if (isMemo(signal)) {\n printMemo(signal, signal.key, lines, depth + 1);\n }\n }\n return lines;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { Signals, SignalStore, WarpDriveSignal } from './internal.ts';\nimport {\n consumeInternalSignal,\n createInternalMemo,\n createInternalSignal,\n getOrCreateInternalSignal,\n makeInitializer,\n notifyInternalSignal,\n peekInternalSignal,\n withSignalStore,\n} from './internal.ts';\n\n/**\n * Creates a signal for the key/object pairing and subscribes to the signal.\n *\n * Use when you need to ensure a signal exists and is subscribed to.\n *\n * @private\n */\nexport function entangleSignal<T extends object>(\n signals: SignalStore,\n obj: T,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, obj, key, initialValue);\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal;\n}\n\nexport function entangleInitiallyStaleSignal<T extends object>(\n signals: SignalStore,\n obj: T,\n key: string | symbol,\n initialValue: unknown\n): WarpDriveSignal {\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, obj, key, initialValue);\n internalSignal.isStale = true; // mark it as stale\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal;\n}\n\nexport function createSignalDescriptor(key: string | symbol, intialValue: unknown): PropertyDescriptor {\n return {\n enumerable: true,\n configurable: false,\n get(this: { [Signals]: SignalStore }) {\n const signals = withSignalStore(this);\n const internalSignal = entangleSignal(signals, this, key, intialValue);\n internalSignal.isStale = false; // reset stale state\n return internalSignal.value;\n },\n set(this: { [Signals]: SignalStore }, value: unknown) {\n const signals = withSignalStore(this);\n const internalSignal = getOrCreateInternalSignal(signals, this, key, intialValue);\n\n if (internalSignal.value !== value) {\n internalSignal.value = value;\n notifyInternalSignal(internalSignal);\n }\n },\n };\n}\n\n/**\n * define an enumerable signal property.\n *\n * Akin to Object.defineProperty.\n *\n * The signal will be lazily created when accessed and scoped to the\n * instance of the object.\n *\n * @private\n */\nexport function defineSignal<T extends object>(obj: T, key: string, v?: unknown): void {\n Object.defineProperty(obj, key, createSignalDescriptor(key, v));\n}\n\n/**\n * Define a non-enumerable signal property.\n *\n * @private\n */\nexport function defineNonEnumerableSignal<T extends object>(obj: T, key: string, v?: unknown): void {\n const desc = createSignalDescriptor(key, v);\n desc.enumerable = false;\n Object.defineProperty(obj, key, desc);\n}\n\ninterface DecoratorPropertyDescriptor extends PropertyDescriptor {\n initializer?: () => unknown;\n}\n\n/**\n * Decorator version of creating a signal.\n */\nexport function signal<T extends object, K extends keyof T & string>(\n target: T,\n key: K,\n descriptor?: DecoratorPropertyDescriptor\n): void {\n // Error on `@signal()`, `@signal(...args)``\n assert(\n 'You attempted to use @signal(), which is not necessary nor supported. Remove the parentheses and you will be good to go!',\n target !== undefined\n );\n assert(\n `You attempted to use @signal on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @signal(${Array.from(\n arguments\n )\n .map((d) => `'${d}'`)\n .join(\n ', '\n )}) ), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@signal`'}`,\n typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3\n );\n\n return createSignalDescriptor(\n key,\n descriptor.initializer ? makeInitializer(descriptor.initializer) : null\n ) as unknown as void;\n}\n\n/**\n * Decorator version of creating a memoized getter\n */\nexport function memoized<T extends object, K extends keyof T & string>(\n target: T,\n key: K,\n descriptor: PropertyDescriptor\n): PropertyDescriptor {\n // Error on `@memoized()`, `@memoized(...args)`, and `@memoized propName = value;`\n assert(\n 'You attempted to use @memoized(), which is not necessary nor supported. Remove the parentheses and you will be good to go!',\n target !== undefined\n );\n assert(\n `You attempted to use @memoized on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @memoized(${Array.from(\n arguments\n )\n .map((d) => `'${d}'`)\n .join(\n ', '\n )}), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@memoized`'}`,\n typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3\n );\n assert(\n `The @memoized decorator must be applied to getters. '${key}' is not a getter.`,\n typeof descriptor.get === 'function'\n );\n\n // oxlint-disable-next-line typescript/unbound-method\n const getter = descriptor.get;\n descriptor.get = function () {\n const signals = withSignalStore(this);\n\n let memoSignal = signals.get(key);\n if (!memoSignal) {\n memoSignal = createInternalMemo(signals, this, key, getter.bind(this)) as unknown as WarpDriveSignal;\n }\n return (memoSignal as unknown as () => unknown)();\n };\n\n return descriptor;\n}\n\n/**\n * Decorator version of creating a gate.\n *\n * @private\n */\nexport function gate<T extends object, K extends keyof T & string>(\n _target: T,\n key: K,\n desc: PropertyDescriptor\n): PropertyDescriptor {\n // oxlint-disable-next-line typescript/unbound-method\n const getter = desc.get as (this: T) => unknown;\n // oxlint-disable-next-line typescript/unbound-method\n const setter = desc.set as (this: T, v: unknown) => void;\n const isLocal = (desc as unknown as { isLocal?: boolean }).isLocal;\n\n desc.get = function (this: T) {\n const signals = withSignalStore(this);\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n internalSignal = createInternalSignal(signals, this, key, getter.call(this));\n } else if (internalSignal.isStale) {\n internalSignal.isStale = false;\n internalSignal.value = getter.call(this);\n }\n\n consumeInternalSignal(internalSignal);\n return internalSignal.value;\n };\n\n if (setter) {\n desc.set = function (this: T, v: unknown) {\n const signals = withSignalStore(this);\n let internalSignal = peekInternalSignal(signals, key);\n if (!internalSignal) {\n // we can't use `v` as initialValue here because setters don't\n // return the value and the final value may be different\n // than what the setter was called with.\n internalSignal = createInternalSignal(signals, this, key, undefined);\n internalSignal.isStale = true;\n }\n setter.call(this, v);\n // when a gate is set, we do not notify the signal\n // as its update is controlled externally.\n // unless it specifically sets itself to be locally managed\n if (isLocal) {\n internalSignal.isStale = true;\n notifyInternalSignal(internalSignal);\n }\n };\n }\n return desc;\n}\n\n/**\n * Defines a reactive \"gated\" property on `obj` using `desc` as its\n * getter/setter descriptor.\n *\n * Unlike a signal defined with {@link defineSignal}, a gated property's\n * consumers are not notified when the property is set, since its update\n * is expected to be controlled externally (for instance, by a signal it\n * derives its value from) unless the descriptor opts into being locally\n * managed.\n *\n * Akin to `Object.defineProperty`.\n *\n * @private\n */\nexport function defineGate<T extends object>(obj: T, key: string, desc: PropertyDescriptor): void {\n const options = Object.assign({ enumerable: true, configurable: false }, gate(obj, key as keyof T & string, desc));\n Object.defineProperty(obj, key, options);\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { Awaitable, Future } from '../request.ts';\nimport { getPromiseResult, setPromiseResult } from '../request.ts';\nimport type { RequestManager } from '../request/-private/manager.ts';\nimport { DOMError } from '../request/-private/utils.ts';\nimport type { Store } from '../store/-private/store-service.ts';\nimport type {\n ImmutableRequestInfo,\n RequestInfo,\n ResponseInfo,\n StructuredDataDocument,\n StructuredErrorDocument,\n} from '../types/request.ts';\n// oxlint-disable-next-line no-unused-vars\nimport type { PendingPromise, PromiseState, RejectedPromise, ResolvedPromise } from './promise-state.ts';\nimport { defineNonEnumerableSignal, defineSignal } from './reactivity/signal.ts';\n\nconst RequestCache = new WeakMap<Future<unknown>, RequestState>();\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMError && error.name === 'AbortError';\n}\n\ninterface PrivateLoadingState {\n _sizeHint: number;\n _bytesLoaded: number;\n _startTime: number;\n _endTime: number;\n _lastPacketTime: number;\n _isPending: boolean;\n _isStarted: boolean;\n _isComplete: boolean;\n _isCancelled: boolean;\n _isErrored: boolean;\n _error: Error | null;\n _stream: TransformStream | null;\n _future: Future<unknown>;\n _triggered: boolean;\n}\n\nfunction upgradeLoadingState(state: unknown): PrivateLoadingState {\n return state as PrivateLoadingState;\n}\n\nasync function watchStream(stream: ReadableStream<Uint8Array>, loadingState: RequestLoadingState): Promise<void> {\n const state = upgradeLoadingState(loadingState);\n const reader = stream.getReader();\n let bytesLoaded = 0;\n let shouldForward = state._stream !== null && state._stream.readable.locked;\n let isForwarding = shouldForward;\n let writer = state._stream?.writable.getWriter();\n const buffer = [];\n\n state._isPending = false;\n state._isStarted = true;\n state._startTime = performance.now();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n bytesLoaded += value.byteLength;\n state._bytesLoaded = bytesLoaded;\n state._lastPacketTime = performance.now();\n\n shouldForward = shouldForward || (state._stream !== null && state._stream.readable.locked);\n\n if (shouldForward) {\n if (!isForwarding) {\n isForwarding = true;\n writer = state._stream!.writable.getWriter();\n for (const item of buffer) {\n await writer.ready;\n await writer.write(item);\n }\n buffer.length = 0;\n }\n await writer!.ready;\n await writer!.write(value);\n } else {\n buffer.push(value);\n }\n }\n\n // if we are still forwarding, we need to close the writer\n if (isForwarding) {\n await writer!.ready;\n await writer!.close();\n } else if (state._stream) {\n // if we are not forwarding, we need to cancel the stream\n await state._stream.readable.cancel('The Stream Has Already Ended');\n state._stream = null;\n }\n\n const endTime = performance.now();\n state._endTime = endTime;\n state._isComplete = true;\n state._isStarted = false;\n}\n\n/**\n * Lazily consumes the stream of a request, providing a number of\n * reactive properties that can be used to build UIs that respond\n * to the progress of a request.\n *\n * @hideconstructor\n */\nexport class RequestLoadingState {\n /** @internal */\n declare private _sizeHint: number;\n /** @internal */\n declare private _bytesLoaded: number;\n /** @internal */\n declare private _startTime: number;\n /** @internal */\n declare private _endTime: number;\n /** @internal */\n declare private _lastPacketTime: number;\n /** @internal */\n declare private _isPending: boolean;\n /** @internal */\n declare private _isStarted: boolean;\n /** @internal */\n declare private _isComplete: boolean;\n /** @internal */\n declare private _isCancelled: boolean;\n /** @internal */\n declare private _isErrored: boolean;\n /** @internal */\n declare private _error: Error | null;\n\n /** @internal */\n private _stream: TransformStream | null = null;\n /** @internal */\n private _future: Future<unknown>;\n /** @internal */\n private _triggered = false;\n /** @internal */\n private _trigger() {\n if (this._triggered) {\n return;\n }\n this._triggered = true;\n const future = this._future;\n const promise: Promise<ReadableStream<Uint8Array> | null> & { sizeHint?: number } = future.getStream();\n if (promise.sizeHint) {\n this._sizeHint = promise.sizeHint;\n }\n this.promise = promise.then(\n (stream) => {\n if (!stream) {\n this._isPending = false;\n this._isComplete = true;\n return;\n }\n return watchStream(stream, this);\n },\n (error: Error) => {\n this._isPending = false;\n this._isStarted = false;\n if (isAbortError(error)) {\n this._isCancelled = true;\n this._isComplete = true;\n }\n this._isErrored = true;\n this._error = error;\n }\n );\n }\n\n /**\n * Resolves once the stream has finished being consumed, or rejects\n * if the request errors. `null` until first accessed.\n */\n promise: Promise<void> | null = null;\n\n /**\n * Whether the stream has not yet started being consumed.\n */\n get isPending(): boolean {\n this._trigger();\n return this._isPending;\n }\n\n /**\n * The total size of the response in bytes, if known ahead of time\n * (via a `Content-Length` header or similar).\n */\n get sizeHint(): number {\n this._trigger();\n return this._sizeHint;\n }\n\n /**\n * A readable stream of the response content. Accessing this property\n * begins consumption of the underlying request stream.\n */\n get stream(): ReadableStream | null {\n this._trigger();\n if (!this._stream) {\n if (this._isComplete || this._isCancelled || this._isErrored) {\n return null;\n }\n this._stream = new TransformStream();\n }\n return this._stream.readable;\n }\n\n /**\n * Whether the stream has started being consumed but has not yet completed.\n */\n get isStarted(): boolean {\n this._trigger();\n return this._isStarted;\n }\n\n /**\n * The number of bytes loaded so far.\n */\n get bytesLoaded(): number {\n this._trigger();\n return this._bytesLoaded;\n }\n\n /**\n * The `performance.now()` timestamp at which the stream started being consumed.\n */\n get startTime(): number {\n this._trigger();\n return this._startTime;\n }\n\n /**\n * The `performance.now()` timestamp at which the stream finished being consumed.\n */\n get endTime(): number {\n this._trigger();\n return this._endTime;\n }\n\n /**\n * The `performance.now()` timestamp at which the last chunk of data was received.\n */\n get lastPacketTime(): number {\n this._trigger();\n return this._lastPacketTime;\n }\n\n /**\n * Whether the stream has finished being consumed.\n */\n get isComplete(): boolean {\n this._trigger();\n return this._isComplete;\n }\n\n /**\n * Whether the request was aborted before the stream finished being consumed.\n */\n get isCancelled(): boolean {\n this._trigger();\n return this._isCancelled;\n }\n\n /**\n * Whether an error occurred while consuming the stream.\n */\n get isErrored(): boolean {\n this._trigger();\n return this._isErrored;\n }\n\n /**\n * The error that occurred while consuming the stream, if any.\n */\n get error(): Error | null {\n this._trigger();\n return this._error;\n }\n\n /**\n * The number of milliseconds elapsed since the stream started being\n * consumed, using the last packet time (or end time, once complete)\n * as the endpoint.\n */\n get elapsedTime(): number {\n return (this.endTime || this.lastPacketTime) - this.startTime;\n }\n\n /**\n * The ratio (0 to 1) of {@link RequestLoadingState.bytesLoaded | bytesLoaded}\n * to {@link RequestLoadingState.sizeHint | sizeHint}, or `0` if no size hint is available.\n */\n get completedRatio(): number {\n return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;\n }\n\n /**\n * The inverse of {@link RequestLoadingState.completedRatio | completedRatio}.\n */\n get remainingRatio(): number {\n return 1 - this.completedRatio;\n }\n\n /**\n * The total number of milliseconds elapsed between\n * {@link RequestLoadingState.startTime | startTime} and {@link RequestLoadingState.endTime | endTime}.\n */\n get duration(): number {\n return this.endTime - this.startTime;\n }\n\n /**\n * The average download speed in bytes per second.\n */\n get speed(): number {\n // bytes per second\n return this.bytesLoaded / (this.elapsedTime / 1000);\n }\n\n constructor(future: Future<unknown>) {\n this._future = future;\n }\n\n /**\n * Aborts the underlying request.\n */\n abort = (): void => {\n this._future.abort();\n };\n}\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isPending', true);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isStarted', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isComplete', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isCancelled', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_isErrored', false);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_error', null);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_sizeHint', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_bytesLoaded', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_startTime', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_endTime', 0);\ndefineNonEnumerableSignal(RequestLoadingState.prototype, '_lastPacketTime', 0);\n\n/**\n * The state of a request in the \"pending\"\n * state. This is the default initial state.\n *\n * Extends the {@link PendingPromise} interface.\n *\n */\nexport interface PendingRequest extends PendingPromise {\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n loadingState: RequestLoadingState;\n request: null;\n response: null;\n}\n/**\n * The state of a request in the \"fulfilled\" state.\n * This is the state of a request that has resolved\n * successfully.\n *\n * Extends the {@link ResolvedPromise} interface.\n *\n */\nexport interface ResolvedRequest<RT> extends ResolvedPromise<RT> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n /**\n * A lazily created {@link RequestLoadingState} instance\n * which provides a number of reactive properties that can be used\n * to build UIs that respond to the progress of a request.\n */\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n/**\n * The state of a request in the \"rejected\" state.\n * This is the state of a request that has rejected\n * with an error.\n *\n * Extends the {@link RejectedPromise} interface.\n *\n */\nexport interface RejectedRequest<\n RT,\n E extends StructuredErrorDocument = StructuredErrorDocument,\n> extends RejectedPromise<E> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: false;\n\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n/**\n * The state of a request in the \"cancelled\" state.\n * This is the state of a promise that has been\n * cancelled.\n *\n */\nexport interface CancelledRequest<RT, E extends StructuredErrorDocument = StructuredErrorDocument> {\n /**\n * Retries the request with high (blocking) priority. This is the\n * same as having passed `cacheOptions.reload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n reload(): Future<RT>;\n /**\n * Retries the request with low (non-blocking) priority. This is the\n * same as having passed `cacheOptions.backgroundReload = true` on the original\n * request.\n *\n * This will not change the existing request's state. To subscribe\n * to the new request's state, use `getRequestState` on the returned\n * {@link Future}.\n *\n * ```ts\n * const future = state.reload();\n * const state = getRequestState(future);\n * ```\n *\n * It is safe to pass this around as an \"action\" or \"event\" handler\n * as its context is bound.\n */\n refresh(usePolicy?: boolean): Future<RT>;\n\n /**\n * The status of the request.\n *\n */\n status: 'cancelled';\n\n /**\n * Whether the request is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the request is pending.\n *\n */\n isLoading: false;\n\n /**\n * Whether the request has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the request has rejected\n * with an error.\n *\n */\n isError: true;\n\n /**\n * Once the request has resolved, this will\n * be the value the request resolved to.\n *\n */\n value: null;\n /**\n * Once the request has resolved, this will\n * be the value the request resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the request has rejected, this will\n * be the error the request rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: E;\n\n /**\n * Once the request has rejected, this will\n * be the error the request rejected with.\n *\n */\n reason: E;\n\n /**\n * Whether the request is cancelled.\n *\n */\n isCancelled: true;\n\n loadingState: RequestLoadingState;\n request: ImmutableRequestInfo<RT> | null;\n response: Response | ResponseInfo | null;\n}\n\nexport interface PrivateRequestState {\n _loadingState?: RequestLoadingState;\n _request: Future<unknown>;\n}\n\n/**\n * RequestState extends the concept of {@link PromiseState} to provide a reactive\n * wrapper for a request {@link Future} which allows you write declarative code\n * around a Future's control flow.\n *\n * It is useful in both Template and JavaScript contexts, allowing you\n * to quickly derive behaviors and data from pending, error and success\n * states.\n *\n * The key difference between a {@link Promise} and a Future is that Futures provide\n * access to a {@link ReadableStream | stream} of their content, the {@link RequestKey} of the request (if any)\n * as well as the ability to attempt to {@link Future.abort | abort} the request.\n *\n * ```ts\n * interface Future<T> extends Promise<T>> {\n * getStream(): Promise<ReadableStream>;\n * abort(): void;\n * lid: RequestKey | null;\n * }\n * ```\n *\n * These additional APIs allow us to craft even richer state experiences.\n *\n * To get the state of a request, use {@link getRequestState}.\n *\n * See also:\n * - {@link PendingRequest}\n * - {@link ResolvedRequest}\n * - {@link RejectedRequest}\n * - {@link CancelledRequest}\n *\n */\nexport type RequestState<RT = unknown, E extends StructuredErrorDocument = StructuredErrorDocument> =\n | PendingRequest\n | ResolvedRequest<RT>\n | RejectedRequest<RT, E>\n | CancelledRequest<RT, E>;\n\nconst RequestStateProto = {};\n\nfunction performRefresh<RT = unknown>(\n requester: RequestManager | Store,\n request: RequestInfo<RT>,\n isReload: boolean | null\n): Future<RT> {\n const req = Object.assign({}, request);\n const cacheOptions = Object.assign({}, req.cacheOptions);\n if (isReload) {\n // force direct to network\n cacheOptions.reload = true;\n } else if (isReload === false) {\n // delete reload to ensure we use backgroundReload / policy\n delete cacheOptions.reload;\n cacheOptions.backgroundReload = true;\n } else {\n // delete props to ensure we use the policy\n delete cacheOptions.backgroundReload;\n delete cacheOptions.reload;\n }\n req.cacheOptions = cacheOptions;\n return requester.request(req);\n}\n\n// TODO introduce a new mechanism for defining multiple properties\n// that share a common signal\ndefineSignal(RequestStateProto, 'reason', null);\ndefineSignal(RequestStateProto, 'value', null);\ndefineSignal(RequestStateProto, 'result', null);\ndefineSignal(RequestStateProto, 'error', null);\ndefineSignal(RequestStateProto, 'status', 'pending');\ndefineSignal(RequestStateProto, 'isPending', true);\ndefineSignal(RequestStateProto, 'isLoading', true);\ndefineSignal(RequestStateProto, 'isSuccess', false);\ndefineSignal(RequestStateProto, 'isError', false);\ndefineSignal(RequestStateProto, 'request', null);\ndefineSignal(RequestStateProto, 'response', null);\n\nObject.defineProperty(RequestStateProto, 'isCancelled', {\n get(this: RequestState): boolean {\n return this.isError && isAbortError(this.reason);\n },\n});\nObject.defineProperty(RequestStateProto, 'loadingState', {\n get(this: RequestState & PrivateRequestState): RequestLoadingState {\n if (!this._loadingState) {\n this._loadingState = new RequestLoadingState(this._request);\n }\n\n return this._loadingState;\n },\n});\n\nexport function createRequestState<RT, E>(future: Future<RT>): Readonly<RequestState<RT, StructuredErrorDocument<E>>> {\n const state = getPromiseResult(\n future as unknown as Awaitable<StructuredDataDocument<RT>, StructuredErrorDocument<E>>\n );\n const promiseState = Object.create(RequestStateProto) as RequestState<RT, StructuredErrorDocument<E>> &\n PrivateRequestState;\n promiseState._request = future;\n // @ts-expect-error - we still attach it for PendingState\n promiseState.reload = (): Future<RT> => {\n assert(\n `Cannot reload a request that is still pending. Await or abort the original request first.`,\n !promiseState.isPending\n );\n\n return performRefresh<RT>(future.requester, promiseState.request!, true);\n };\n\n // @ts-expect-error - we still attach it for PendingState\n promiseState.refresh = (usePolicy: boolean = false): Future<RT> => {\n assert(\n `Cannot refresh a request that is still pending. Await or abort the original request first.`,\n !promiseState.isPending\n );\n\n return performRefresh<RT>(future.requester, promiseState.request!, usePolicy === true ? null : false);\n };\n\n if (state) {\n if (state.isError) {\n promiseState.error = state.result;\n promiseState.reason = state.result;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = state.result.request as ImmutableRequestInfo<RT>;\n promiseState.response = state.result.response;\n } else {\n promiseState.result = state.result.content;\n promiseState.value = state.result.content;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = state.result.request as ImmutableRequestInfo<RT>;\n promiseState.response = state.result.response;\n }\n } else {\n void future.then(\n (result) => {\n setPromiseResult(future, { isError: false, result });\n promiseState.result = result.content;\n promiseState.value = result.content;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = result.request as ImmutableRequestInfo<RT>;\n promiseState.response = result.response;\n },\n (error: StructuredErrorDocument<E>) => {\n setPromiseResult(future, { isError: true, result: error });\n promiseState.error = error;\n promiseState.reason = error;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n promiseState.request = error.request as ImmutableRequestInfo<RT>;\n promiseState.response = error.response;\n }\n );\n }\n\n return promiseState;\n}\n\n/**\n * `getRequestState` can be used in both JavaScript and Template contexts.\n *\n * ```ts\n * import { getRequestState } from '@warp-drive/ember';\n *\n * const state = getRequestState(future);\n * ```\n *\n * For instance, we could write a getter on a component that updates whenever\n * the request state advances or the future changes, by combining the function\n * with the use of `@cached`\n *\n * ```ts\n * class Component {\n * @cached\n * get title() {\n * const state = getRequestState(this.args.request);\n * if (state.isPending) {\n * return 'loading...';\n * }\n * if (state.isError) { return null; }\n * return state.result.title;\n * }\n * }\n * ```\n *\n * Or in a template as a helper:\n *\n * ```gjs\n * import { getRequestState } from '@warp-drive/ember';\n *\n * <template>\n * {{#let (getRequestState @request) as |state|}}\n * {{#if state.isPending}}\n * <Spinner />\n * {{else if state.isError}}\n * <ErrorForm @error={{state.error}} />\n * {{else}}\n * <h1>{{state.result.title}}</h1>\n * {{/if}}\n * {{/let}}\n * </template>\n * ```\n *\n * If looking to use in a template, consider also the `<Request />` component\n * which offers a number of additional capabilities for requests *beyond* what\n * `RequestState` provides.\n *\n */\nexport function getRequestState<RT, E>(future: Future<RT>): Readonly<RequestState<RT, StructuredErrorDocument<E>>> {\n let state = RequestCache.get(future);\n\n if (!state) {\n state = createRequestState<RT, E>(future);\n RequestCache.set(future, state);\n }\n\n return state as Readonly<RequestState<RT, StructuredErrorDocument<E>>>;\n}\n","const deferred = /* @__PURE__ */ new WeakMap();\nfunction deferDecorator(proto, prop, desc) {\n let map = deferred.get(proto);\n if (!map) {\n map = /* @__PURE__ */ new Map();\n deferred.set(proto, map);\n }\n map.set(prop, desc);\n}\nfunction findDeferredDecorator(target, prop) {\n var _a;\n let cursor = target.prototype;\n while (cursor) {\n let desc = (_a = deferred.get(cursor)) == null ? void 0 : _a.get(prop);\n if (desc) {\n return desc;\n }\n cursor = Object.getPrototypeOf(cursor);\n }\n}\nfunction decorateFieldV1(target, prop, decorators, initializer) {\n return decorateFieldV2(target.prototype, prop, decorators, initializer);\n}\nfunction decorateFieldV2(prototype, prop, decorators, initializer) {\n let desc = {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n };\n if (initializer) {\n desc.initializer = initializer;\n }\n for (let decorator of decorators) {\n desc = decorator(prototype, prop, desc) || desc;\n }\n if (desc.initializer === void 0) {\n Object.defineProperty(prototype, prop, desc);\n } else {\n deferDecorator(prototype, prop, desc);\n }\n}\nfunction decorateMethodV1({ prototype }, prop, decorators) {\n return decorateMethodV2(prototype, prop, decorators);\n}\nfunction decorateMethodV2(prototype, prop, decorators) {\n const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);\n let desc = { ...origDesc };\n for (let decorator of decorators) {\n desc = decorator(prototype, prop, desc) || desc;\n }\n if (desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;\n desc.initializer = void 0;\n }\n Object.defineProperty(prototype, prop, desc);\n}\nfunction initializeDeferredDecorator(target, prop) {\n let desc = findDeferredDecorator(target.constructor, prop);\n if (desc) {\n Object.defineProperty(target, prop, {\n enumerable: desc.enumerable,\n configurable: desc.configurable,\n writable: desc.writable,\n value: desc.initializer ? desc.initializer.call(target) : void 0\n });\n }\n}\nfunction decorateClass(target, decorators) {\n return decorators.reduce(\n (accum, decorator) => decorator(accum) || accum,\n target\n );\n}\nfunction decoratePOJO(pojo, decorated) {\n for (let [type, prop, decorators] of decorated) {\n if (type === \"field\") {\n decoratePojoField(pojo, prop, decorators);\n } else {\n decorateMethodV2(pojo, prop, decorators);\n }\n }\n return pojo;\n}\nfunction decoratePojoField(pojo, prop, decorators) {\n let desc = {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: () => {\n var _a;\n return (_a = Object.getOwnPropertyDescriptor(pojo, prop)) == null ? void 0 : _a.value;\n }\n };\n for (let decorator of decorators) {\n desc = decorator(pojo, prop, desc) || desc;\n }\n if (desc.initializer) {\n desc.value = desc.initializer.call(pojo);\n delete desc.initializer;\n }\n Object.defineProperty(pojo, prop, desc);\n}\nconst runtime = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({\n __proto__: null,\n c: decorateClass,\n f: decorateFieldV1,\n g: decorateFieldV2,\n i: initializeDeferredDecorator,\n m: decorateMethodV1,\n n: decorateMethodV2,\n p: decoratePOJO\n}, Symbol.toStringTag, { value: \"Module\" }));\nexport {\n decorateFieldV1 as a,\n decorateFieldV2 as b,\n decorateMethodV1 as c,\n decorateClass as d,\n decorateMethodV2 as e,\n decoratePOJO as f,\n initializeDeferredDecorator as i,\n runtime as r\n};\n//# sourceMappingURL=runtime--fcdnjmJ.js.map\n","import { DEBUG } from '@warp-drive/build-config/env';\nimport { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { RequestManager, Store, StoreRequestInput } from '../index.ts';\nimport type { Future } from '../request.ts';\nimport type { RequestKey } from '../types/identifier.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\nimport type { PrivateRequestState, RequestState } from './request-state.ts';\nimport { getRequestState } from './request-state.ts';\n\n// default to 30 seconds unavailable before we refresh\nconst DEFAULT_DEADLINE = 30_000;\n/**\n * A symbol used to dispose of a {@link RequestSubscription} when the\n * component or context using it is torn down.\n */\nexport const DISPOSE = (Symbol.dispose || Symbol.for('dispose')) as unknown as '(symbol) dispose';\n\nfunction isNeverString(val: never): string {\n return val;\n}\n\n/**\n * The individual autorefresh strategies a {@link RequestSubscription}\n * may combine, see {@link AutorefreshBehaviorCombos}.\n */\nexport type AutorefreshBehaviorType = 'online' | 'interval' | 'invalid';\n\n/**\n * The value accepted by {@link SubscriptionArgs.autorefresh}: either a\n * boolean, a single {@link AutorefreshBehaviorType}, or a comma-separated\n * combination of up to three of them.\n */\nexport type AutorefreshBehaviorCombos =\n | boolean\n | AutorefreshBehaviorType\n | `${AutorefreshBehaviorType},${AutorefreshBehaviorType}`\n | `${AutorefreshBehaviorType},${AutorefreshBehaviorType},${AutorefreshBehaviorType}`;\n\n/**\n * Utilities to assist in recovering from the error.\n */\nexport interface RecoveryFeatures {\n /**\n * Whether the browser reports that the network is online.\n */\n isOnline: boolean;\n /**\n * Whether the browser reports that the tab is hidden.\n */\n isHidden: boolean;\n /**\n * Retries the request, reloading it from the server.\n */\n retry: () => Promise<void>;\n}\n\n/** @deprecated use {@link RecoveryFeatures} */\nexport type ErrorFeatures = RecoveryFeatures;\n\n/**\n * Utilities for keeping the request fresh\n */\nexport interface ContentFeatures<RT> {\n /**\n * Whether the browser reports that the network is online.\n */\n isOnline: boolean;\n /**\n * Whether the browser reports that the tab is hidden.\n */\n isHidden: boolean;\n /**\n * Whether the subscription is currently refreshing the request.\n */\n isRefreshing: boolean;\n /**\n * Refreshes the request, updating it in the background.\n */\n refresh: () => Promise<void>;\n /**\n * Retries the request, reloading it from the server.\n */\n reload: () => Promise<void>;\n /**\n * Aborts the in-flight refresh/reload request, if any.\n */\n abort?: () => void;\n /**\n * The most recent refresh/reload request that was made, if any.\n */\n latestRequest?: Future<RT>;\n}\n\n/**\n * The args accepted by the `<Request />` component.\n */\nexport interface RequestArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * The {@link RequestSubscription} instance backing the component, if any.\n */\n subscription?: RequestSubscription<RT, E>;\n\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n/**\n * The args accepted by a {@link RequestSubscription}.\n */\n// oxlint-disable-next-line no-unused-vars\nexport interface SubscriptionArgs<RT, E> {\n /**\n * The request to monitor. This should be a `Future` instance returned\n * by either the `store.request` or `store.requestManager.request` methods.\n *\n */\n request?: Future<RT> | undefined | null;\n\n /**\n * A query to use for the request. This should be an object that can be\n * passed to `store.request`. Use this in place of `@request` if you would\n * like the component to also initiate the request.\n *\n */\n query?: StoreRequestInput<RT> | undefined | null;\n\n /**\n * The autorefresh behavior for the request. This can be a boolean, or any\n * combination of the following values: `'online'`, `'interval'`, `'invalid'`.\n *\n * - `'online'`: Refresh the request when the browser comes back online\n * - `'interval'`: Refresh the request at a specified interval\n * - `'invalid'`: Refresh the request when the store emits an invalidation\n *\n * If `true`, this is equivalent to `'online,invalid'`.\n *\n * Defaults to `false`.\n *\n */\n autorefresh?: AutorefreshBehaviorCombos;\n\n /**\n * The number of milliseconds to wait before refreshing the request when the\n * browser comes back online or the network becomes available.\n *\n * This also controls the interval at which the request will be refreshed if\n * the `interval` autorefresh type is enabled.\n *\n * Defaults to `30_000` (30 seconds).\n *\n */\n autorefreshThreshold?: number;\n\n /**\n * The behavior of the request initiated by autorefresh. This can be one of\n * the following values:\n *\n * - `'refresh'`: Refresh the request in the background\n * - `'reload'`: Force a reload of the request\n * - `'policy'` (**default**): Let the store's configured CachePolicy decide whether to\n * reload, refresh, or do nothing.\n *\n * Defaults to `'policy'`.\n *\n */\n autorefreshBehavior?: 'refresh' | 'reload' | 'policy';\n}\n\nexport interface RequestComponentArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n// oxlint-disable-next-line no-unused-vars\nexport interface RequestSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\n/**\n * A reactive class\n *\n * @hideconstructor\n */\nexport class RequestSubscription<RT, E> {\n /**\n * Whether the browser reports that the network is online.\n */\n declare isOnline: boolean;\n\n /**\n * Whether the browser reports that the tab is hidden.\n */\n declare isHidden: boolean;\n\n /**\n * Whether the component is currently refreshing the request.\n */\n declare isRefreshing: boolean;\n\n /**\n * The most recent blocking request that was made, typically\n * the result of a reload.\n *\n * This will never be the original request passed as an arg to\n * the component.\n *\n * @internal\n */\n declare private _localRequest: Future<RT> | undefined;\n\n /**\n * The most recent request that was made, typically due to either a\n * reload or a refresh.\n *\n * This will never be the original request passed as an arg to\n * the component.\n *\n * @internal\n */\n declare private _latestRequest: Future<RT> | undefined;\n\n /**\n * The time at which the network was reported as offline.\n *\n * @internal\n */\n declare private _unavailableStart: number | null;\n /** @internal */\n declare private _intervalStart: number | null;\n /** @internal */\n declare private _nextInterval: number | null;\n /** @internal */\n declare private _invalidated: boolean;\n /** @internal */\n declare private _isUpdating: boolean;\n /** @internal */\n declare private isDestroyed: boolean;\n\n /**\n * The event listener for network status changes,\n * cached to use the reference for removal.\n *\n * @internal\n */\n declare private _onlineChanged: (event: Event) => void;\n\n /**\n * The event listener for visibility status changes,\n * cached to use the reference for removal.\n *\n * @internal\n */\n declare private _backgroundChanged: (event: Event) => void;\n\n /**\n * The last request passed as an arg to the component,\n * cached for comparison.\n *\n * @internal\n */\n declare private _originalRequest: Future<RT> | undefined | null;\n\n /**\n * The last query passed as an arg to the component,\n * cached for comparison.\n *\n * @internal\n */\n declare private _originalQuery: StoreRequestInput<RT> | undefined | null;\n /** @internal */\n declare private _subscription: object | null;\n /** @internal */\n declare private _subscribedTo: object | null;\n /** @internal */\n declare private _args: SubscriptionArgs<RT, E>;\n /**\n * The Store this subscription subscribes to or the RequestManager\n * which issues this request.\n */\n declare store: Store | RequestManager;\n /**\n * The Store or RequestManager that the last subscription is attached to.\n *\n * This differs from 'store' because a <Request /> may be passed a\n * request originating from a different store than the <Request />\n * component would use if it were to issue the request itself.\n *\n * @internal\n */\n private _requester: Store | RequestManager | null;\n\n constructor(store: Store | RequestManager, args: SubscriptionArgs<RT, E>) {\n this._args = args;\n this.store = store;\n this._subscribedTo = null;\n this._subscription = null;\n this._intervalStart = null;\n this._invalidated = false;\n this._nextInterval = null;\n this._requester = null;\n this.isDestroyed = false;\n this[DISPOSE] = _DISPOSE;\n\n this._installListeners();\n void this._beginPolling();\n }\n\n /**\n * @internal\n */\n private async _beginPolling() {\n // await the initial request\n try {\n if (!this.isIdle) {\n await this.request;\n }\n } catch {\n // ignore errors here, we just want to wait for the request to finish\n } finally {\n if (!this.isDestroyed) {\n void this._scheduleInterval();\n }\n }\n }\n\n /**\n * Whether neither a `request` nor a `query` arg was provided, and so\n * this subscription has nothing to fetch or monitor.\n */\n @memoized\n get isIdle(): boolean {\n const { request, query } = this._args;\n\n return Boolean(!request && !query);\n }\n\n /**\n * The set of {@link AutorefreshBehaviorType}s this subscription is\n * configured to autorefresh for, derived from {@link SubscriptionArgs.autorefresh}.\n */\n @memoized\n get autorefreshTypes(): Set<AutorefreshBehaviorType> {\n const { autorefresh } = this._args;\n let types: AutorefreshBehaviorType[];\n\n if (autorefresh === true) {\n types = ['online', 'invalid'];\n } else if (typeof autorefresh === 'string') {\n types = autorefresh.split(',') as AutorefreshBehaviorType[];\n } else {\n types = [];\n }\n\n return new Set(types);\n }\n\n // we only run this function on component creation\n // and when an update is triggered, so it does not\n // react to changes in the autorefreshThreshold\n // or autorefresh args.\n //\n // if we need to react to those changes, we can\n // use a modifier or internal component or some\n // such to trigger a re-run of this function.\n /** @internal */\n private async _scheduleInterval() {\n const { autorefreshThreshold } = this._args;\n const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;\n if (\n // dont schedule in SSR\n typeof window === 'undefined' ||\n // dont schedule without a threshold\n !hasValidThreshold ||\n // dont schedule if we weren't told to\n !this.autorefreshTypes.has('interval') ||\n // dont schedule if we're already scheduled\n this._intervalStart !== null\n ) {\n return;\n }\n\n // if we have a current request, wait for it to finish\n // before scheduling the next one\n if (this._latestRequest) {\n try {\n await this._latestRequest;\n } catch {\n // ignore errors here, we just want to wait for the request to finish\n }\n\n if (this.isDestroyed) {\n return;\n }\n }\n\n // setup the next interval\n this._intervalStart = Date.now();\n this._nextInterval = setTimeout(() => {\n this._maybeUpdate();\n }, autorefreshThreshold);\n }\n\n /** @internal */\n private _clearInterval() {\n if (this._nextInterval) {\n clearTimeout(this._nextInterval);\n this._intervalStart = null;\n }\n }\n /**\n * @internal\n */\n private _updateSubscriptions() {\n if (this.isIdle) {\n return;\n }\n const requestId = this._request.lid;\n\n // if we're already subscribed to this request, we don't need to do anything\n if (this._subscribedTo === requestId) {\n return;\n }\n\n // if we're subscribed to a different request, we need to unsubscribe\n this._removeSubscriptions();\n\n // if we have a request, we need to subscribe to it\n const store = this._getRequester();\n this._requester = store;\n if (requestId && isStore(store)) {\n this._subscribedTo = requestId;\n\n this._subscription = store.notifications.subscribe(\n requestId,\n (_id: RequestKey, op: 'invalidated' | 'state' | 'added' | 'updated' | 'removed') => {\n // ignore subscription events that occur while our own component's request\n // is occurring\n if (this._isUpdating) {\n return;\n }\n switch (op) {\n case 'invalidated': {\n // if we're subscribed to invalidations, we need to update\n if (this.autorefreshTypes.has('invalid')) {\n this._invalidated = true;\n this._maybeUpdate();\n }\n break;\n }\n case 'state': {\n const latest = store.requestManager._deduped.get(requestId);\n const priority = latest?.priority;\n const state = this.reqState;\n if (!priority) {\n // if there is no priority, we have completed whatever request\n // was occurring and so we are no longer refreshing (if we were)\n this.isRefreshing = false;\n } else if (priority.blocking && !state.isLoading) {\n // if we are blocking, there is an active request for this identity\n // that MUST be fulfilled from network (not cache).\n // Thus this is not \"refreshing\" because we should clear out and\n // block on this request.\n //\n // we receive state notifications when either a request initiates\n // or completes.\n //\n // In the completes case: we may receive the state notification\n // slightly before the request is finalized because the NotificationManager\n // may sync flush it (and thus deliver it before the microtask completes)\n //\n // In the initiates case: we aren't supposed to receive one unless there\n // is no other request in flight for this identity.\n //\n // However, there is a race condition here where the completed\n // notification can trigger an update that generates a new request\n // thus giving us an initiated notification before the older request\n // finalizes.\n //\n // When this occurs, if the triggered update happens to have caused\n // a new request to be made for the same identity AND that request\n // is the one passed into this component as the @request arg, then\n // getRequestState will return the state of the new request.\n // We can detect this by checking if the request state is \"loading\"\n // as outside of this case we would have a completed request.\n //\n // That is the reason for the `&& !state.isLoading` check above.\n\n // TODO should we just treat this as refreshing?\n this.isRefreshing = false;\n this._maybeUpdate('policy', true);\n } else {\n this.isRefreshing = true;\n }\n }\n }\n }\n );\n }\n }\n\n /**\n * @internal\n */\n private _removeSubscriptions() {\n const store = this._requester;\n if (this._subscription && store && isStore(store)) {\n store.notifications.unsubscribe(this._subscription);\n this._subscribedTo = null;\n this._subscription = null;\n this._requester = null;\n }\n }\n\n /**\n * Install the event listeners for network and visibility changes.\n *\n * This is only done in environments that provide a fully-featured global\n * `window` and/or `document`. Some non-DOM environments (e.g. React Native,\n * SSR/Node, workers) may provide a `window` global without the APIs we\n * rely on here (or no `window`/`document` at all), in which case we skip\n * attaching the corresponding listeners rather than throwing.\n *\n * @internal\n */\n private _installListeners() {\n const hasWindow = typeof window !== 'undefined';\n const hasDocument = typeof document !== 'undefined';\n const hasWindowEvents = hasWindow && typeof window.addEventListener === 'function';\n const hasDocumentEvents = hasDocument && typeof document.addEventListener === 'function';\n\n this.isOnline = hasWindow && typeof window.navigator?.onLine === 'boolean' ? window.navigator.onLine : true;\n this._unavailableStart = this.isOnline ? null : Date.now();\n this.isHidden =\n hasDocument && typeof document.visibilityState === 'string' && document.visibilityState === 'hidden';\n\n if (hasWindowEvents) {\n this._onlineChanged = (event: Event) => {\n this.isOnline = event.type === 'online';\n if (event.type === 'offline' && this._unavailableStart === null) {\n this._unavailableStart = Date.now();\n }\n this._maybeUpdate();\n };\n\n window.addEventListener('online', this._onlineChanged, { passive: true, capture: true });\n window.addEventListener('offline', this._onlineChanged, { passive: true, capture: true });\n }\n\n if (hasDocumentEvents) {\n this._backgroundChanged = () => {\n const isHidden = document.visibilityState === 'hidden';\n this.isHidden = isHidden;\n\n if (isHidden && this._unavailableStart === null) {\n this._unavailableStart = Date.now();\n }\n\n this._maybeUpdate();\n };\n\n document.addEventListener('visibilitychange', this._backgroundChanged, { passive: true, capture: true });\n }\n }\n\n /**\n * If the network is online and the tab is visible, either reload or refresh the request\n * based on the component's configuration and the requested update mode.\n *\n * Valid modes are:\n *\n * - `'reload'`: Force a reload of the request.\n * - `'refresh'`: Refresh the request in the background.\n * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.\n * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.\n *\n * @internal\n */\n private _maybeUpdate(mode?: 'reload' | 'refresh' | 'policy' | '_invalidated', silent?: boolean): void {\n if (this.isIdle) {\n return;\n }\n\n const { reqState } = this;\n if (reqState.isPending) {\n return;\n }\n\n const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));\n\n if (!canAttempt) {\n if (!silent && mode && mode !== '_invalidated') {\n throw new Error(`Reload not available: the network is not online or the tab is hidden`);\n }\n\n return;\n }\n\n const { autorefreshTypes } = this;\n let shouldAttempt = this._invalidated || Boolean(mode);\n\n if (!shouldAttempt && autorefreshTypes.has('online')) {\n const { _unavailableStart } = this;\n const { autorefreshThreshold } = this._args;\n const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;\n shouldAttempt = Boolean(_unavailableStart && Date.now() - _unavailableStart > deadline);\n }\n\n if (!shouldAttempt && autorefreshTypes.has('interval')) {\n const { _intervalStart } = this;\n const { autorefreshThreshold } = this._args;\n\n if (_intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {\n shouldAttempt = Boolean(Date.now() - _intervalStart >= autorefreshThreshold);\n }\n }\n\n this._unavailableStart = null;\n this._invalidated = false;\n\n if (shouldAttempt) {\n this._clearInterval();\n this._isUpdating = true;\n\n const realMode = mode === '_invalidated' ? null : mode;\n const val = realMode ?? this._args.autorefreshBehavior ?? 'policy';\n\n // if the future was generated by an older store version, it may not have\n // a requester set. In this case we append it to ensure that reload and\n // refresh will work appropriately.\n const requester = this._getRequester();\n if (!(reqState as unknown as PrivateRequestState)._request.requester) {\n (reqState as unknown as PrivateRequestState)._request.requester = requester;\n }\n\n switch (val) {\n case 'reload':\n this._latestRequest = reqState.reload();\n break;\n case 'refresh':\n this._latestRequest = reqState.refresh();\n break;\n case 'policy':\n this._latestRequest = reqState.refresh(true);\n break;\n default:\n assert(`Invalid ${mode ? 'update mode' : '@autorefreshBehavior'} for <Request />: ${isNeverString(val)}`);\n }\n\n if (val !== 'refresh') {\n this._localRequest = this._latestRequest;\n }\n\n void this._scheduleInterval();\n void this._latestRequest.finally(() => {\n this._isUpdating = false;\n });\n } else {\n // TODO probably want this\n // void this.scheduleInterval();\n }\n }\n\n /**\n * @internal\n */\n private _getRequester(): Store | RequestManager {\n // Note: we check for the requester's presence\n // as well as the request's presence because we may\n // be subscribed to a request issued by a store from an older\n // version of the library that didn't yet set requester.\n if (this._args.request?.requester) {\n return this._args.request.requester;\n }\n\n return this.store;\n }\n\n /**\n * Retry the request, reloading it from the server.\n */\n retry = async (): Promise<void> => {\n this._maybeUpdate('reload');\n await this._localRequest;\n };\n\n /**\n * Refresh the request, updating it in the background.\n */\n refresh = async (): Promise<void> => {\n this._maybeUpdate('refresh');\n await this._latestRequest;\n };\n\n /**\n * features to yield to the error slot of a component\n */\n @memoized\n get errorFeatures(): RecoveryFeatures {\n return {\n isHidden: this.isHidden,\n isOnline: this.isOnline,\n retry: this.retry,\n };\n }\n\n /**\n * features to yield to the content slot of a component\n */\n @memoized\n get contentFeatures(): ContentFeatures<RT> {\n const feat: ContentFeatures<RT> = {\n isHidden: this.isHidden,\n isOnline: this.isOnline,\n reload: this.retry,\n refresh: this.refresh,\n isRefreshing: this.isRefreshing,\n latestRequest: this._latestRequest,\n };\n\n if (feat.isRefreshing) {\n feat.abort = () => {\n this._latestRequest?.abort();\n };\n }\n\n return feat;\n }\n\n /**\n * @internal\n */\n @memoized\n get _request(): Future<RT> {\n const { request, query } = this._args;\n assert(`Cannot use both @request and @query args with the <Request> component`, !request || !query);\n const { _localRequest, _originalRequest, _originalQuery } = this;\n const isOriginalRequest = request === _originalRequest && query === _originalQuery;\n\n if (_localRequest && isOriginalRequest) {\n return _localRequest;\n }\n\n // update state checks for the next time\n this._originalQuery = query;\n this._originalRequest = request;\n\n if (request) {\n return request;\n }\n assert(`You must provide either @request or an @query arg with the <Request> component`, query);\n return (this.store as Store).request(query);\n }\n\n /**\n * The {@link Future} this subscription is currently monitoring, and\n * (re-)subscribes to notifications for as a side effect of access.\n */\n @memoized\n get request(): Future<RT> {\n if (DEBUG) {\n try {\n const request = this._request;\n this._updateSubscriptions();\n return request;\n } catch (e) {\n // oxlint-disable-next-line no-console\n console.log(e);\n throw new Error(`Unable to initialize the request`, { cause: e });\n }\n } else {\n const request = this._request;\n this._updateSubscriptions();\n return request;\n }\n }\n\n /**\n * The {@link RequestState} for {@link RequestSubscription.request | request}.\n */\n get reqState(): RequestState<RT, StructuredErrorDocument<E>> {\n return getRequestState<RT, E>(this.request);\n }\n\n /**\n * The resolved content of the request, once it has succeeded.\n */\n get result() {\n return this.reqState.result as RT;\n }\n}\n\ndefineSignal(RequestSubscription.prototype, 'isOnline', true);\ndefineSignal(RequestSubscription.prototype, 'isHidden', false);\ndefineSignal(RequestSubscription.prototype, 'isRefreshing', false);\ndefineSignal(RequestSubscription.prototype, '_localRequest', undefined);\ndefineSignal(RequestSubscription.prototype, '_latestRequest', undefined);\n\nfunction isStore(store: Store | RequestManager): store is Store {\n return 'requestManager' in store;\n}\n\n/**\n * Creates a {@link RequestSubscription}, the reactive class powering the\n * `<Request />` component's autorefresh, retry, and refresh behaviors.\n */\nexport function createRequestSubscription<RT, E>(\n store: Store | RequestManager,\n args: SubscriptionArgs<RT, E>\n): RequestSubscription<RT, E> {\n return new RequestSubscription(store, args);\n}\n\ninterface PrivateRequestSubscription {\n isDestroyed: boolean;\n _removeSubscriptions(): void;\n _clearInterval(): void;\n _onlineChanged: () => void;\n _backgroundChanged: () => void;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivateRequestSubscription {\n return sub as PrivateRequestSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: RequestSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n self._removeSubscriptions();\n self._clearInterval();\n\n if (self._onlineChanged && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {\n window.removeEventListener('online', self._onlineChanged, { passive: true, capture: true } as unknown as boolean);\n window.removeEventListener('offline', self._onlineChanged, {\n passive: true,\n capture: true,\n } as unknown as boolean);\n }\n\n if (\n self._backgroundChanged &&\n typeof document !== 'undefined' &&\n typeof document.removeEventListener === 'function'\n ) {\n document.removeEventListener('visibilitychange', self._backgroundChanged, {\n passive: true,\n capture: true,\n } as unknown as boolean);\n }\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport type { Link } from '../types/spec/json-api-raw.ts';\nimport type { PaginationCache } from './pagination-cache.ts';\nimport { memoized, signal } from './reactivity/signal';\nimport type { RequestState } from './request-state.ts';\nimport { getRequestState } from './request-state.ts';\n\nconst { abs } = Math;\n\n/**\n * Extracts the `data` member of a document type, or the document type itself\n * when it has no `data` member.\n */\nexport type ContentData<RT> = RT extends { data: infer D } ? D : RT;\n\n/**\n * The element type of a collection document's `data` array — the item type an\n * infinite view renders. See {@link PaginationState.data}.\n */\nexport type ContentItem<RT> = ContentData<RT> extends readonly (infer I)[] ? I : ContentData<RT>;\n\n/** @internal */\nexport function 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\ntype Links = {\n prev?: string | null;\n next?: string | null;\n first?: string | null;\n last?: string | null;\n};\n\n/**\n * A single page of a paginated collection: its request, its loaded document, and\n * its links to neighboring pages in the shared page graph.\n *\n * Pages are yielded to consumers as `Readonly<PageCache>` — through\n * {@link PaginationState.activePage}, {@link PaginationState.pages}, and the\n * relational getters below — to read a page's data and request status when\n * building pagination UIs:\n *\n * ```ts\n * const page = paginationState.activePage;\n *\n * if (page?.isLoading) {\n * // show a spinner\n * } else if (page?.isError) {\n * // show page.reason\n * } else {\n * // render page.data\n * }\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PageCache<RT = unknown, E = unknown> {\n /** @internal */\n declare manager: PaginationCache<RT, E>;\n\n /**\n * The request that loaded (or is loading) this page, or `null` if the page is\n * known from links but was never requested. Wrap it in a `<Request>` component\n * to render the page's loading, error, and content states.\n */\n @signal declare request: Future<RT> | null;\n\n /** @internal */\n @signal declare state: Readonly<RequestState<RT, StructuredErrorDocument<E>>> | null;\n\n /** The `self` link of this page — the URL that identifies it in the collection. */\n @signal declare selfLink: string | null;\n\n /** The `prev` link of this page, or `null` at the start of the collection. */\n @signal declare prevLink: string | null;\n\n /** The `next` link of this page, or `null` at the end of the collection. */\n @signal declare nextLink: string | null;\n\n /** The `first` link of the collection, when the response exposed one. */\n @signal declare firstLink: string | null;\n\n /** The `last` link of the collection, when the response exposed one. */\n @signal declare lastLink: string | null;\n\n /**\n * The 1-based page number, or `0` when unknown (for example cursor-based\n * pagination, where pages have no ordinal position). Derived from the\n * collection's {@link PageHints}.\n */\n @signal declare pageNumber: number;\n\n /** @internal */\n @signal declare before: Readonly<PageCache<RT, E>> | null;\n /** @internal */\n @signal declare after: Readonly<PageCache<RT, E>> | null;\n\n constructor(manager: PaginationCache<RT, E>, url: string) {\n this.manager = manager;\n this.pageNumber = 0;\n this.selfLink = url;\n }\n\n /**\n * The document this page's request resolved to, or `null` while it has not\n * resolved.\n */\n @memoized\n get value(): RT | null {\n return this.state?.value as RT | null;\n }\n\n /**\n * The `data` member of the loaded document — the page's items — or `null`\n * while the page has not loaded.\n */\n @memoized\n get data(): ContentData<RT> | null {\n return ((this.value as { data?: unknown } | null)?.data ?? null) as ContentData<RT> | null;\n }\n\n /**\n * Whether a request has ever been issued for this page. `false` for pages that\n * are known only from links.\n */\n @memoized\n get isRequested(): boolean {\n return Boolean(this.state);\n }\n\n /** Whether this page's request has settled (successfully or with an error). */\n @memoized\n get isLoaded(): boolean {\n return this.isSuccess || this.isError;\n }\n\n /** Whether this page's request is currently in flight. */\n @memoized\n get isLoading(): boolean {\n return Boolean(this.state?.isLoading);\n }\n\n /** Whether this page's request resolved successfully. */\n @memoized\n get isSuccess(): boolean {\n return Boolean(this.state?.isSuccess);\n }\n\n /** Whether this page's request was cancelled (aborted). */\n @memoized\n get isCancelled(): boolean {\n return Boolean(this.state?.isCancelled);\n }\n\n /** Whether this page's request rejected with an error. */\n @memoized\n get isError(): boolean {\n return Boolean(this.state?.isError);\n }\n\n /** The error this page's request rejected with, or `null` if it did not reject. */\n @memoized\n get reason(): StructuredErrorDocument<E> | null {\n return this.state?.reason ?? null;\n }\n\n /** The page at this page's `prev` link, or `null` at the start of the collection. */\n @memoized\n get prev(): PageCache<RT, E> | null {\n const url = this.prevLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The page at this page's `next` link, or `null` at the end of the collection. */\n @memoized\n get next(): PageCache<RT, E> | null {\n const url = this.nextLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The first page of the collection, when the response exposed a `first` link. */\n @memoized\n get first(): PageCache<RT, E> | null {\n const url = this.firstLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** The last page of the collection, when the response exposed a `last` link. */\n @memoized\n get last(): PageCache<RT, E> | null {\n const url = this.lastLink;\n return url ? this.manager.getPageCache(url) : null;\n }\n\n /** @internal */\n @memoized\n get isLinked(): boolean {\n return Boolean(this.before || this.after);\n }\n\n /** @internal */\n async load(request: Future<RT>): Promise<ReactiveDocument<unknown> | null> {\n try {\n this.request = request;\n this.state = getRequestState<RT, E>(this.request);\n const value = await this.request;\n const content = value.content as ReactiveDocument<unknown>;\n\n const self = getHref(content?.links?.self);\n const first = getHref(content?.links?.first);\n const last = getHref(content?.links?.last);\n const next = getHref(content?.links?.next);\n const prev = getHref(content?.links?.prev);\n\n assert('Expected the page to have a self link', self);\n\n // The page number is a hint. When the response exposes it, rely on it. When\n // absent (`0`, e.g. cursor pagination), keep whatever relative number a\n // neighbor already assigned via `setPageNumber` rather than clobbering it.\n const pageNumber = this.getPageNumber(content);\n if (pageNumber) {\n this.pageNumber = pageNumber;\n }\n\n const firstPage = first ? this.manager.getPageCache(first) : null;\n const lastPage = last ? this.manager.getPageCache(last) : null;\n const prevPage = prev ? this.manager.getPageCache(prev) : null;\n const nextPage = next ? this.manager.getPageCache(next) : null;\n\n if (firstPage) {\n this.firstLink = first;\n firstPage.setPageNumber(1);\n if (!firstPage.after) {\n firstPage.updateLinkage({ after: this });\n }\n }\n\n if (lastPage) {\n this.lastLink = last;\n lastPage.setPageNumber(this.manager.totalPages);\n if (!lastPage.before) {\n lastPage.updateLinkage({ before: this });\n }\n }\n\n if (nextPage) {\n this.nextLink = next;\n nextPage.setPageNumber(this.pageNumber + 1);\n nextPage.updateLinks({ prev: self });\n }\n\n if (prevPage) {\n this.prevLink = prev;\n prevPage.setPageNumber(this.pageNumber - 1);\n prevPage.updateLinks({ next: self });\n }\n\n if (this.isLinked) {\n if (prevPage) prevPage.updateLinkage({ after: this });\n if (nextPage) nextPage.updateLinkage({ before: this });\n } else if (prevPage?.isLinked) {\n this.updateLinkage({ before: prevPage });\n if (nextPage) nextPage.updateLinkage({ before: this });\n } else if (nextPage?.isLinked) {\n this.updateLinkage({ after: nextPage });\n if (prevPage) prevPage.updateLinkage({ after: this });\n } else if ((prevPage || nextPage) && (firstPage || lastPage)) {\n this.lookupLinkage(firstPage, lastPage);\n } else if (prevPage || nextPage) {\n this.updateLinkage({ before: prevPage, after: nextPage });\n }\n\n return content;\n } catch {\n // no-op\n }\n\n return null;\n }\n\n /** @internal */\n updateLinkage({ before, after }: { before?: PageCache<RT, E> | null; after?: PageCache<RT, E> | null }): void {\n assert('Expected at least one of before or after page states to link to this page', before || after);\n\n const leftSide = before ?? after?.before;\n const rightSide = after ?? before?.after;\n\n if (leftSide && leftSide !== this) {\n leftSide.setAfter(this);\n this.setBefore(leftSide);\n }\n\n if (rightSide && rightSide !== this) {\n rightSide.setBefore(this);\n this.setAfter(rightSide);\n }\n }\n\n /** @internal */\n lookupLinkage(firstPage: PageCache<RT, E> | null, lastPage: PageCache<RT, E> | null): void {\n assert('Expected at least one of firstPage or lastPage to lookup linkage against', firstPage || lastPage);\n\n if (firstPage && lastPage) {\n const firstPageDelta = abs(this.pageNumber - firstPage.pageNumber);\n const lastPageDelta = abs(this.pageNumber - lastPage.pageNumber);\n\n if (firstPageDelta <= lastPageDelta) {\n this.lookupLinkageForward(firstPage);\n } else {\n this.lookupLinkageBackwards(lastPage);\n }\n } else if (firstPage) {\n this.lookupLinkageForward(firstPage);\n } else if (lastPage) {\n this.lookupLinkageBackwards(lastPage);\n }\n }\n\n /** @internal */\n lookupLinkageForward(page: PageCache<RT, E>): void {\n while (page.after && page.after.pageNumber < this.pageNumber) {\n page = page.after;\n }\n\n this.updateLinkage({ before: page });\n }\n\n /** @internal */\n lookupLinkageBackwards(page: PageCache<RT, E>): void {\n while (page.before && page.before.pageNumber > this.pageNumber) {\n page = page.before;\n }\n\n this.updateLinkage({ after: page });\n }\n\n /** @internal */\n setBefore(page: Readonly<PageCache<RT, E>> | null): void {\n assert('Expected the before page to be a different page, got the same page', page !== this);\n this.before = page;\n }\n\n /** @internal */\n setAfter(page: Readonly<PageCache<RT, E>> | null): void {\n assert('Expected the after page to be a different page, got the same page', page !== this);\n this.after = page;\n }\n\n /** @internal */\n getPageNumber(document: ReactiveDocument<unknown>): number {\n return this.manager.readPageHints(document).currentPage;\n }\n\n /** @internal */\n updateLinks = ({ prev, next, first, last }: Links): void => {\n if (prev) {\n this.prevLink = prev;\n }\n if (next) {\n this.nextLink = next;\n }\n if (first) {\n this.firstLink = first;\n }\n if (last) {\n this.lastLink = last;\n }\n };\n\n /** @internal */\n setPageNumber = (pageNumber: number): void => {\n if (!this.pageNumber) {\n this.pageNumber = pageNumber;\n }\n };\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { ContentItem } from './page-cache.ts';\nimport { PageCache } from './page-cache.ts';\nimport { memoized, signal } from './reactivity/signal';\n\nconst PaginationCacheMap = new Map<string, PaginationCache>();\n\n/**\n * A hint function for extracting the `currentPage` and `totalPages` from a loaded\n * document, for when the response does not expose these values through the\n * default `meta` locations. Provided by the consumer via `<Paginate />`'s\n * `@pageHints` arg:\n *\n * ```gts\n * <Paginate @pageHints={{...}} />\n * ```\n *\n * Since these values are attached to the shared {@link PaginationCache}, the hint is\n * a property of the *collection*, not the component. Every `<Paginate />` sharing a\n * collection must provide the same function reference — define it once at module\n * scope and import it everywhere.\n *\n * @since 5.9.0\n * @public\n */\nexport interface PageHints {\n (document: ReactiveDocument<unknown>): { currentPage: number; totalPages: number };\n}\n\n/**\n * The default {@link PageHints}. Reads `currentPage`/`page` and `totalPages` from the\n * document `meta`, matching the behavior used before `pageHints` was configurable.\n * Used whenever the consumer does not provide a `pageHints` function.\n *\n * @since 5.9.0\n * @public\n */\nexport const defaultPageHints: PageHints = (document) => {\n const currentPage = (document.meta?.page ?? document.meta?.currentPage ?? 0) as number;\n const totalPages = (document.meta?.totalPages ?? 0) as number;\n return { currentPage, totalPages };\n};\n\n/**\n * The global, shared cache for a paginated collection. Keyed by the collection's\n * `first` (or `self`) link, so that multiple components paging the same collection\n * share loaded pages, the page graph, and `totalPages`.\n *\n * This holds only shared, request-agnostic data. Per-component state (the active\n * page, navigation) lives on {@link PaginationState}, which is the API consumers\n * interact with — the cache itself is plumbing shared between the pagination\n * classes.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationCache<RT = unknown, E = unknown> {\n /**\n * The cache key this collection is stored under in the module-level cache —\n * its `first` (or `self`) link. This is the collection's identity: two\n * requests whose documents resolve to the same key are pages of the same\n * collection.\n *\n * @internal\n */\n declare readonly key: string;\n\n /** @internal */\n @signal declare firstPage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The total number of pages in the collection, or `0` when unknown. Consumers\n * should read this via {@link PaginationState.totalPages}.\n */\n @signal declare totalPages: number;\n /**\n * Whether this collection has server-known page numbers. Stays `false` for\n * cursor-based collections (opaque `prev`/`next`, no index/total), which drives\n * whether numbered links are produced. Set once a {@link PageHints} yields a real\n * `currentPage`/`totalPages`.\n *\n * @internal\n */\n @signal declare isNumbered: boolean;\n /** @internal */\n declare private pagesCache: Map<string, PageCache>;\n /** @internal */\n private pageHints: PageHints = defaultPageHints;\n\n constructor(key: string) {\n this.key = key;\n this.pagesCache = new Map<string, PageCache>();\n this.firstPage = null;\n this.totalPages = 0;\n this.isNumbered = false;\n }\n\n /**\n * Installs the consumer-provided {@link PageHints} onto the shared cache. The first\n * explicit hint wins; passing `undefined` (no hint) is a no-op that preserves the\n * default. In dev, asserts that components sharing a collection do not provide\n * diverging hint functions.\n *\n * @internal\n */\n installPageHints(pageHints: PageHints | undefined): void {\n if (!pageHints) {\n return;\n }\n if (this.pageHints === defaultPageHints) {\n this.pageHints = pageHints;\n return;\n }\n assert(\n 'Received diverging `pageHints` functions for the same paginated collection. Provide the same function reference to every <Paginate /> sharing a collection (define it once at module scope).',\n this.pageHints === pageHints\n );\n }\n\n /**\n * Runs the active {@link PageHints} against a document.\n *\n * Both values are *hints*, not requirements. A value of `0` means \"unknown\" —\n * the response did not expose it and no `pageHints` function derived it. When a\n * value is present (`> 0`) it is relied upon (numbered links, total, sparse\n * placement of jumped-to pages); when absent the page graph falls back to pure\n * `prev`/`next` adjacency (as in cursor/infinite streams).\n *\n * @internal\n */\n readPageHints(document: ReactiveDocument<unknown>): { currentPage: number; totalPages: number } {\n const { currentPage, totalPages } = this.pageHints(document);\n if (currentPage > 0 || totalPages > 0) {\n this.isNumbered = true;\n }\n return { currentPage, totalPages };\n }\n\n /** @internal */\n getPageCache(url: string): Readonly<PageCache<RT, E>> {\n let page = this.pagesCache.get(url);\n if (!page) {\n page = new PageCache<RT, E>(this, url);\n this.pagesCache.set(url, page);\n }\n\n return page as Readonly<PageCache<RT, E>>;\n }\n\n /** @internal */\n loadPage(url: string, request: Future<RT> | null): Readonly<PageCache<RT, E>> {\n const page = this.getPageCache(url);\n if ((!page.isLoaded || page.isError) && request) {\n assert('Expected a request to a load a page', request);\n void page.load(request).then((document) => {\n this.updateFirstPage(page);\n if (document) {\n this.totalPages = this.getTotalPages(document);\n }\n });\n }\n return page;\n }\n\n /** @internal */\n private updateFirstPage(page: Readonly<PageCache<RT, E>>): void {\n let maybeFirstPage = page;\n while (maybeFirstPage.before) {\n maybeFirstPage = maybeFirstPage.before;\n }\n if (!this.firstPage || this.firstPage.pageNumber > maybeFirstPage.pageNumber) {\n this.firstPage = maybeFirstPage;\n }\n }\n\n /** @internal */\n getTotalPages(document: ReactiveDocument<unknown>): number {\n return this.readPageHints(document).totalPages;\n }\n\n /**\n * Every page known to the shared graph, in order — loaded pages and pages\n * known only from links — across all components sharing the collection.\n *\n * This is the whole-collection view. For the run a single component is\n * viewing, use {@link PaginationState.pages}.\n *\n * ```ts\n * const cache = getPaginationCache(firstLink);\n * for (const page of cache.pages) {\n * // page.isLoaded, page.pageNumber, page.data, ...\n * }\n * ```\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n let page: Readonly<PageCache<RT, E>> | null = self.firstPage;\n while (page) {\n yield page;\n page = page.after;\n }\n },\n };\n }\n\n /**\n * The items of every loaded page in the shared graph, flattened into one\n * contiguous iterable in page order. Pages that are known but not loaded\n * contribute nothing.\n *\n * This is the whole-collection view. For the run a single component is\n * viewing, use {@link PaginationState.data}.\n */\n @memoized\n get data(): Iterable<ContentItem<RT>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n for (const page of self.pages) {\n if (page.data) {\n yield* page.data as ContentItem<RT>[];\n }\n }\n },\n };\n }\n}\n\n/**\n * Get the shared {@link PaginationCache} for a given cache key (the collection's\n * `first` or `self` link). Returns the same instance for the same key for the\n * lifetime of the module.\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationCache<RT, E>(key: string): PaginationCache<RT, E> {\n let cache = PaginationCacheMap.get(key);\n\n if (!cache) {\n cache = new PaginationCache<RT, E>(key);\n PaginationCacheMap.set(key, cache);\n }\n\n return cache as PaginationCache<RT, E>;\n}\n\n/**\n * Clears the module-level pagination cache used by {@link getPaginationCache}.\n * Primarily intended for test isolation, since the cache is keyed by url and\n * otherwise persists for the lifetime of the module.\n *\n * @since 5.9.0\n * @public\n */\nexport function clearPaginationCache(): void {\n PaginationCacheMap.clear();\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { RequestManager, Store } from '../index.ts';\nimport type { ReactiveDocument } from '../reactive.ts';\nimport type { Future } from '../request.ts';\nimport type { ContentItem, PageCache } from './page-cache.ts';\nimport { getHref } from './page-cache.ts';\nimport { getPaginationCache, type PageHints, type PaginationCache } from './pagination-cache.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\n\n/**\n * The two navigation surfaces a `<Paginate />` component can drive. Selecting\n * one (via the component's `@mode` arg) narrows the yielded state so the two\n * APIs cannot be mixed:\n *\n * - `'paged'` — single-page view, see {@link PagedPaginationState}.\n * - `'infinite'` — accumulated view, see {@link InfinitePaginationState}.\n */\nexport type PaginateMode = 'paged' | 'infinite';\n\n/**\n * The part of a {@link PaginationState} available to both navigation surfaces.\n */\nexport interface SharedPaginationState<RT = unknown, E = unknown> {\n /** See {@link PaginationState.totalPages}. */\n readonly totalPages: number;\n /** See {@link PaginationState.adoptPage}. */\n adoptPage(request: Future<RT>): Promise<RT | null>;\n /**\n * The shared page graph and data this component reads from.\n *\n * @internal\n */\n readonly paginationCache: PaginationCache<RT, E> | null;\n}\n\n/**\n * The paged (single-page view) surface of a {@link PaginationState}: render\n * {@link PaginationState.activePageRequest | activePageRequest}, navigate with\n * {@link PaginationState.loadPage | loadPage}. This is what the `<Paginate />`\n * component yields in `'paged'` mode (the default).\n */\nexport interface PagedPaginationState<RT = unknown, E = unknown> extends SharedPaginationState<RT, E> {\n /** See {@link PaginationState.activePage}. */\n readonly activePage: Readonly<PageCache<RT, E>> | null;\n /** See {@link PaginationState.activePageRequest}. */\n readonly activePageRequest: Future<RT> | null;\n /** See {@link PaginationState.loadPage}. */\n loadPage: (url: string) => Promise<RT | null>;\n}\n\n/**\n * The infinite (accumulated view) surface of a {@link PaginationState}: render\n * {@link PaginationState.data | data}, grow it with\n * {@link PaginationState.loadNext | loadNext}/{@link PaginationState.loadPrev | loadPrev}.\n * This is what the `<Paginate />` component yields in `'infinite'` mode.\n */\nexport interface InfinitePaginationState<RT = unknown, E = unknown> extends SharedPaginationState<RT, E> {\n /** See {@link PaginationState.data}. */\n readonly data: Iterable<ContentItem<RT>>;\n /** See {@link PaginationState.pages}. */\n readonly pages: Iterable<Readonly<PageCache<RT, E>>>;\n /** See {@link PaginationState.hasNext}. */\n readonly hasNext: boolean;\n /** See {@link PaginationState.hasPrevious}. */\n readonly hasPrevious: boolean;\n /** See {@link PaginationState.nextRequest}. */\n readonly nextRequest: Future<RT> | null;\n /** See {@link PaginationState.previousRequest}. */\n readonly previousRequest: Future<RT> | null;\n /** See {@link PaginationState.loadNext}. */\n loadNext: () => Promise<RT | null>;\n /** See {@link PaginationState.loadPrev}. */\n loadPrev: () => Promise<RT | null>;\n}\n\n/**\n * Resolves a {@link PaginateMode} to the surface it exposes, so a component\n * generic over the mode can yield only that surface.\n */\nexport type PaginationStateFor<RT = unknown, E = unknown, M extends PaginateMode = 'paged'> = M extends 'infinite'\n ? InfinitePaginationState<RT, E>\n : PagedPaginationState<RT, E>;\n\n/**\n * The per-component, local pagination state. It houses the state that is unique\n * to a single component instance — the active page and navigation — while\n * referencing a shared {@link PaginationCache} for the page graph and data.\n *\n * This is the object yielded by the `<Paginate />` component, narrowed by the\n * component's `@mode` arg to one of its two navigation surfaces so the two\n * APIs cannot be mixed:\n *\n * - **Paged** (`@mode=\"paged\"`, the default): {@link PagedPaginationState} —\n * render {@link activePageRequest}, navigate with {@link loadPage} (what the\n * numbered/relational links call). Reads {@link activePage}.\n * - **Infinite** (`@mode=\"infinite\"`): {@link InfinitePaginationState} — render\n * {@link data}, wrap {@link nextRequest}/{@link previousRequest} in `<Request>`\n * for loading state, and grow the view with {@link loadNext}/{@link loadPrev}.\n *\n * Both surfaces read the same shared page graph; the mode only selects which\n * API is exposed.\n *\n * Instances are created via {@link getPaginationState} (or by the `<Paginate />`\n * component on your behalf), never constructed directly.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationState<RT = unknown, E = unknown>\n implements PagedPaginationState<RT, E>, InfinitePaginationState<RT, E>\n{\n /** @internal */\n declare private store: Store | RequestManager;\n /** @internal */\n declare private request: Future<RT>;\n /** @internal */\n declare private pageHints: PageHints | undefined;\n\n /**\n * The shared page graph and data this component reads from.\n *\n * @internal\n */\n declare paginationCache: PaginationCache<RT, E> | null;\n\n /**\n * The page the paged surface is currently showing. Starts at the page this\n * component first loaded and moves whenever {@link loadPage} runs (for\n * example a numbered link is clicked).\n */\n declare activePage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The page this component first loaded, used to seed the active page and frontier.\n *\n * @internal\n */\n declare private initialPage: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The first and last loaded pages of the contiguous run this component is\n * viewing. Drives the infinite surface — {@link data} walks from\n * `frontierStart` to `frontierEnd`, and {@link loadPrev}/{@link loadNext} extend\n * them backward/forward. Both seed to {@link initialPage}; a purely paged\n * consumer never extends them, so they stay put and are effectively unused.\n *\n * @internal\n */\n declare private frontierStart: Readonly<PageCache<RT, E>> | null;\n /** @internal */\n declare private frontierEnd: Readonly<PageCache<RT, E>> | null;\n\n /**\n * The request of the latest {@link adoptPage} call — only that call may\n * commit. Later calls (or a {@link loadPage} navigation) claim the slot,\n * superseding in-flight adoptions so the newest navigation always wins.\n * Untracked bookkeeping.\n *\n * @internal\n */\n declare private _adoptTarget: Future<RT> | null;\n\n constructor(request: Future<RT>, pageHints?: PageHints) {\n this.store = request.requester;\n this.request = request;\n this.pageHints = pageHints;\n this._adoptTarget = null;\n\n void this.setup();\n }\n\n /**\n * The request for the {@link activePage}, for the paged surface to render. This\n * is what a single-page view wraps in a `<Request>` to show the active page's\n * loading, error, and content states:\n *\n * ```gts\n * <Paginate @request={{this.request}}>\n * <:content as |pages|>\n * <Request @request={{pages.activePageRequest}}>\n * <:content as |result|>\n * {{#each result.data as |item|}}...{{/each}}\n * </:content>\n * </Request>\n * </:content>\n * </Paginate>\n * ```\n */\n @memoized\n get activePageRequest(): Future<RT> | null {\n return this.activePage?.request ?? null;\n }\n\n /**\n * The total number of pages in the collection, or `0` when it is unknown (for\n * example a cursor-based collection that reports no total).\n *\n * ```gts\n * <p>Page {{pages.activePage.pageNumber}} of {{pages.totalPages}}</p>\n * ```\n */\n @memoized\n get totalPages(): number {\n return this.paginationCache?.totalPages ?? 0;\n }\n\n /**\n * The pages of the run this component is viewing, from the backward frontier\n * to the forward frontier inclusive, in order. Part of the infinite surface:\n * it is the same run as {@link data}, yielding the {@link PageCache} objects\n * instead of their flattened items — use it when the UI needs per-page\n * boundaries or request states.\n *\n * Grows as {@link loadNext}/{@link loadPrev} extend the frontier. Scoped to\n * this component's frontier (not the shared cache), so components paging the\n * same collection to different extents each see only what they have scrolled\n * through. For every page known to the whole collection, see\n * {@link PaginationCache.pages}.\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n const end = self.frontierEnd;\n let page: Readonly<PageCache<RT, E>> | null = self.frontierStart;\n while (page) {\n yield page;\n if (page === end) {\n break;\n }\n page = page.after;\n }\n },\n };\n }\n\n /**\n * The accumulated items across the loaded run, from the backward frontier to\n * the forward frontier inclusive — the single set an infinite collection renders.\n * Grows as {@link loadNext}/{@link loadPrev} extend the frontier. Scoped to this\n * component's frontier (not the shared cache), so components paging the same\n * collection to different extents each see only what they have scrolled through.\n *\n * The flattened items of {@link pages}, as one contiguous iterable. For the\n * items of every loaded page in the whole collection, see\n * {@link PaginationCache.data}.\n *\n * ```gts\n * <Paginate @request={{this.request}} @mode=\"infinite\">\n * <:content as |pages features|>\n * {{#each pages.data as |item|}}...{{/each}}\n * {{#if pages.hasNext}}\n * <button {{on \"click\" features.loadNext}}>Load more</button>\n * {{/if}}\n * </:content>\n * </Paginate>\n * ```\n */\n @memoized\n get data(): Iterable<ContentItem<RT>> {\n // oxlint-disable-next-line typescript/no-this-alias\n const self = this;\n return {\n *[Symbol.iterator]() {\n for (const page of self.pages) {\n if (page.data) {\n yield* page.data as ContentItem<RT>[];\n }\n }\n },\n };\n }\n\n /**\n * Whether a page exists after the forward frontier — i.e. there is more to load\n * going forward. Use to hide the trailing load-more sentinel at end-of-list:\n *\n * ```gts\n * {{#if pages.hasNext}}\n * <button {{on \"click\" features.loadNext}}>Load more</button>\n * {{/if}}\n * ```\n */\n @memoized\n get hasNext(): boolean {\n return Boolean(this.frontierEnd?.nextLink);\n }\n\n /**\n * Whether a page exists before the backward frontier.\n */\n @memoized\n get hasPrevious(): boolean {\n return Boolean(this.frontierStart?.prevLink);\n }\n\n /**\n * The request for the page just after the forward frontier, for the infinite\n * surface. `null` until {@link loadNext} fires it (so a `<Request>` wrapping it\n * renders its idle block), the in-flight `Future` while that page loads, then\n * `null` again once the frontier advances onto it. Also `null` at end-of-list.\n *\n * ```gts\n * {{#if pages.hasNext}}\n * <Request @request={{pages.nextRequest}}>\n * <:idle><button {{on \"click\" features.loadNext}}>Load more</button></:idle>\n * <:loading><Spinner /></:loading>\n * </Request>\n * {{/if}}\n * ```\n */\n @memoized\n get nextRequest(): Future<RT> | null {\n const url = this.frontierEnd?.nextLink;\n if (!url) {\n return null;\n }\n return this.paginationCache?.getPageCache(url).request ?? null;\n }\n\n /**\n * The request for the page just before the backward frontier. Mirror of\n * {@link nextRequest} for {@link loadPrev}.\n */\n @memoized\n get previousRequest(): Future<RT> | null {\n const url = this.frontierStart?.prevLink;\n if (!url) {\n return null;\n }\n return this.paginationCache?.getPageCache(url).request ?? null;\n }\n\n /** @internal */\n private async setup(): Promise<void> {\n let document;\n try {\n document = await this.request;\n } catch {\n // a failed (or aborted) initial request leaves the pagination state\n // empty. Rendering the failure is the request subscription's job, and\n // recovery (retry) produces a new request and with it a new state.\n return;\n }\n const content = document.content as ReactiveDocument<unknown>;\n const selfLink = getHref(content.links?.self);\n const firstLink = getHref(content.links?.first);\n assert('Expected the initial document to have a self link', selfLink);\n\n const cacheKey = firstLink ?? selfLink ?? '';\n const cache = getPaginationCache<RT, E>(cacheKey);\n cache.installPageHints(this.pageHints);\n this.paginationCache = cache;\n cache.totalPages = cache.getTotalPages(content);\n this.activePage = this.initialPage = cache.loadPage(selfLink, this.request);\n this.frontierStart = this.frontierEnd = this.initialPage;\n }\n\n /**\n * Commits a resolved, membership-proven page into this state, making it the\n * {@link activePage}. The synchronous commit step under {@link adoptPage},\n * which is where the resolution and membership verification live.\n *\n * It only activates the page and keeps the infinite surface's frontier\n * coherent — a page already inside the run leaves the frontier untouched,\n * an adjacent page extends it, and a disjoint page resets the run to the\n * adopted page (jump semantics).\n *\n * @internal\n */\n private _activate(page: Readonly<PageCache<RT, E>>, url: string): void {\n this.activePage = page;\n\n for (const existing of this.pages) {\n if (existing === page) {\n return;\n }\n }\n\n if (this.frontierEnd?.nextLink === url) {\n this.frontierEnd = page;\n } else if (this.frontierStart?.prevLink === url) {\n this.frontierStart = page;\n } else {\n this.frontierStart = this.frontierEnd = page;\n }\n }\n\n /**\n * Adopts an externally-issued request into this pagination, making its page\n * the {@link activePage} — the programmatic entry point for route-driven\n * navigation when managing a `PaginationState` directly (the `<Paginate />`\n * component uses the same mechanism for a changed `@request` arg).\n *\n * Awaits the request and verifies that its document is a page of this\n * state's collection (same `first` — or `self` — link). On a match, the\n * page is loaded (a page already in the shared cache is reused) and — once\n * its request settles — committed: it becomes the active page, and the\n * infinite surface's run is kept coherent (a page already inside the run\n * leaves it untouched, an adjacent page extends it, a disjoint page resets\n * the run to the adopted page). The commit happens only after the page has\n * loaded, so the previous page stays active — and rendered — while the\n * adoption resolves. Returns the page's document.\n *\n * Concurrent calls race safely: the latest call wins. An earlier in-flight\n * adoption is superseded and commits nothing, and a {@link loadPage}\n * navigation also supersedes a pending adoption (the user's click is the\n * newer intent).\n *\n * Returns `null` — leaving the state untouched — whenever the adoption does\n * not commit:\n *\n * - the request (or its page's load) rejected\n * - the document is a page of a *different* collection\n * - this state has not finished setting up its own collection yet\n * - the call was superseded by a newer navigation\n *\n * ```ts\n * const pages = getPaginationState(initialRequest);\n * // later, e.g. in a route model hook reacting to a ?page= param:\n * const adopted = await pages.adoptPage(store.request(query));\n * if (adopted === null) {\n * // not part of this collection — start a fresh pagination\n * }\n * ```\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler.\n */\n adoptPage = async (request: Future<RT>): Promise<RT | null> => {\n this._adoptTarget = request;\n\n let content;\n try {\n content = (await request).content as ReactiveDocument<unknown>;\n } catch {\n return null;\n }\n if (this._adoptTarget !== request) {\n // a newer navigation claimed the slot while the request resolved\n return null;\n }\n\n const cache = this.paginationCache;\n if (!cache) {\n return null;\n }\n\n const selfLink = getHref(content.links?.self);\n const firstLink = getHref(content.links?.first);\n assert('Expected the adopted document to have a self link', selfLink);\n if (!selfLink || (firstLink ?? selfLink) !== cache.key) {\n return null;\n }\n\n const page = cache.loadPage(selfLink, request);\n try {\n // wait for the page's request state to settle its value; adopting an\n // already-settled future still needs this microtask\n await page.request;\n } catch {\n return null;\n }\n if (this._adoptTarget !== request) {\n // a newer navigation claimed the slot while the page loaded\n return null;\n }\n\n this._activate(page, selfLink);\n return page.value;\n };\n\n /**\n * Extends the backward frontier by one page, prepending it to {@link data}.\n * The frontier advances only once the page has loaded, so\n * {@link previousRequest} tracks the in-flight page meanwhile. Returns the\n * loaded value, or `null` when there is no previous page or the load fails.\n *\n * On failure the frontier stays put and {@link previousRequest} keeps\n * resolving to the failed page, so a wrapping `<Request>` renders its error\n * block. Calling again retries: the failed page is re-requested with a\n * forced reload.\n *\n * In templates it is also available as the `loadPrev` content feature\n * ({@link InfinitePaginationContentFeatures.loadPrev}) yielded by\n * `<Paginate />`; the two are the same function.\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler.\n */\n loadPrev = async (): Promise<RT | null> => {\n return this._extend('prev');\n };\n\n /**\n * Extends the forward frontier by one page, appending it to {@link data}.\n * Mirror of {@link loadPrev}.\n *\n * In templates it is also available as the `loadNext` content feature\n * ({@link InfinitePaginationContentFeatures.loadNext}) yielded by\n * `<Paginate />`; the two are the same function.\n *\n * ```gts\n * <button {{on \"click\" pages.loadNext}}>Load more</button>\n * ```\n */\n loadNext = async (): Promise<RT | null> => {\n return this._extend('next');\n };\n\n /** @internal */\n private _extend = async (dir: 'prev' | 'next'): Promise<RT | null> => {\n const cache = this.paginationCache;\n assert('Expected the pagination cache to be set up before loading a page', cache);\n\n const frontier = dir === 'next' ? this.frontierEnd : this.frontierStart;\n const url = dir === 'next' ? frontier?.nextLink : frontier?.prevLink;\n if (!url) {\n return null;\n }\n\n const page = cache.getPageCache(url);\n if (!page.isRequested || page.isError) {\n // re-requesting a page that previously failed is the retry path: force\n // a reload so a cached error response is not replayed.\n const request = this.store.request(\n page.isError ? { method: 'GET', url, cacheOptions: { reload: true } } : { method: 'GET', url }\n );\n cache.loadPage(url, request as Future<RT>);\n }\n\n try {\n await page.request;\n } catch {\n // the failure is surfaced reactively: the frontier stays put, so\n // `nextRequest`/`previousRequest` resolves to the failed page and a\n // wrapping `<Request>` renders its error block. Calling again retries.\n return null;\n }\n\n // Advance the frontier only after the load resolves. While loading, the\n // frontier still points at the previous page, so `nextRequest`/`prevRequest`\n // resolves to this in-flight page and a wrapping `<Request>` shows loading.\n if (dir === 'next') {\n this.frontierEnd = page;\n } else {\n this.frontierStart = page;\n }\n\n return page.value;\n };\n\n /**\n * Loads a specific page by its URL and makes it the {@link activePage},\n * requesting it first if it is not already loaded. This is the paged surface's\n * navigation entry point, called by the numbered and relational links.\n *\n * In templates it is also available as the `loadPage` content feature\n * ({@link PagedPaginationContentFeatures.loadPage}) yielded by `<Paginate />`;\n * the two are the same function.\n *\n * It is a stable reference, so it is safe to pass around as an \"action\" or\n * \"event\" handler. Returns the page's value, or `null` if it has none or\n * the load fails.\n *\n * On failure the page stays active and {@link activePageRequest} resolves to\n * it, so a wrapping `<Request>` renders its error block. Calling again (for\n * example clicking the page's link a second time) retries: the failed page\n * is re-requested with a forced reload.\n *\n * ```gts\n * <EachLink @pages={{pages}}>\n * <:link as |link|>\n * <button {{on \"click\" (fn features.loadPage link.url)}}>{{link.text}}</button>\n * </:link>\n * </EachLink>\n * ```\n */\n loadPage = async (url: string): Promise<RT | null> => {\n const cache = this.paginationCache;\n assert('Expected the pagination cache to be set up before loading a page', cache);\n\n // an explicit navigation supersedes any in-flight adoption\n this._adoptTarget = null;\n\n const page = cache.getPageCache(url);\n this.activePage = page;\n\n if (!page.isLoaded || page.isError) {\n // re-requesting a page that previously failed is the retry path: force\n // a reload so a cached error response is not replayed.\n const request = this.store.request(\n page.isError ? { method: 'GET', url, cacheOptions: { reload: true } } : { method: 'GET', url }\n );\n cache.loadPage(url, request as Future<RT>);\n try {\n await page.request;\n } catch {\n // the failure is surfaced reactively: the page stays active, so\n // `activePageRequest` resolves to it and a wrapping `<Request>`\n // renders its error block. Calling again retries.\n return null;\n }\n }\n\n return page.value;\n };\n}\n\ndefineSignal(PaginationState.prototype, 'paginationCache', null);\ndefineSignal(PaginationState.prototype, 'activePage', null);\ndefineSignal(PaginationState.prototype, 'initialPage', null);\ndefineSignal(PaginationState.prototype, 'frontierStart', null);\ndefineSignal(PaginationState.prototype, 'frontierEnd', null);\n\nconst PaginationStateCache = new WeakMap<Future<unknown>, PaginationState>();\n\n/**\n * Get the {@link PaginationState} for a given request. Returns the same instance\n * for the same request future, so that repeated calls (e.g. in a template, or\n * alongside the `<Paginate />` component using the same request) share the same\n * local pagination state. Keyed by request identity, just like\n * {@link getRequestState}.\n *\n * ```ts\n * const future = store.request(query);\n * const pages = getPaginationState(future);\n *\n * await future;\n * pages.totalPages; // now known, if the response exposed it\n * await pages.loadNext();\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationState<RT, E>(request: Future<RT>, pageHints?: PageHints): PaginationState<RT, E> {\n let state = PaginationStateCache.get(request);\n\n if (!state) {\n // the cache is heterogeneous over RT/E (mirrored by the cast on return)\n state = new PaginationState<RT, E>(request, pageHints) as unknown as PaginationState;\n PaginationStateCache.set(request, state);\n }\n\n return state as PaginationState<RT, E>;\n}\n","import type { PageCache } from './page-cache.ts';\nimport type { PagedPaginationState } from './pagination-state.ts';\nimport { memoized } from './reactivity/signal';\n\nconst PaginationLinksCache = new WeakMap<PagedPaginationState, PaginationLinks>();\n\n/**\n * A single numbered link, e.g. page `3`. Loads its page and makes it active when\n * {@link setActive} runs. Carries its {@link index} and its\n * {@link distanceFromActiveIndex} so a UI can style links by how far they sit\n * from the current page.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#each state.links as |link|}}\n * {{#if link.isReal}}\n * <button class={{if link.isCurrent \"active\"}} {{on \"click\" link.setActive}}>\n * {{link.text}}\n * </button>\n * {{/if}}\n * {{/each}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class RealPaginationLink {\n readonly isReal = true as const;\n\n readonly url: string;\n readonly index: number;\n readonly isCurrent: boolean;\n readonly distanceFromActiveIndex: number;\n /** @internal */\n declare private _loadPage: (url: string) => Promise<unknown>;\n\n constructor(url: string, index: number, activeIndex: number, loadPage: (url: string) => Promise<unknown>) {\n this.url = url;\n this.index = index;\n this.isCurrent = index === activeIndex;\n this.distanceFromActiveIndex = Math.abs(index - activeIndex);\n this._loadPage = loadPage;\n }\n\n get text(): string {\n return `${this.index}`;\n }\n\n /**\n * Loads this link's page and makes it the active page on the associated\n * {@link PaginationState}. It is a stable reference, so it is safe to pass\n * around as an \"action\" or \"event\" handler:\n *\n * ```gts\n * <button {{on \"click\" link.setActive}}>{{link.text}}</button>\n * ```\n */\n setActive = (): Promise<unknown> => {\n return this._loadPage(this.url);\n };\n}\n\n/**\n * A stand-in for a run of pages that have not been loaded yet, rendered as an\n * ellipsis between numbered links. It covers an {@link indexRange} rather than a\n * single page and has no page to navigate to.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#each state.links as |link|}}\n * {{#unless link.isReal}}\n * <span title=\"{{link.rangeSize}} more pages\">{{link.text}}</span>\n * {{/unless}}\n * {{/each}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PlaceholderPaginationLink {\n readonly isReal = false as const;\n\n /**\n * The inclusive `[start, end]` page-number range of not-yet-loaded pages this\n * placeholder stands in for.\n */\n indexRange: [start: number, end: number];\n /** @internal */\n private readonly activeIndex: number;\n\n text = '.';\n\n constructor(index: [start: number, end: number], activeIndex: number) {\n this.indexRange = index;\n this.activeIndex = activeIndex;\n }\n\n /** The number of pages this placeholder covers. */\n get rangeSize(): number {\n return this.indexRange[1] - this.indexRange[0] + 1;\n }\n\n /**\n * The distance between the active page and the nearest edge of this\n * placeholder's index range.\n */\n get distanceFromActiveIndex(): number {\n const [start, end] = this.indexRange;\n return Math.min(Math.abs(start - this.activeIndex), Math.abs(end - this.activeIndex));\n }\n\n /** @internal */\n private _mergeRange(newRange: [start: number, end: number]): void {\n const [oldStart, oldEnd] = this.indexRange;\n const [newStart, newEnd] = newRange;\n const mergedRange: [start: number, end: number] = [Math.min(oldStart, newStart), Math.max(oldEnd, newEnd)];\n this.indexRange = mergedRange;\n }\n}\n\n/**\n * A relational (`first`/`prev`/`next`/`last`) navigation link, relative to the\n * active page. Unlike {@link RealPaginationLink} these carry no ordinal index —\n * they are the only links available for cursor-based pagination, where pages are\n * chained purely by opaque relational links with no page number or total. They\n * are also available in numbered pagination as a convenience.\n *\n * ```gts\n * <EachLink @pages={{pages}} as |state|>\n * {{#if state.prev}}<button {{on \"click\" state.prev.setActive}}>Previous</button>{{/if}}\n * {{#if state.next}}<button {{on \"click\" state.next.setActive}}>Next</button>{{/if}}\n * </EachLink>\n * ```\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class RelationalPaginationLink {\n readonly isReal = true as const;\n\n readonly rel: 'first' | 'prev' | 'next' | 'last';\n readonly url: string;\n /**\n * Whether this link points at the page that is already active — for example\n * the `first` link while the first page is being viewed. Useful for\n * disabling the control.\n */\n readonly isCurrent: boolean;\n /** @internal */\n declare private _loadPage: (url: string) => Promise<unknown>;\n\n constructor(\n rel: 'first' | 'prev' | 'next' | 'last',\n url: string,\n isCurrent: boolean,\n loadPage: (url: string) => Promise<unknown>\n ) {\n this.rel = rel;\n this.url = url;\n this.isCurrent = isCurrent;\n this._loadPage = loadPage;\n }\n\n get text(): string {\n return this.rel;\n }\n\n /**\n * Loads this link's page and makes it the active page on the associated\n * {@link PaginationState}. It is a stable reference, so it is safe to pass\n * around as an \"action\" or \"event\" handler:\n *\n * ```gts\n * <button {{on \"click\" link.setActive}}>{{link.text}}</button>\n * ```\n */\n setActive = (): Promise<unknown> => {\n return this._loadPage(this.url);\n };\n}\n\n/**\n * A member of {@link PaginationLinks.links}: either a numbered\n * {@link RealPaginationLink} or a {@link PlaceholderPaginationLink} standing in\n * for a gap. Discriminate with {@link RealPaginationLink.isReal | isReal}:\n *\n * ```ts\n * for (const link of links.links) {\n * if (link.isReal) {\n * // numbered link: link.index, link.setActive\n * } else {\n * // gap: link.indexRange\n * }\n * }\n * ```\n */\nexport type PaginationLink = RealPaginationLink | PlaceholderPaginationLink;\n\n/**\n * The reactive set of navigation links derived from a {@link PaginationState}.\n * Where `PaginationState` tracks which pages are loaded and which one is active,\n * `PaginationLinks` turns that page graph into the links a UI renders to move\n * between pages.\n *\n * It provides two kinds of link:\n *\n * - {@link links}: the numbered links, with {@link PlaceholderPaginationLink}\n * placeholders standing in for gaps of not-yet-loaded pages. Only numbered\n * collections (where the server exposes page numbers) produce these.\n * - {@link prev} and {@link next}: the relational links for the active page.\n * Available in both numbered and cursor-based pagination, and the only links a\n * cursor-based collection has.\n * - {@link first} and {@link last}: the relational links to the collection's\n * edges, when the response exposes them. Usually present on every page —\n * including the edge page itself, where the link's\n * {@link RelationalPaginationLink.isCurrent | isCurrent} is `true`.\n *\n * Every link updates as pages load and as the active page changes, since they\n * read straight from the state's shared page graph. To get the links for a\n * state, use {@link getPaginationLinks}.\n *\n * See also:\n * - {@link RealPaginationLink}\n * - {@link PlaceholderPaginationLink}\n * - {@link RelationalPaginationLink}\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationLinks<RT = unknown, E = unknown> {\n /** @internal */\n declare private paginationState: PagedPaginationState<RT, E>;\n\n constructor(paginationState: PagedPaginationState<RT, E>) {\n this.paginationState = paginationState;\n }\n\n /**\n * The relational `first` link of the collection, or `null` when the active\n * page's response did not expose one. Unlike {@link prev}/{@link next} it is\n * usually present on every page — including the first page itself, where the\n * link's {@link RelationalPaginationLink.isCurrent | isCurrent} is `true`\n * (useful for disabling the control).\n */\n @memoized\n get first(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.firstLink;\n return url\n ? new RelationalPaginationLink('first', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `prev` link for the active page, or `null` at the start of the\n * collection. Available in both numbered and cursor pagination.\n */\n @memoized\n get prev(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.prevLink;\n return url\n ? new RelationalPaginationLink('prev', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `next` link for the active page, or `null` at the end of the\n * collection. Available in both numbered and cursor pagination.\n */\n @memoized\n get next(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.nextLink;\n return url\n ? new RelationalPaginationLink('next', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The relational `last` link of the collection, or `null` when the active\n * page's response did not expose one. Mirror of {@link first} for the end of\n * the collection.\n */\n @memoized\n get last(): RelationalPaginationLink | null {\n const activePage = this.paginationState.activePage;\n const url = activePage?.lastLink;\n return url\n ? new RelationalPaginationLink('last', url, url === activePage?.selfLink, this.paginationState.loadPage)\n : null;\n }\n\n /**\n * The numbered links and placeholders, derived from the shared page graph.\n *\n * Only produced for numbered pagination (where the server exposes page numbers).\n * Cursor-based collections have no page numbers, so this is empty — use\n * {@link prev}/{@link next} for cursor navigation.\n */\n @memoized\n get links(): PaginationLink[] {\n const links: PaginationLink[] = [];\n\n const cache = this.paginationState.paginationCache;\n if (!cache || !cache.isNumbered) {\n return links;\n }\n\n const { firstPage, totalPages } = cache;\n const activeIndex = this.paginationState.activePage?.pageNumber ?? 0;\n\n if (firstPage) {\n let previousPage: Readonly<PageCache<RT, E>> | null = null;\n let currentPage: Readonly<PageCache<RT, E>> | null = firstPage;\n while (currentPage) {\n if (previousPage && currentPage.pageNumber - previousPage.pageNumber > 1) {\n links.push(\n new PlaceholderPaginationLink([previousPage.pageNumber + 1, currentPage.pageNumber - 1], activeIndex)\n );\n }\n links.push(\n new RealPaginationLink(\n currentPage.selfLink ?? '',\n currentPage.pageNumber,\n activeIndex,\n this.paginationState.loadPage\n )\n );\n previousPage = currentPage;\n currentPage = currentPage.after;\n }\n\n if (previousPage && previousPage.pageNumber < totalPages) {\n links.push(new PlaceholderPaginationLink([previousPage.pageNumber + 1, totalPages], activeIndex));\n }\n }\n\n return links;\n }\n}\n\n/**\n * Get the {@link PaginationLinks} for a given {@link PaginationState}. Returns\n * the same instance for the same state, so repeated calls (for example a\n * `<Paginate />` component and a separate links component reading the same state)\n * share one set of links. Keyed by state identity, the same way\n * {@link getPaginationState} is keyed by request and {@link getRequestState} by\n * future.\n *\n * ```ts\n * const links = getPaginationLinks(paginationState);\n *\n * for (const link of links.links) {\n * if (link.isReal) {\n * // render a numbered link, using link.setActive as the click handler\n * } else {\n * // render an ellipsis for the gap link.indexRange covers\n * }\n * }\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function getPaginationLinks<RT, E>(state: PagedPaginationState<RT, E>): Readonly<PaginationLinks<RT, E>> {\n let links = PaginationLinksCache.get(state);\n\n if (!links) {\n links = new PaginationLinks<RT, E>(state);\n PaginationLinksCache.set(state, links);\n }\n\n return links;\n}\n","import type { RequestManager, Store } from '../index.ts';\nimport type { Future } from '../request.ts';\nimport type { StructuredErrorDocument } from '../types/request.ts';\nimport type { PageHints } from './pagination-cache.ts';\nimport { getPaginationState, type PaginateMode, type PaginationState } from './pagination-state.ts';\nimport { defineSignal, memoized } from './reactivity/signal.ts';\nimport type { RequestLoadingState } from './request-state.ts';\nimport type { RequestSubscription, SubscriptionArgs } from './request-subscription.ts';\nimport { createRequestSubscription, DISPOSE } from './request-subscription.ts';\n\ninterface ErrorFeatures {\n isHidden: boolean;\n isOnline: boolean;\n retry: () => Promise<void>;\n}\n\n/**\n * The content features available in both pagination modes: the state and\n * controls of the initial request.\n */\nexport interface SharedPaginationContentFeatures<RT> {\n isOnline: boolean;\n isHidden: boolean;\n isRefreshing: boolean;\n /**\n * Whether a changed `@request` arg is currently resolving against the\n * loaded collection — e.g. a route-driven navigation (browser back button).\n * The existing content stays rendered while this is `true`; once the\n * request resolves it either becomes the active page (same collection) or\n * the component resets to the new collection.\n */\n isNavigating: boolean;\n refresh: () => Promise<void>;\n reload: () => Promise<void>;\n abort?: () => void;\n latestRequest?: Future<RT>;\n}\n\n/**\n * The content features yielded in `'paged'` mode: navigation happens by\n * loading a specific page.\n */\nexport interface PagedPaginationContentFeatures<RT> extends SharedPaginationContentFeatures<RT> {\n loadPage: (url: string) => Promise<RT | null>;\n}\n\n/**\n * The content features yielded in `'infinite'` mode: navigation happens by\n * extending the loaded run at either end.\n */\nexport interface InfinitePaginationContentFeatures<RT> extends SharedPaginationContentFeatures<RT> {\n loadNext: () => Promise<RT | null>;\n loadPrev: () => Promise<RT | null>;\n}\n\n/**\n * The full set of content features a {@link PaginationSubscription} builds —\n * both modes' surfaces. The `<Paginate />` component narrows this to one mode\n * via {@link PaginationContentFeaturesFor} before yielding.\n */\nexport type PaginationContentFeatures<RT> = PagedPaginationContentFeatures<RT> & InfinitePaginationContentFeatures<RT>;\n\n/**\n * Resolves a {@link PaginateMode} to the content features it exposes. Mirror of\n * {@link PaginationStateFor}.\n */\nexport type PaginationContentFeaturesFor<RT = unknown, M extends PaginateMode = 'paged'> = M extends 'infinite'\n ? InfinitePaginationContentFeatures<RT>\n : PagedPaginationContentFeatures<RT>;\n\nexport interface PaginationSubscriptionArgs<RT, E> extends SubscriptionArgs<RT, E> {\n /**\n * A function to extract the `currentPage` and `totalPages` from a loaded document\n * when they are not available in the default `meta` locations. Must be the same\n * reference across all `<Paginate />` components sharing a collection.\n */\n pageHints?: PageHints;\n}\n\nexport interface PaginateArgs<RT, E> extends PaginationSubscriptionArgs<RT, E> {\n /**\n * Which navigation surface the component yields: `'paged'` (the default) or\n * `'infinite'`. Type-only — it narrows the yielded state and features so the\n * two surfaces cannot be mixed, and is never read at runtime.\n */\n mode?: PaginateMode;\n\n subscription?: PaginationSubscription<RT, E>;\n\n /**\n * The store instance to use for making requests. If contexts are available,\n * the component will default to using the `store` on the context.\n *\n * This is required if the store is not available via context or should be\n * different from the store provided via context.\n *\n */\n store?: Store | RequestManager;\n}\n\n// oxlint-disable-next-line no-unused-vars\nexport interface PaginationSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\n/**\n * Lifecycle glue for the `<Paginate />` component. Owns the initial\n * {@link RequestSubscription} (loading/error state, autorefresh, disposal) and\n * the per-component {@link PaginationState} that it hands to the component.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationSubscription<RT, E> {\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _subscribedTo: object | null;\n /** @internal */\n declare private _args: PaginationSubscriptionArgs<RT, E>;\n /**\n * The Store this subscription subscribes to or the RequestManager\n * which issues this request.\n */\n declare store: Store | RequestManager;\n\n /**\n * The wrapped {@link RequestSubscription} monitoring the initial request.\n * Created eagerly: constructing one consumes reactive state (its own\n * signals), so building it lazily inside a tracked getter would cause the\n * getter to invalidate — and the subscription to be recreated, losing its\n * reloaded request — whenever `retry`/`reload` runs.\n *\n * @internal\n */\n declare private _requestSubscription: RequestSubscription<RT, E>;\n\n /**\n * The first request this subscription saw — the one that keys the\n * {@link PaginationState} until a navigation resolves to a different\n * collection. Plain (untracked) because it is written during the first\n * computation of {@link paginationState}.\n *\n * @internal\n */\n declare private _seedRequest: Future<RT> | null;\n\n /**\n * The request a resolved navigation swapped the {@link PaginationState} to,\n * when the navigation turned out to target a different collection. A signal:\n * writing it (always outside of render, from {@link _resolveNavigation})\n * invalidates {@link paginationState} so the fresh state takes over.\n *\n * @internal\n */\n declare private _navRequest: Future<RT> | null;\n\n /**\n * The changed request currently being resolved by {@link _resolveNavigation},\n * both to avoid kicking the same navigation twice and as the latest-wins\n * guard when several changes race. Untracked bookkeeping.\n *\n * @internal\n */\n declare private _navTarget: Future<RT> | null;\n\n constructor(store: Store | RequestManager, args: PaginationSubscriptionArgs<RT, E>) {\n this._args = args;\n this.store = store;\n this.isDestroyed = false;\n this._seedRequest = null;\n this._navTarget = null;\n this[DISPOSE] = _DISPOSE;\n this._requestSubscription = createRequestSubscription<RT, E>(store, args);\n }\n\n /**\n * The per-component pagination state yielded to the component.\n *\n * Keyed to the request that started the collection, not the current\n * `@request` arg: when the arg changes, the existing state keeps rendering\n * while {@link _resolveNavigation} resolves the new request in the\n * background. A request that resolves to a page of the same collection is\n * adopted into this state as the new active page (route-driven navigation,\n * e.g. the browser back button); one that resolves to a different\n * collection swaps in a fresh state (a true reset).\n *\n * A background `refresh` does not swap the request, so the pagination\n * state is stable across refreshes.\n */\n @memoized\n get paginationState(): PaginationState<RT, E> {\n const request = this._requestSubscription.request;\n const active = this._navRequest ?? this._seedRequest;\n\n if (!active) {\n // first access: this request starts the collection\n this._seedRequest = request;\n return getPaginationState<RT, E>(request, this._args.pageHints);\n }\n\n if (request !== active && request !== this._navTarget) {\n this._navTarget = request;\n void this._resolveNavigation(request);\n }\n\n return getPaginationState<RT, E>(active, this._args.pageHints);\n }\n\n /**\n * Resolves a changed `@request` arg against the current collection via\n * {@link PaginationState.adoptPage}: a request that resolves to a page of\n * the same collection is adopted into the existing state; one that resolves\n * to a different collection (or arrives before a collection is loaded) swaps\n * the state for a fresh one keyed to this request.\n *\n * A rejected request changes nothing here — the request subscription\n * already surfaces the failure (error/cancelled states), and the existing\n * pagination state is kept for recovery. The request is awaited before\n * `adoptPage` so that rejection and the latest-wins guard are handled\n * before anything is adopted.\n *\n * @internal\n */\n private async _resolveNavigation(request: Future<RT>): Promise<void> {\n try {\n await request;\n } catch {\n return;\n }\n\n // latest wins: a newer navigation or disposal superseded this one\n if (this.isDestroyed || this._navTarget !== request) {\n return;\n }\n\n const adopted = await this.paginationState.adoptPage(request);\n if (this.isDestroyed || this._navTarget !== request) {\n // a newer navigation claimed the slot while `adoptPage` resolved — its\n // own resolution decides the outcome. Without this check a superseded\n // `null` would be mistaken for a foreign collection and wrongly reset.\n return;\n }\n if (adopted === null) {\n // this call is still the latest navigation, so `null` means the page is\n // not part of the current collection (or the collection has not set up\n // yet): reset to a fresh state\n this._navRequest = request;\n }\n // `_navTarget` intentionally stays set: it marks this request as\n // processed so the getter does not re-kick it, and a newer navigation\n // may already have claimed the field while `adoptPage` was awaited.\n }\n\n /**\n * Whether there is no request or query to monitor, so the component has\n * nothing to load.\n */\n @memoized\n get isIdle(): boolean {\n return this._requestSubscription.isIdle;\n }\n\n /**\n * Whether the collection is still blocking-loading: no {@link PaginationState}\n * has finished setting up yet. Only the very first page load (or the reset\n * to a different collection) blocks here — extending the collection with\n * `loadNext`/`loadPrev` does not, and neither does a changed `@request` arg\n * while a collection is already on screen (that is {@link isNavigating}).\n *\n * Remains `true` for the moment between the request resolving and the\n * {@link paginationState} finishing its setup from the response, so that\n * {@link isSuccess} consumers never see a success state with an empty\n * pagination surface.\n */\n @memoized\n get isLoading(): boolean {\n const { reqState } = this._requestSubscription;\n return this.paginationState.paginationCache === null && (reqState.isLoading || reqState.isSuccess);\n }\n\n /**\n * Whether a changed `@request` arg is resolving while a collection is\n * already on screen — route-driven navigation, e.g. the browser back\n * button. The content stays rendered (see {@link isSuccess}); consumers can\n * use this to show a lightweight navigation indicator, the same way a\n * `loadPage` call surfaces through the active page's request state.\n */\n @memoized\n get isNavigating(): boolean {\n return this.paginationState.paginationCache !== null && this._requestSubscription.reqState.isLoading;\n }\n\n /**\n * The {@link RequestLoadingState} for the initial request, for building UIs\n * that respond to download progress.\n */\n @memoized\n get loadingState(): RequestLoadingState {\n return this._requestSubscription.reqState.loadingState;\n }\n\n /**\n * Whether the component has a set-up {@link paginationState} to render and\n * the current request did not fail. Stays `true` while a changed `@request`\n * arg resolves ({@link isNavigating}), so the existing content keeps\n * rendering instead of falling back to a blocking loading state.\n */\n @memoized\n get isSuccess(): boolean {\n const { reqState } = this._requestSubscription;\n return this.paginationState.paginationCache !== null && !reqState.isError && !reqState.isCancelled;\n }\n\n /**\n * Whether the initial request was cancelled (aborted).\n */\n @memoized\n get isCancelled(): boolean {\n return this._requestSubscription.reqState.isCancelled;\n }\n\n /**\n * Whether the initial request rejected with an error.\n */\n @memoized\n get isError(): boolean {\n return this._requestSubscription.reqState.isError;\n }\n\n /**\n * The error the initial request rejected with, or `null` if it did not reject.\n */\n @memoized\n get reason(): StructuredErrorDocument<E> | null {\n return this._requestSubscription.reqState.reason;\n }\n\n /**\n * Error features to yield to the error slot of a component\n */\n @memoized\n get errorFeatures(): ErrorFeatures {\n return {\n isHidden: this._requestSubscription.isHidden,\n isOnline: this._requestSubscription.isOnline,\n retry: this._requestSubscription.retry,\n };\n }\n\n /**\n * Content features to yield to the content slot of a component\n */\n @memoized\n get contentFeatures(): PaginationContentFeatures<RT> {\n const contentFeatures = this._requestSubscription.contentFeatures;\n const { paginationState } = this;\n const feat: PaginationContentFeatures<RT> = {\n ...contentFeatures,\n isNavigating: this.isNavigating,\n loadPrev: paginationState.loadPrev,\n loadNext: paginationState.loadNext,\n loadPage: paginationState.loadPage,\n };\n\n if (feat.isRefreshing) {\n feat.abort = () => {\n contentFeatures.latestRequest?.abort();\n };\n }\n\n return feat;\n }\n\n /**\n * The initial request `Future` this subscription is monitoring, i.e. the first\n * page load. This is the future the {@link paginationState} is built from.\n *\n * @internal\n */\n @memoized\n get request(): Future<RT> {\n return this._requestSubscription.request;\n }\n}\n\ndefineSignal(PaginationSubscription.prototype, '_navRequest', null);\n\n/**\n * Creates the {@link PaginationSubscription} a `<Paginate />` component uses to\n * manage its request lifecycle and pagination state. Pass the result back into\n * the component via `@subscription` to manage the lifecycle externally.\n *\n * ```ts\n * const subscription = createPaginationSubscription(store, { request });\n *\n * subscription.paginationState; // the per-component PaginationState\n * subscription[DISPOSE](); // tear down when the owning component unmounts\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function createPaginationSubscription<RT, E>(\n store: Store | RequestManager,\n args: PaginationSubscriptionArgs<RT, E>\n): PaginationSubscription<RT, E> {\n return new PaginationSubscription(store, args);\n}\n\ninterface PrivatePaginationSubscription {\n isDestroyed: boolean;\n _requestSubscription: RequestSubscription<unknown, unknown>;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivatePaginationSubscription {\n return sub as PrivatePaginationSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: PaginationSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n self._requestSubscription?.[DISPOSE]?.();\n}\n","import { memoized } from './-private.ts';\nimport type { PaginationLinks } from './pagination-links.ts';\nimport { getPaginationLinks } from './pagination-links.ts';\nimport type { PagedPaginationState } from './pagination-state.ts';\nimport { DISPOSE } from './request-subscription.ts';\n\n// oxlint-disable-next-line no-unused-vars\nexport interface PaginationLinksSubscription<RT, E> {\n /**\n * The method to call when the component this subscription is attached to\n * unmounts.\n */\n [DISPOSE](): void;\n}\n\nexport interface PaginationLinksSubscriptionArgs<RT, E> {\n pages: PagedPaginationState<RT, E>;\n}\n\n/**\n * The framework-agnostic core of a pagination links component (for example the\n * `<EachLink />` component of `@warp-drive/ember`): it owns the component\n * lifecycle, while the links themselves live on the {@link PaginationLinks}\n * it exposes.\n *\n * Given the {@link PagedPaginationState} a `<Paginate />` component is driving,\n * {@link paginationLinks} derives that state's `PaginationLinks` — the numbered\n * links (with placeholders for gaps) and the relational\n * `first`/`prev`/`next`/`last` links a component yields for the consumer to\n * render. All of them read from the same shared page graph as the\n * `<Paginate />` component, so they stay in sync as pages load and the active\n * page changes.\n *\n * @since 5.9.0\n * @public\n * @hideconstructor\n */\nexport class PaginationLinksSubscription<RT, E> {\n /** @internal */\n declare private isDestroyed: boolean;\n /** @internal */\n declare private _args: PaginationLinksSubscriptionArgs<RT, E>;\n\n constructor(args: PaginationLinksSubscriptionArgs<RT, E>) {\n this._args = args;\n this.isDestroyed = false;\n this[DISPOSE] = _DISPOSE;\n }\n\n /**\n * The {@link PaginationLinks} derived from the {@link PagedPaginationState}\n * passed as an arg — the surface a links component yields to its consumer:\n * the numbered {@link PaginationLinks.links | links} (empty for cursor-based\n * collections) and the relational {@link PaginationLinks.first | first}/\n * {@link PaginationLinks.prev | prev}/{@link PaginationLinks.next | next}/\n * {@link PaginationLinks.last | last} links.\n *\n * Recomputes when the `pages` arg changes, so a component whose pagination\n * resets to a different collection derives fresh links automatically.\n */\n @memoized\n get paginationLinks(): Readonly<PaginationLinks<RT, E>> {\n return getPaginationLinks<RT, E>(this._args.pages);\n }\n}\n\n/**\n * Creates the {@link PaginationLinksSubscription} a links component (such as\n * `<EachLink />`) uses to derive its links from a {@link PagedPaginationState}.\n *\n * ```ts\n * const subscription = createPaginationLinksSubscription({ pages: paginationState });\n *\n * subscription.paginationLinks; // the derived PaginationLinks\n * subscription[DISPOSE](); // tear down when the owning component unmounts\n * ```\n *\n * @since 5.9.0\n * @public\n */\nexport function createPaginationLinksSubscription<RT, E>(\n args: PaginationLinksSubscriptionArgs<RT, E>\n): PaginationLinksSubscription<RT, E> {\n return new PaginationLinksSubscription(args);\n}\n\ninterface PrivatePaginationLinksSubscription {\n isDestroyed: boolean;\n}\n\nfunction upgradeSubscription(sub: unknown): PrivatePaginationLinksSubscription {\n return sub as PrivatePaginationLinksSubscription;\n}\n\nfunction _DISPOSE<RT, E>(this: PaginationLinksSubscription<RT, E>) {\n const self = upgradeSubscription(this);\n self.isDestroyed = true;\n}\n","import { assert } from '@warp-drive/build-config/macros';\n\nimport type { Awaitable } from '../request.ts';\nimport { getPromiseResult, setPromiseResult } from '../request.ts';\nimport { defineSignal } from './reactivity/signal.ts';\n\nconst PromiseCache = new WeakMap<Awaitable, PromiseState>();\n\n/**\n * The state of a promise in the \"pending\"\n * state. This is the default initial state.\n *\n */\nexport interface PendingPromise {\n /**\n * The status of the promise.\n *\n */\n status: 'pending';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: true;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: true;\n\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: false;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: null;\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: null;\n}\n\n/**\n * The state of a promise in the \"fulfilled\" state.\n * This is the state of a promise that has resolved\n * successfully.\n *\n */\nexport interface ResolvedPromise<T> {\n /**\n * The status of the promise.\n *\n */\n status: 'fulfilled';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: false;\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: true;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: false;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: T;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: T;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: null;\n}\n\n/**\n * The state of a promise in the \"rejected\" state.\n * This is the state of a promise that has rejected\n * with an error.\n *\n */\nexport interface RejectedPromise<E> {\n /**\n * The status of the promise.\n *\n */\n status: 'rejected';\n\n /**\n * Whether the promise is pending.\n *\n */\n isPending: false;\n\n /**\n * Whether the promise is pending.\n *\n * @deprecated use `isPending` instead\n */\n isLoading: false;\n\n /**\n * Whether the promise has resolved\n * successfully.\n *\n */\n isSuccess: false;\n\n /**\n * Whether the promise has rejected\n * with an error.\n *\n */\n isError: true;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n */\n value: null;\n\n /**\n * Once the promise has resolved, this will\n * be the value the promise resolved to.\n *\n * @deprecated use `value` instead\n */\n result: null;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n *\n * @deprecated use `reason` instead\n */\n error: E;\n\n /**\n * Once the promise has rejected, this will\n * be the error the promise rejected with.\n *\n */\n reason: E;\n}\n\n/**\n * The state of a promise. This is the type that is returned\n * from `getPromiseState`.\n *\n * See also:\n * - {@link PendingPromise}\n * - {@link ResolvedPromise}\n * - {@link RejectedPromise}\n *\n */\nexport type PromiseState<T = unknown, E = unknown> = PendingPromise | ResolvedPromise<T> | RejectedPromise<E>;\n\nconst PromiseStateProto = {};\n\n// TODO introduce a new mechanism for defining multiple properties\n// that share a common signal\ndefineSignal(PromiseStateProto, 'reason', null);\ndefineSignal(PromiseStateProto, 'value', null);\ndefineSignal(PromiseStateProto, 'result', null);\ndefineSignal(PromiseStateProto, 'error', null);\ndefineSignal(PromiseStateProto, 'status', 'pending');\ndefineSignal(PromiseStateProto, 'isPending', true);\ndefineSignal(PromiseStateProto, 'isLoading', true);\ndefineSignal(PromiseStateProto, 'isSuccess', false);\ndefineSignal(PromiseStateProto, 'isError', false);\n\nexport function createPromiseState<T, E>(promise: Promise<T> | Awaitable<T, E>): Readonly<PromiseState<T, E>> {\n const state = getPromiseResult<T, E>(promise);\n const promiseState = Object.create(PromiseStateProto) as PromiseState<T, E>;\n\n if (state) {\n if (state.isError) {\n promiseState.error = state.result;\n promiseState.reason = state.result;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n } else {\n promiseState.result = state.result;\n promiseState.value = state.result;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n }\n } else {\n void promise.then(\n (result) => {\n setPromiseResult(promise, { isError: false, result });\n promiseState.result = result;\n promiseState.value = result;\n promiseState.status = 'fulfilled';\n promiseState.isSuccess = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n },\n (error: E) => {\n setPromiseResult(promise, { isError: true, result: error });\n promiseState.error = error;\n promiseState.reason = error;\n promiseState.status = 'rejected';\n promiseState.isError = true;\n promiseState.isPending = false;\n promiseState.isLoading = false;\n }\n );\n }\n\n return promiseState;\n}\n\nconst LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');\ntype LegacyAwaitable<T, E> = { promise: Promise<T> | Awaitable<T, E>; [LegacyPromiseProxy]: true };\n\nfunction isLegacyAwaitable<T, E>(promise: object): promise is LegacyAwaitable<T, E> {\n return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;\n}\n\nfunction getPromise<T, E>(promise: Promise<T> | Awaitable<T, E> | LegacyAwaitable<T, E>): Promise<T> | Awaitable<T, E> {\n return isLegacyAwaitable(promise) ? promise.promise : promise;\n}\n\n/**\n * Returns a reactive state-machine for the provided promise or awaitable.\n *\n * Repeat calls to `getPromiseState` with the same promise will return the same state object\n * making is safe and easy to use in templates and JavaScript code to produce reactive\n * behaviors around promises.\n *\n * `getPromiseState` can be used in both JavaScript and Template contexts.\n *\n * ```ts\n * import { getPromiseState } from '@warp-drive/ember';\n *\n * const state = getPromiseState(promise);\n * ```\n *\n * For instance, we could write a getter on a component that updates whenever\n * the promise state advances or the promise changes, by combining the function\n * with the use of `@cached`\n *\n * ```ts\n * class Component {\n * @cached\n * get title() {\n * const state = getPromiseState(this.args.request);\n * if (state.isPending) {\n * return 'loading...';\n * }\n * if (state.isError) { return null; }\n * return state.result.title;\n * }\n * }\n * ```\n *\n * Or in a template as a helper:\n *\n * ```gjs\n * import { getPromiseState } from '@warp-drive/ember';\n *\n * <template>\n * {{#let (getPromiseState @request) as |state|}}\n * {{#if state.isPending}} <Spinner />\n * {{else if state.isError}} <ErrorForm @error={{state.error}} />\n * {{else}}\n * <h1>{{state.result.title}}</h1>\n * {{/if}}\n * {{/let}}\n * </template>\n * ```\n *\n * If looking to use in a template, consider also the `<Await />` component.\n *\n * See also {@link PromiseState}\n */\nexport function getPromiseState<T = unknown, E = unknown>(\n promise: Promise<T> | Awaitable<T, E>\n): Readonly<PromiseState<T, E>> {\n assert(`getPromiseState expects to be called with a promise: called with ${String(promise)}`, promise);\n const _promise = getPromise(promise);\n let state = PromiseCache.get(_promise) as PromiseState<T, E> | undefined;\n\n if (!state) {\n state = createPromiseState(_promise);\n PromiseCache.set(_promise, state);\n }\n\n return state;\n}\n"],"x_google_ignoreList":[4],"mappings":";;;;AAMA,MAAaG,eAA0CH,eAAe,OAAOI,OAAO,KAAK,CAAC;AAC1F,MAAaC,gBAA2CL,eAAe,OAAOI,OAAO,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4J3F,SAAgBE,aAAgBC,aAA8D;CAK5F,MAAMC,QAAQD,YAAY,EACxBE,WAAW,EACTC,OAAOP,aACT,EACF,CAAC;CACDD,aAAa,eAAeM,KAAK;AACnC;;;;;;AAOA,SAAgBG,aAAaC,KAAaC,KAAiC;CAGzE,OAFwCZ,cAAc,aAE/Ca,CAAW,CAACH,aAAaC,KAAKC,GAAG;AAC1C;;;;;;AAOA,SAA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