@warp-drive-mirror/core 5.10.0-alpha.16 → 5.10.0-alpha.17
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-Y-13dsHO.js.map +1 -1
- package/dist/build-config/babel-macros.d.ts +0 -5
- package/dist/build-config/canary-features.d.ts +0 -5
- package/dist/build-config/debugging.d.ts +0 -59
- package/dist/build-config/deprecations.d.ts +0 -5
- package/dist/build-config.d.ts +0 -17
- package/dist/configure.d.ts +0 -8
- package/dist/graph/-private.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{internal-BOC6nyCi.d.ts → internal-DTPBJZLO.d.ts} +2 -1
- package/dist/{internal-BOC6nyCi.d.ts.map → internal-DTPBJZLO.d.ts.map} +1 -1
- package/dist/reactive/-private.d.ts +1 -1
- package/dist/reactive.d.ts +1 -276
- package/dist/reactive.js +1 -1
- package/dist/request.d.ts +1 -9
- package/dist/signals/-leaked.d.ts +1 -15
- package/dist/signals/-leaked.d.ts.map +1 -1
- package/dist/{src-DDLNZD8D.js → src-PuYJ-RSZ.js} +1 -279
- package/dist/src-PuYJ-RSZ.js.map +1 -0
- package/dist/store/-private.d.ts +1 -1
- package/dist/store/-private.js +1 -1
- package/dist/store.d.ts +1 -6
- package/dist/types/-private.js +1 -1
- package/dist/types/cache/relationship.d.ts +0 -5
- package/dist/types/cache.d.ts +1 -6
- package/dist/types/graph.d.ts +0 -5
- package/dist/types/record.d.ts +0 -5
- package/dist/types/request.d.ts +1 -1
- package/dist/types/schema/concepts.d.ts +0 -5
- package/dist/types/schema/schema-service.d.ts +1 -6
- package/dist/types/spec/error.d.ts +0 -4
- package/dist/types/spec/json-api-raw.d.ts +0 -5
- package/dist/types.d.ts +1 -9
- package/dist/unpkg/dev/-private-BoKjsWc1.js.map +1 -1
- package/dist/unpkg/dev/index.js +1 -1
- package/dist/unpkg/dev/reactive.js +1 -1
- package/dist/unpkg/dev/runtime-DhiRXM4s.js.map +1 -1
- package/dist/unpkg/dev/{src-DKHeerUf.js → src-Dy9m6GTv.js} +1 -279
- package/dist/unpkg/dev/src-Dy9m6GTv.js.map +1 -0
- package/dist/unpkg/dev/store/-private.js +1 -1
- package/dist/unpkg/dev/types/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/-private-BoKjsWc1.js.map +1 -1
- package/dist/unpkg/dev-deprecated/index.js +1 -1
- package/dist/unpkg/dev-deprecated/reactive.js +1 -1
- package/dist/unpkg/dev-deprecated/runtime-DtHRI2Rj.js.map +1 -1
- package/dist/unpkg/dev-deprecated/{src-lyEz1lmd.js → src-ByOiBTF3.js} +1 -279
- package/dist/unpkg/dev-deprecated/src-ByOiBTF3.js.map +1 -0
- package/dist/unpkg/dev-deprecated/store/-private.js +1 -1
- package/dist/unpkg/dev-deprecated/types/-private.js +1 -1
- package/dist/unpkg/prod/-private-CRDwlN1v.js.map +1 -1
- package/dist/unpkg/prod/index.js +1 -1
- package/dist/unpkg/prod/reactive.js +1 -1
- package/dist/unpkg/prod/{src-Dagh1FmP.js → src-NuWjjfax.js} +1 -279
- package/dist/unpkg/prod/src-NuWjjfax.js.map +1 -0
- package/dist/unpkg/prod/store/-private.js +1 -1
- package/dist/unpkg/prod/types/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/-private-CRDwlN1v.js.map +1 -1
- package/dist/unpkg/prod-deprecated/index.js +1 -1
- package/dist/unpkg/prod-deprecated/reactive.js +1 -1
- package/dist/unpkg/prod-deprecated/{src-3nV2sDcO.js → src-Bt7BkX1Y.js} +1 -279
- package/dist/unpkg/prod-deprecated/src-Bt7BkX1Y.js.map +1 -0
- package/dist/unpkg/prod-deprecated/store/-private.js +1 -1
- package/dist/unpkg/prod-deprecated/types/-private.js +1 -1
- package/package.json +5 -5
- package/dist/src-DDLNZD8D.js.map +0 -1
- package/dist/unpkg/dev/src-DKHeerUf.js.map +0 -1
- package/dist/unpkg/dev-deprecated/src-lyEz1lmd.js.map +0 -1
- package/dist/unpkg/prod/src-Dagh1FmP.js.map +0 -1
- package/dist/unpkg/prod-deprecated/src-3nV2sDcO.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"-private-Y-13dsHO.js","names":["getOrSetGlobal","peekTransient","setTransient","macroCondition","getGlobalConfig","ARRAY_SIGNAL","Symbol","OBJECT_SIGNAL","setupSignals","buildConfig","hooks","wellknown","Array","registerSignals","signalHooks","register","createSignal","obj","key","WarpDrive","env","DEBUG","test","Error","consumeSignal","signal","notifySignal","createMemo","object","fn","willSyncFlushWatchers","waitFor","promise","getOrSetGlobal","ARRAY_SIGNAL","consumeSignal","createMemo","createSignal","notifySignal","OBJECT_SIGNAL","getGlobalConfig","macroCondition","INITIALIZER_PROTO","isInitializer","makeInitializer","fn","Object","assign","create","value","obj","getPrototypeOf","Signals","Symbol","upgradeWithSignals","withSignalStore","initializeSignalStore","WarpDrive","env","DEBUG","test","Error","Map","createInternalSignal","signals","key","initialValue","warpDriveSignal","context","signal","call","isStale","set","getOrCreateInternalSignal","peekInternalSignal","createInternalMemo","object","String","withFrame","memo","consumeInternalMemo","TrackingFrame","add","get","consumeInternalSignal","notifyInternalSignal","frameSignals","Set","frameFn","size","clear","parent","isMemo","globalThis","debugWarpDriveSignals","log","colorizeLines","printMemo","printSignal","lines","k","LightColors","red","green","reset","DarkColors","isLightMode","window","matchMedia","matches","RED","GREEN","RESET","EOL","Colors","colors","line","str","push","args","console","isDirty","isDirtyMemo","depth","_dirty","padStart","consumeInternalSignal","createInternalMemo","createInternalSignal","getOrCreateInternalSignal","makeInitializer","notifyInternalSignal","peekInternalSignal","withSignalStore","macroCondition","getGlobalConfig","entangleSignal","signals","obj","key","initialValue","internalSignal","entangleInitiallyStaleSignal","isStale","createSignalDescriptor","intialValue","enumerable","configurable","get","value","set","defineSignal","v","Object","defineProperty","defineNonEnumerableSignal","desc","signal","target","descriptor","WarpDrive","env","DEBUG","test","Error","undefined","arguments","length","Array","from","map","d","join","initializer","memoized","getter","memoSignal","bind","gate","_target","setter","isLocal","call","defineGate","options","assign","getPromiseResult","setPromiseResult","DOMError","defineNonEnumerableSignal","defineSignal","macroCondition","getGlobalConfig","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","WarpDrive","env","DEBUG","test","Error","refresh","usePolicy","result","status","isLoading","response","content","isSuccess","getRequestState","set","defineSignal","memoized","getRequestState","getGlobalConfig","macroCondition","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","WarpDrive","env","DEBUG","test","_localRequest","finally","retry","errorFeatures","contentFeatures","feat","latestRequest","abort","_originalRequest","_originalQuery","isOriginalRequest","e","console","log","cause","result","undefined","createRequestSubscription","upgradeSubscription","sub","self","removeEventListener","_DISPOSE","upgradeSubscription","memoized","signal","getRequestState","macroCondition","getGlobalConfig","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","applyDocument","update","links","self","WarpDrive","env","DEBUG","test","Error","currentPage","totalPages","readPageHints","firstPage","lastPage","prevPage","nextPage","isNumbered","ownNumber","page","stated","updateLinks","detachAfter","detachBefore","setPageNumber","linkFirst","linkLast","updateLinkage","lookupLinkage","setBefore","setAfter","head","tail","leftSide","rightSide","displaced","firstPageDelta","lastPageDelta","lookupLinkageForward","lookupLinkageBackwards","i","PageCache","memoized","signal","macroCondition","getGlobalConfig","g","i","n","PaginationCacheMap","Map","defaultPageHints","document","currentPage","meta","page","totalPages","PaginationCache","prototype","firstPage","isNumbered","pageHints","constructor","key","pagesCache","installPageHints","WarpDrive","env","DEBUG","test","Error","readPageHints","getPageCache","url","get","set","loadPage","request","isLoaded","isError","load","updateFirstPage","isSuccess","update","maybeFirstPage","before","pageNumber","pages","push","after","data","items","getPaginationCache","cache","clearPaginationCache","clear","i","getHref","getPaginationCache","defineSignal","memoized","macroCondition","getGlobalConfig","n","PaginationState","constructor","request","pageHints","store","requester","_adoptTarget","runMembers","Set","setup","activePageRequest","activePage","prototype","totalPages","paginationCache","pages","end","frontierEnd","page","frontierStart","push","next","after","isSuccess","has","runEnd","data","items","hasNext","Boolean","nextLink","hasPrevious","prevLink","nextRequest","url","pendingRequest","previousRequest","getPageCache","document","content","selfLink","links","self","firstLink","first","WarpDrive","env","DEBUG","test","Error","cacheKey","cache","installPageHints","initialPage","restartRun","loadPage","extendRun","dir","add","clear","_activate","existing","adoptPage","key","value","loadPrev","_extend","loadNext","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","_DISPOSE","upgradeSubscription","memoized","getPaginationLinks","DISPOSE","n","PaginationLinksSubscription","constructor","args","_args","isDestroyed","_DISPOSE","paginationLinks","pages","prototype","createPaginationLinksSubscription","upgradeSubscription","sub","self","getPromiseResult","setPromiseResult","defineSignal","macroCondition","getGlobalConfig","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","WarpDrive","env","DEBUG","test","Error","String","_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-mirror/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 * To support multiple frameworks on the same page, import\n * `@warp-drive-mirror/alien-signals/install` before each framework's `install` entry\n * point. Its hooks implement {@link SignalHooks.register}, so each framework's\n * hooks, passed to {@link registerSignals}, are added to its signals graph\n * instead of replacing it, and its memos stay up to date for every framework.\n * See [Using Ember and React on the Same Page](/guides/the-manual/cookbook/multiple-frameworks-on-one-page.md).\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 * @summary The create, consume, notify, and memo hooks a framework or TC39 signals implementation\n * supplies to `setupSignals` to make WarpDrive data reactive.\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 * An optional method that returns whether a signal consumed right now would be tracked by the\n * framework, for instance because a component is rendering.\n *\n * ***Warp*Drive** itself does not call it. Hooks that compose other implementations, such as\n * the ones `@warp-drive-mirror/alien-signals/install` configures, use it to skip work for reads that no\n * framework would track.\n */\n isTracking?: () => boolean;\n\n /**\n * An optional method, present only on hooks that compose other signals implementations into\n * their own, such as the ones `@warp-drive-mirror/alien-signals/install` configures.\n *\n * {@link registerSignals} calls it instead of replacing the configured hooks, so that a\n * framework's hooks are added alongside the ones already configured rather than replacing them.\n */\n register?: <K>(buildConfig: (options: HooksOptions) => SignalHooks<K>) => void;\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 * @summary The options passed to the `setupSignals` callback, including the well-known key WarpDrive\n * uses for an array's contents signal.\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, replacing any configured\n * before. To add a framework's hooks alongside those of other frameworks, use\n * {@link registerSignals} instead.\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 * @summary Registers the signal hooks WarpDrive uses for reactivity, built by a callback that receives\n * `HooksOptions`.\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 * Adds the hooks built by `buildConfig` to the configured signals implementation if it composes\n * other implementations, such as `@warp-drive-mirror/alien-signals`, and otherwise configures them with\n * {@link setupSignals}.\n *\n * A framework's `install` entry point calls this rather than `setupSignals`, so that importing\n * `@warp-drive-mirror/alien-signals/install` first lets every framework on the page share its signals\n * and memos.\n *\n * @example\n * ```ts\n * import { registerSignals } from '@warp-drive-mirror/core/configure';\n *\n * registerSignals(buildSignalConfig);\n * ```\n *\n * @summary Registers signal hooks with the configured composing implementation, or configures\n * them with `setupSignals` when there is none.\n * @since 5.10.0\n * @public\n * @param buildConfig - a function that takes options and returns a configuration object\n */\nexport function registerSignals<T>(buildConfig: (options: HooksOptions) => SignalHooks<T>): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n if (signalHooks?.register) {\n signalHooks.register(buildConfig);\n } else {\n setupSignals(buildConfig);\n }\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-mirror/build-config/env';\nimport { assert } from '@warp-drive-mirror/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-mirror/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-mirror/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 * @summary Reactive download progress for a request, such as bytes loaded and timing, built by lazily\n * reading its response stream.\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 that was aborted before it settled.\n *\n * A cancelled request has `status: 'cancelled'` and its `reason` is an\n * `AbortError`. `isError` is also `true`, as for a {@link RejectedRequest},\n * so check `status` or `isCancelled` to tell the two apart.\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 * @summary The reactive pending, fulfilled, rejected, or cancelled state of a request `Future`, as\n * returned by `getRequestState`.\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 = isAbortError(state.result) ? 'cancelled' : '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 = isAbortError(error) ? 'cancelled' : '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 * It returns a {@link RequestState}: a reactive object that updates as the\n * request advances. Calling it again with the same {@link Future} returns the\n * same object. Check `status` to narrow it to one of four states:\n *\n * - {@link PendingRequest} (`'pending'`) is the initial state, before the\n * request settles.\n * - {@link ResolvedRequest} (`'fulfilled'`) holds the response content on `value`.\n * - {@link RejectedRequest} (`'rejected'`) holds the error on `reason`.\n * - {@link CancelledRequest} (`'cancelled'`) is a request that was aborted.\n * `isError` is also `true` for a cancelled request, so check `status` or\n * `isCancelled` rather than `isError` if you handle it differently.\n *\n * Every state also exposes a {@link RequestLoadingState} on `loadingState`\n * for tracking the progress of the response stream.\n *\n * The [Reactive Control Flow](/guides/the-manual/reactivity/control-flow) guide shows\n * how to render request states with it, and\n * [Using The Response](/guides/the-manual/requests/using-the-response) covers the\n * `Future` it reads.\n *\n * ```ts\n * import { getRequestState } from '@warp-drive-mirror/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-mirror/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 * @param future - the request {@link Future} to track, as returned by `store.request` or `requestManager.request`\n * @return the cached {@link RequestState} for `future`\n * @summary Returns a cached, reactive state object tracking a request `Future` through pending, success,\n * error, and cancellation.\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-mirror/build-config/env';\nimport { assert } from '@warp-drive-mirror/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 *\n * @summary One autorefresh trigger for a request subscription: on reconnecting (`online`), on a timer\n * (`interval`), or on store invalidation (`invalid`).\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 *\n * @summary The accepted values for a request subscription's `autorefresh` option: a boolean or a\n * comma-separated mix of `online`, `interval`, and `invalid`.\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 *\n * @summary The online and visibility state plus a `retry` function that a request subscription exposes\n * for recovering from a failed request.\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 *\n * @summary The online, visibility, and refreshing state plus `refresh`, `reload`, and `abort` functions a\n * request subscription exposes alongside successful content.\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 *\n * @summary The arguments of the `<Request />` component: the request or query to run, autorefresh\n * options, and an optional store or subscription.\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 * @summary Options for a request subscription: the request or query to monitor and its autorefresh settings.\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 * @summary Reactive subscription that monitors a request or query, tracking online, visibility and refresh state and\n * handling autorefresh, reload and retry.\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 *\n * @summary Creates a reactive subscription to a request or query that tracks its state and handles\n * autorefresh, retry, and refresh.\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-mirror/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 * @summary Experimental: one page of a paginated collection, exposing its request, loading and error status, data,\n * and links to neighboring pages.\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 this.request = request;\n this.state = getRequestState<RT, E>(this.request);\n let content: ReactiveDocument<unknown>;\n try {\n content = (await this.request).content as ReactiveDocument<unknown>;\n } catch {\n // a rejected request is surfaced reactively through the page's state\n return null;\n }\n\n this.applyDocument(content);\n return content;\n }\n\n /**\n * Re-applies an already-loaded page from a newer request for the same page\n * (a reload, or a route-driven navigation back to it). The newer document is\n * authoritative: its links and page hints replace the ones recorded from\n * the earlier load, and the collection total is updated from it. The page\n * keeps its current request until the newer one resolves, so a page on\n * screen does not flash a loading state; a rejected request leaves the\n * page untouched.\n *\n * @internal\n */\n async update(request: Future<RT>): Promise<ReactiveDocument<unknown> | null> {\n const state = getRequestState<RT, E>(request);\n let content: ReactiveDocument<unknown>;\n try {\n content = (await request).content as ReactiveDocument<unknown>;\n } catch {\n return null;\n }\n\n this.request = request;\n this.state = state;\n this.applyDocument(content);\n return content;\n }\n\n /**\n * Records a loaded document's links and page number, and links this page\n * into the shared page graph.\n *\n * The document is authoritative for what it states: a link it names\n * explicitly (including an explicit `null`) overwrites whatever a neighbor\n * or an earlier load of this page recorded, and a link it omits is kept.\n * `next`/`prev` name the adjacent pages; `first`/`last` name the ends of\n * the collection, beyond which nothing may remain linked.\n *\n * For a numbered collection the document must also agree with the page\n * numbers: `next` is the page after this one, `prev` the page before, a\n * page without `prev` is page 1, a page without `next` is the last page,\n * `first` is page 1 and `last` is page `totalPages`. A document that\n * contradicts this is a server (or collection-mixing) bug and is asserted\n * in development, before anything is recorded from it. A cursor collection\n * has no numbers, so there its links are the only authority.\n *\n * @internal\n */\n applyDocument(content: ReactiveDocument<unknown>): void {\n const links = (content?.links ?? {}) as Record<string, unknown>;\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 // Both hints may be `0` (unknown, e.g. cursor pagination).\n const { currentPage, totalPages } = this.manager.readPageHints(content);\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 (this.manager.isNumbered) {\n // a page's number as known so far: this document's hint for this page,\n // otherwise what is recorded — its own document's hint, or the number a\n // neighbor assigned by position (in a numbered collection those are\n // consistent, so a mismatch is a contradiction either way); `0` is unknown\n const ownNumber = (page: Readonly<PageCache<RT, E>>): number => (page === this ? currentPage : page.pageNumber);\n\n assert(\n `Page ${self} is page ${currentPage} but the collection has ${totalPages} pages: it lies beyond the collection total`,\n !currentPage || !totalPages || currentPage <= totalPages\n );\n assert(\n `Page ${self} is page ${currentPage} and has no prev link but is not the first page`,\n !('prev' in links && !prev && currentPage > 1)\n );\n assert(\n `Page ${self} is page ${currentPage} of ${totalPages} and has no next link but is not the last page`,\n !('next' in links && !next && currentPage > 0 && totalPages > 0 && currentPage < totalPages)\n );\n assert(\n `Page ${self} is page ${currentPage} but its next link names page ${nextPage ? ownNumber(nextPage) : 0}, expected page ${currentPage + 1}`,\n !nextPage || !currentPage || !ownNumber(nextPage) || ownNumber(nextPage) === currentPage + 1\n );\n assert(\n `Page ${self} is page ${currentPage} but its prev link names page ${prevPage ? ownNumber(prevPage) : 0}, expected page ${currentPage - 1}`,\n !prevPage || !currentPage || !ownNumber(prevPage) || ownNumber(prevPage) === currentPage - 1\n );\n assert(\n `Page ${self} has a first link that names page ${firstPage ? ownNumber(firstPage) : 0}, expected page 1`,\n !firstPage || !ownNumber(firstPage) || ownNumber(firstPage) === 1\n );\n assert(\n `Page ${self} has a last link that names page ${lastPage ? ownNumber(lastPage) : 0}, expected the last page ${totalPages}`,\n !lastPage || !totalPages || !ownNumber(lastPage) || ownNumber(lastPage) === totalPages\n );\n assert(\n `Page ${self} has a first link to ${first} but that first page has a page linked before it`,\n !firstPage?.before\n );\n }\n\n // The page number is a hint. When the response exposes it, rely on it. When\n // absent, keep whatever relative number a neighbor already assigned via\n // `setPageNumber` rather than clobbering it.\n if (currentPage) {\n this.pageNumber = currentPage;\n }\n this.manager.totalPages = totalPages;\n\n const stated: Links = {};\n if ('first' in links) stated.first = first;\n if ('last' in links) stated.last = last;\n if ('next' in links) stated.next = next;\n if ('prev' in links) stated.prev = prev;\n this.updateLinks(stated);\n\n // An explicit `null` next/prev link, or a first/last link, marks an end\n // of the collection: nothing in the graph may extend past it, and the end\n // page has no link past it either. Detaching drops pages that no longer\n // exist (e.g. the collection shrank) from the chain; they stay cached and\n // relink if a later document reaches them. A neighbor whose own link\n // still named this page is contradicted by this newer document, so that\n // link is cleared too — links and graph must agree.\n if ('next' in links && !next) {\n const after = this.after;\n this.detachAfter();\n if (after?.prevLink === self) after.updateLinks({ prev: null });\n }\n if ('prev' in links && !prev) {\n const before = this.before;\n this.detachBefore();\n if (before?.nextLink === self) before.updateLinks({ next: null });\n }\n if (lastPage) {\n lastPage.detachAfter();\n lastPage.updateLinks({ next: null });\n }\n if (firstPage) {\n firstPage.detachBefore();\n firstPage.updateLinks({ prev: null });\n }\n\n // first/last are sparse hints: the end page belongs beyond every page\n // reachable from this one, not necessarily right beside it.\n if (firstPage) {\n firstPage.setPageNumber(1);\n if (firstPage !== this && !firstPage.after) {\n this.linkFirst(firstPage);\n }\n }\n\n if (lastPage) {\n lastPage.setPageNumber(this.manager.totalPages);\n if (lastPage !== this && !lastPage.before) {\n this.linkLast(lastPage);\n }\n }\n\n if (nextPage) {\n nextPage.setPageNumber(this.pageNumber + 1);\n nextPage.updateLinks({ prev: self });\n }\n\n if (prevPage) {\n prevPage.setPageNumber(this.pageNumber - 1);\n prevPage.updateLinks({ next: self });\n }\n\n // next/prev are adjacency: a page currently linked beside this one that\n // the document names differently stays only when its page number proves\n // it lies beyond the named neighbor (a sparse first/last placement).\n // Otherwise it is stale — e.g. a cursor that moved — and detaches.\n if (nextPage && this.after && this.after !== nextPage && this.after.pageNumber <= nextPage.pageNumber) {\n this.detachAfter();\n }\n if (prevPage && this.before && this.before !== prevPage && this.before.pageNumber >= prevPage.pageNumber) {\n this.detachBefore();\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\n /** @internal */\n detachAfter(): void {\n const after = this.after;\n if (after) {\n if (after.before === this) after.setBefore(null);\n this.setAfter(null);\n }\n }\n\n /** @internal */\n detachBefore(): void {\n const before = this.before;\n if (before) {\n if (before.after === this) before.setAfter(null);\n this.setBefore(null);\n }\n }\n\n /**\n * Links an unlinked `first` page before the earliest page reachable\n * backwards from this one that must follow it.\n *\n * @internal\n */\n linkFirst(firstPage: PageCache<RT, E>): void {\n // oxlint-disable-next-line typescript/no-this-alias\n let head: PageCache<RT, E> = this;\n while (\n head.before &&\n head.before !== firstPage &&\n (!head.before.pageNumber || head.before.pageNumber > firstPage.pageNumber)\n ) {\n head = head.before;\n }\n firstPage.updateLinkage({ after: head });\n }\n\n /**\n * Links an unlinked `last` page after the furthest page reachable forwards\n * from this one that must precede it.\n *\n * @internal\n */\n linkLast(lastPage: PageCache<RT, E>): void {\n // oxlint-disable-next-line typescript/no-this-alias\n let tail: PageCache<RT, E> = this;\n while (\n tail.after &&\n tail.after !== lastPage &&\n (!tail.after.pageNumber || !lastPage.pageNumber || tail.after.pageNumber < lastPage.pageNumber)\n ) {\n tail = tail.after;\n }\n lastPage.updateLinkage({ before: tail });\n }\n\n /**\n * Places this page between `before` and `after` in the graph (a missing side\n * is taken from the given side's current neighbor, so a single side splices\n * this page in). Pointers this page or the displaced neighbors held to their\n * old positions are cleared first, so a page moved within the graph never\n * leaves a dangling link behind that could close a cycle.\n *\n * @internal\n */\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 if (this.before !== leftSide) this.detachBefore();\n const displaced = leftSide.after;\n if (displaced && displaced !== this && displaced !== rightSide && displaced.before === leftSide) {\n displaced.setBefore(null);\n }\n leftSide.setAfter(this);\n this.setBefore(leftSide);\n }\n\n if (rightSide && rightSide !== this) {\n if (this.after !== rightSide) this.detachAfter();\n const displaced = rightSide.before;\n if (displaced && displaced !== this && displaced !== leftSide && displaced.after === rightSide) {\n displaced.setAfter(null);\n }\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 /**\n * Records the given links. Only the keys present are applied, so a caller\n * states exactly what it knows: an explicit `null` clears a link, an\n * omitted key leaves the recorded link alone.\n *\n * @internal\n */\n updateLinks = (links: Links): void => {\n if ('prev' in links) {\n this.prevLink = links.prev ?? null;\n }\n if ('next' in links) {\n this.nextLink = links.next ?? null;\n }\n if ('first' in links) {\n this.firstLink = links.first ?? null;\n }\n if ('last' in links) {\n this.lastLink = links.last ?? null;\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-mirror/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 * @summary Experimental: a function you pass to `<Paginate />` that reads `currentPage` and `totalPages` from a\n * loaded document when they are not in the default `meta` locations.\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 * @summary Experimental: the fallback page-hints function, reading `meta.page` or `meta.currentPage` and\n * `meta.totalPages` from a document, with `0` meaning unknown.\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 * @summary Experimental: the shared, app-wide store of loaded pages, page order, and `totalPages` for one paginated\n * collection, keyed by its `first` or `self` link.\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 /**\n * Loads the page at `url` with `request` when it is not loaded (or its load\n * failed), or re-applies `request`'s document when it is a newer request\n * for an already-loaded page (a reload, or navigating back to it: the newer\n * document is authoritative for the page's links and the collection total,\n * which may have changed since the first load).\n *\n * Resolves to the page once that has settled. A rejected request settles\n * too — it is surfaced through the page's state, not thrown. The promise\n * rejects only when the document contradicts the collection (see\n * {@link PageCache.applyDocument}), so the caller that triggered the load\n * is the one that hears about it.\n *\n * @internal\n */\n async loadPage(url: string, request: Future<RT> | null): Promise<Readonly<PageCache<RT, E>>> {\n const page = this.getPageCache(url);\n if ((!page.isLoaded || page.isError) && request) {\n await page.load(request);\n this.updateFirstPage(page);\n } else if (request && page.isSuccess && request !== page.request) {\n const document = await page.update(request);\n if (document) {\n this.updateFirstPage(page);\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 /**\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 // materialized (not a lazy iterable) so every link read while walking is\n // a dependency of this memo, and a consumer iterating it re-runs when the\n // graph changes\n const pages: Readonly<PageCache<RT, E>>[] = [];\n let page: Readonly<PageCache<RT, E>> | null = this.firstPage;\n while (page) {\n pages.push(page);\n page = page.after;\n }\n return pages;\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 // materialized for the same reason as `pages`\n const items: ContentItem<RT>[] = [];\n for (const page of this.pages) {\n if (page.data) {\n items.push(...(page.data as ContentItem<RT>[]));\n }\n }\n return items;\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 * @summary Experimental: returns the shared pagination cache for a collection's `first` or `self` link, creating it\n * on first use.\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 * @summary Experimental: discards every shared pagination cache, mainly so tests start from a clean state.\n * @since 5.9.0\n * @public\n */\nexport function clearPaginationCache(): void {\n PaginationCacheMap.clear();\n}\n","import { assert } from '@warp-drive-mirror/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 *\n * @summary Experimental: the `@mode` value of `<Paginate />`, either `'paged'` for a single-page view or\n * `'infinite'` for an accumulated view, which selects the yielded pagination API.\n */\nexport type PaginateMode = 'paged' | 'infinite';\n\n/**\n * The part of a {@link PaginationState} available to both navigation surfaces.\n *\n * @summary Experimental: the pagination state members available in both paged and infinite mode, namely\n * `totalPages` and `adoptPage`.\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 *\n * @summary Experimental: the pagination state `<Paginate />` yields in paged mode, exposing the active page, its\n * request, and `loadPage` for navigating to a page by URL.\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 *\n * @summary Experimental: the pagination state `<Paginate />` yields in infinite mode, exposing the accumulated\n * items and pages plus `loadNext` and `loadPrev` to extend them.\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 *\n * @summary Experimental: resolves a pagination mode to its state type, the infinite-mode state for `'infinite'`\n * and the paged-mode state otherwise.\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 * @summary Experimental: one component's pagination state over a shared collection, tracking the active page and\n * the loaded run and providing paged and infinite navigation.\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 * Only ever written through {@link extendRun} and {@link restartRun}, which\n * keep {@link runMembers} in step.\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 * Every page this component has loaded into its run — what the frontier\n * spanned each time it moved. Bounds the walk in {@link pages}: the shared\n * graph may relink a page in the run to one that another component sharing\n * the collection loaded, and that page is not part of this run until it is\n * loaded through here. Untracked bookkeeping — it only changes together with\n * the frontier signals, which carry the notification.\n *\n * @internal\n */\n declare private runMembers: Set<Readonly<PageCache<RT, E>>>;\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 this.runMembers = new Set();\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 * The run is walked through the shared graph, so it ends early when a page\n * that was in it no longer follows the page before it — a reload that showed\n * the collection now ends sooner, or that its next cursor moved. It also ends\n * before a page this component never loaded: a reload may relink a page in\n * the run to one another component sharing the collection scrolled to, and\n * that page joins this run only through {@link loadNext}.\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // materialized (not a lazy iterable) so every link and page state read\n // while walking is a dependency of this memo, and a consumer iterating it\n // re-runs when any of them changes\n const pages: Readonly<PageCache<RT, E>>[] = [];\n const end = this.frontierEnd;\n let page: Readonly<PageCache<RT, E>> | null = this.frontierStart;\n while (page) {\n pages.push(page);\n if (page === end) {\n break;\n }\n const next = page.after;\n if (!next?.isSuccess || !this.runMembers.has(next)) {\n break;\n }\n page = next;\n }\n return pages;\n }\n\n /**\n * The last page of the run {@link pages} walks — the forward frontier, or\n * the page before the first one that no longer follows in the graph or that\n * this component never loaded.\n *\n * @internal\n */\n @memoized\n get runEnd(): Readonly<PageCache<RT, E>> | null {\n let end: Readonly<PageCache<RT, E>> | null = null;\n for (const page of this.pages) {\n end = page;\n }\n return end;\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 // materialized for the same reason as `pages`\n const items: ContentItem<RT>[] = [];\n for (const page of this.pages) {\n if (page.data) {\n items.push(...(page.data as ContentItem<RT>[]));\n }\n }\n return items;\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.runEnd?.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 * and while the page sits loaded in the shared cache (another component\n * scrolled to it) but outside this run — {@link loadNext} then joins it\n * without a request of its own.\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.runEnd?.nextLink;\n if (!url) {\n return null;\n }\n return this.pendingRequest(url);\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.pendingRequest(url);\n }\n\n /**\n * The request of the page at `url` unless it already succeeded, in which\n * case there is nothing pending: the page either sits in this run, or joins\n * it on the next {@link loadNext}/{@link loadPrev} without a new request.\n *\n * @internal\n */\n private pendingRequest(url: string): Future<RT> | null {\n const page = this.paginationCache?.getPageCache(url);\n if (!page || page.isSuccess) {\n return null;\n }\n return page.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 const page = cache.getPageCache(selfLink);\n this.activePage = this.initialPage = page;\n this.restartRun(page);\n await cache.loadPage(selfLink, this.request);\n }\n\n /**\n * Moves the frontier onto a page adjacent to the run, recording it as a\n * member.\n *\n * @internal\n */\n private extendRun(dir: 'prev' | 'next', page: Readonly<PageCache<RT, E>>): void {\n this.runMembers.add(page);\n if (dir === 'next') {\n this.frontierEnd = page;\n } else {\n this.frontierStart = page;\n }\n }\n\n /**\n * Restarts the run at a single page, forgetting every earlier member.\n *\n * @internal\n */\n private restartRun(page: Readonly<PageCache<RT, E>>): void {\n this.runMembers.clear();\n this.runMembers.add(page);\n this.frontierStart = this.frontierEnd = page;\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.runEnd?.nextLink === url) {\n this.extendRun('next', page);\n } else if (this.frontierStart?.prevLink === url) {\n this.extendRun('prev', page);\n } else {\n this.restartRun(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 * In development, a document that contradicts the collection's page\n * numbers (a `next` that skips a page, a `first` that is not page 1, ...)\n * rejects instead of resolving: the graph is not updated from it.\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 // the request already resolved above, so the load settles without failing;\n // a document that contradicts the collection rejects here (see loadPage)\n const page = await cache.loadPage(selfLink, request);\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.runEnd : 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 await cache.loadPage(url, request as Future<RT>);\n } else {\n try {\n // in flight for another component sharing the collection\n await page.request;\n } catch {\n // surfaced through the page's state, handled below\n }\n }\n\n if (!page.isSuccess) {\n // the failure (or cancellation) 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 this.extendRun(dir, page);\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. In development, a document that\n * contradicts the collection's page numbers rejects instead (see\n * {@link adoptPage}).\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 await cache.loadPage(url, request as Future<RT>);\n if (!page.isSuccess) {\n // the failure (or cancellation) 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 * @summary Experimental: returns the pagination state for a request, creating it on first call and returning the\n * same instance for the same request thereafter.\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 * @summary Experimental: a numbered page link with its page number, whether it is current, its distance from the\n * active page, and `setActive` to load and show that page.\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 * @summary Experimental: a non-navigable gap marker in numbered pagination links, standing in for a range of\n * not-yet-loaded pages, usually shown as an ellipsis.\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 * @summary Experimental: a `first`, `prev`, `next`, or `last` link relative to the active page, with `setActive`\n * to load it, and the only kind of link cursor-based pagination has.\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 *\n * @summary Experimental: an entry in the numbered pagination links list, either a navigable numbered link or a\n * placeholder for a gap, told apart by `isReal`.\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 * @summary Experimental: the reactive navigation links for a pagination state, with numbered links and gap\n * placeholders plus `first`, `prev`, `next`, and `last` links for the active page.\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 * @summary Experimental: returns the navigation links for a paged pagination state, creating them on first call and\n * returning the same instance for the same state.\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 *\n * @summary Experimental: the request status flags and controls, like `isRefreshing`, `refresh`, and `reload`,\n * that `<Paginate />` yields to its content block in both modes.\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 *\n * @summary Experimental: the request controls `<Paginate />` yields to its content block in paged mode, adding\n * `loadPage` to navigate to a page by URL.\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 *\n * @summary Experimental: the request controls `<Paginate />` yields to its content block in infinite mode, adding\n * `loadNext` and `loadPrev` to extend the loaded pages.\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 *\n * @summary Experimental: the combined paged and infinite content features a pagination subscription builds, before\n * `<Paginate />` narrows them to one mode.\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 *\n * @summary Experimental: resolves a pagination mode to the content features `<Paginate />` yields, the infinite\n * set for `'infinite'` and the paged set otherwise.\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 * @summary Experimental: the lifecycle core of `<Paginate />`, owning the initial request subscription and the\n * component's pagination state.\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 * @summary Experimental: creates the subscription that manages a `<Paginate />` component's initial request\n * lifecycle and pagination state, for managing that lifecycle yourself.\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-mirror/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 * @summary Experimental: the framework-agnostic lifecycle core of a pagination links component such as\n * `<EachLink />`, exposing the navigation links for a paged pagination state.\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 * @summary Experimental: creates the subscription a pagination links component such as `<EachLink />` uses to\n * derive navigation links from a paged pagination state.\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-mirror/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 * @summary The `getPromiseState` state for a promise that has not yet settled, with `isPending` true and\n * no value or reason.\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 * @summary The `getPromiseState` state for a promise that resolved, with `isSuccess` true and the\n * resolved `value`.\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 * @summary The `getPromiseState` state for a promise that rejected, with `isError` true and the\n * rejection `reason`.\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 * @summary The reactive pending, fulfilled, or rejected state of a promise, as returned by\n * `getPromiseState`.\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 * The [Async as Reactive State](/guides/the-manual/reactivity/derivation) guide shows\n * how to use it in place of tracked loading and error state.\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-mirror/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-mirror/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 *\n * @summary Returns a cached, reactive state object tracking whether a promise is pending, fulfilled, or\n * rejected, for use in JS or templates.\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,MAAaK,eAA0CL,eAAe,OAAOM,OAAO,KAAK,CAAC;AAC1F,MAAaC,gBAA2CP,eAAe,OAAOM,OAAO,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwL3F,SAAgBE,aAAgBC,aAA8D;CAK5F,MAAMC,QAAQD,YAAY,EACxBE,WAAW,EACTC,OAAOP,aACT,EACF,CAAC;CACDH,aAAa,eAAeQ,KAAK;AACnC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgBG,gBAAmBJ,aAA8D;CAC/F,MAAMK,cAAkCb,cAAc,aAAa;CACnE,IAAIa,aAAaC,UACfD,YAAYC,SAASN,WAAW;MAEhCD,aAAaC,WAAW;AAE5B;;;;;;AAOA,SAAgBO,aAAaC,KAAaC,KAAiC;CACzE,MAAMJ,cAAkCb,cAAc,aAAa;CACnEE,eAAAC,gBAAA,CAAA,CAAAe,UAAAC,IAAAC,KAAA,OAAAC,SAAA;EAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,6BAA6B;CAAA,EAAA,CAAET,WAAW;CACjD,OAAOA,YAAYE,aAAaC,KAAKC,GAAG;AAC1C;;;;;;AAOA,SAAgBM,cAAcC,QAAyB;CACrD,MAAMX,cAAkCb,cA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;AA6DA,SAAgBoB,gBACdpB,SAC8B;CAC9BN,eAAAC,gBAAA,CAAA,CAAA0B,UAAAC,IAAAC,KAAA,OAAAC,SAAA;EAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,oEAAoEC,OAAO1B,OAAO,GAAG;CAAA,EAAA,CAAEA,OAAO;CACrG,MAAM2B,WAAWR,WAAWnB,OAAO;CACnC,IAAIC,QAAQL,aAAagC,IAAID,QAAQ;CAErC,IAAI,CAAC1B,OAAO;EACVA,QAAQF,mBAAmB4B,QAAQ;EACnC/B,aAAaiC,IAAIF,UAAU1B,KAAK;CAClC;CAEA,OAAOA;AACT"}
|
|
1
|
+
{"version":3,"file":"-private-Y-13dsHO.js","names":["getOrSetGlobal","peekTransient","setTransient","macroCondition","getGlobalConfig","ARRAY_SIGNAL","Symbol","OBJECT_SIGNAL","setupSignals","buildConfig","hooks","wellknown","Array","registerSignals","signalHooks","register","createSignal","obj","key","WarpDrive","env","DEBUG","test","Error","consumeSignal","signal","notifySignal","createMemo","object","fn","willSyncFlushWatchers","waitFor","promise","getOrSetGlobal","ARRAY_SIGNAL","consumeSignal","createMemo","createSignal","notifySignal","OBJECT_SIGNAL","getGlobalConfig","macroCondition","INITIALIZER_PROTO","isInitializer","makeInitializer","fn","Object","assign","create","value","obj","getPrototypeOf","Signals","Symbol","upgradeWithSignals","withSignalStore","initializeSignalStore","WarpDrive","env","DEBUG","test","Error","Map","createInternalSignal","signals","key","initialValue","warpDriveSignal","context","signal","call","isStale","set","getOrCreateInternalSignal","peekInternalSignal","createInternalMemo","object","String","withFrame","memo","consumeInternalMemo","TrackingFrame","add","get","consumeInternalSignal","notifyInternalSignal","frameSignals","Set","frameFn","size","clear","parent","isMemo","globalThis","debugWarpDriveSignals","log","colorizeLines","printMemo","printSignal","lines","k","LightColors","red","green","reset","DarkColors","isLightMode","window","matchMedia","matches","RED","GREEN","RESET","EOL","Colors","colors","line","str","push","args","console","isDirty","isDirtyMemo","depth","_dirty","padStart","consumeInternalSignal","createInternalMemo","createInternalSignal","getOrCreateInternalSignal","makeInitializer","notifyInternalSignal","peekInternalSignal","withSignalStore","macroCondition","getGlobalConfig","entangleSignal","signals","obj","key","initialValue","internalSignal","entangleInitiallyStaleSignal","isStale","createSignalDescriptor","intialValue","enumerable","configurable","get","value","set","defineSignal","v","Object","defineProperty","defineNonEnumerableSignal","desc","signal","target","descriptor","WarpDrive","env","DEBUG","test","Error","undefined","arguments","length","Array","from","map","d","join","initializer","memoized","getter","memoSignal","bind","gate","_target","setter","isLocal","call","defineGate","options","assign","getPromiseResult","setPromiseResult","DOMError","defineNonEnumerableSignal","defineSignal","macroCondition","getGlobalConfig","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","WarpDrive","env","DEBUG","test","Error","refresh","usePolicy","result","status","isLoading","response","content","isSuccess","getRequestState","set","defineSignal","memoized","getRequestState","getGlobalConfig","macroCondition","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","WarpDrive","env","DEBUG","test","_localRequest","finally","retry","errorFeatures","contentFeatures","feat","latestRequest","abort","_originalRequest","_originalQuery","isOriginalRequest","e","console","log","cause","result","undefined","createRequestSubscription","upgradeSubscription","sub","self","removeEventListener","_DISPOSE","upgradeSubscription","memoized","signal","getRequestState","macroCondition","getGlobalConfig","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","applyDocument","update","links","self","WarpDrive","env","DEBUG","test","Error","currentPage","totalPages","readPageHints","firstPage","lastPage","prevPage","nextPage","isNumbered","ownNumber","page","stated","updateLinks","detachAfter","detachBefore","setPageNumber","linkFirst","linkLast","updateLinkage","lookupLinkage","setBefore","setAfter","head","tail","leftSide","rightSide","displaced","firstPageDelta","lastPageDelta","lookupLinkageForward","lookupLinkageBackwards","i","PageCache","memoized","signal","macroCondition","getGlobalConfig","g","i","n","PaginationCacheMap","Map","defaultPageHints","document","currentPage","meta","page","totalPages","PaginationCache","prototype","firstPage","isNumbered","pageHints","constructor","key","pagesCache","installPageHints","WarpDrive","env","DEBUG","test","Error","readPageHints","getPageCache","url","get","set","loadPage","request","isLoaded","isError","load","updateFirstPage","isSuccess","update","maybeFirstPage","before","pageNumber","pages","push","after","data","items","getPaginationCache","cache","clearPaginationCache","clear","i","getHref","getPaginationCache","defineSignal","memoized","macroCondition","getGlobalConfig","n","PaginationState","constructor","request","pageHints","store","requester","_adoptTarget","runMembers","Set","setup","activePageRequest","activePage","prototype","totalPages","paginationCache","pages","end","frontierEnd","page","frontierStart","push","next","after","isSuccess","has","runEnd","data","items","hasNext","Boolean","nextLink","hasPrevious","prevLink","nextRequest","url","pendingRequest","previousRequest","getPageCache","document","content","selfLink","links","self","firstLink","first","WarpDrive","env","DEBUG","test","Error","cacheKey","cache","installPageHints","initialPage","restartRun","loadPage","extendRun","dir","add","clear","_activate","existing","adoptPage","key","value","loadPrev","_extend","loadNext","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","_DISPOSE","upgradeSubscription","memoized","getPaginationLinks","DISPOSE","n","PaginationLinksSubscription","constructor","args","_args","isDestroyed","_DISPOSE","paginationLinks","pages","prototype","createPaginationLinksSubscription","upgradeSubscription","sub","self","getPromiseResult","setPromiseResult","defineSignal","macroCondition","getGlobalConfig","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","WarpDrive","env","DEBUG","test","Error","String","_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-mirror/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 * To support multiple frameworks on the same page, import\n * `@warp-drive-mirror/alien-signals/install` before each framework's `install` entry\n * point. Its hooks implement {@link SignalHooks.register}, so each framework's\n * hooks, passed to {@link registerSignals}, are added to its signals graph\n * instead of replacing it, and its memos stay up to date for every framework.\n * See [Using Ember and React on the Same Page](/guides/the-manual/cookbook/multiple-frameworks-on-one-page.md).\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 * @summary The create, consume, notify, and memo hooks a framework or TC39 signals implementation\n * supplies to `setupSignals` to make WarpDrive data reactive.\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 * An optional method that returns whether a signal consumed right now would be tracked by the\n * framework, for instance because a component is rendering.\n *\n * ***Warp*Drive** itself does not call it. Hooks that compose other implementations, such as\n * the ones `@warp-drive-mirror/alien-signals/install` configures, use it to skip work for reads that no\n * framework would track.\n */\n isTracking?: () => boolean;\n\n /**\n * An optional method, present only on hooks that compose other signals implementations into\n * their own, such as the ones `@warp-drive-mirror/alien-signals/install` configures.\n *\n * {@link registerSignals} calls it instead of replacing the configured hooks, so that a\n * framework's hooks are added alongside the ones already configured rather than replacing them.\n */\n register?: <K>(buildConfig: (options: HooksOptions) => SignalHooks<K>) => void;\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 * @summary The options passed to the `setupSignals` callback, including the well-known key WarpDrive\n * uses for an array's contents signal.\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, replacing any configured\n * before. To add a framework's hooks alongside those of other frameworks, use\n * {@link registerSignals} instead.\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 * @summary Registers the signal hooks WarpDrive uses for reactivity, built by a callback that receives\n * `HooksOptions`.\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 * Adds the hooks built by `buildConfig` to the configured signals implementation if it composes\n * other implementations, such as `@warp-drive-mirror/alien-signals`, and otherwise configures them with\n * {@link setupSignals}.\n *\n * A framework's `install` entry point calls this rather than `setupSignals`, so that importing\n * `@warp-drive-mirror/alien-signals/install` first lets every framework on the page share its signals\n * and memos.\n *\n * @example\n * ```ts\n * import { registerSignals } from '@warp-drive-mirror/core/configure';\n *\n * registerSignals(buildSignalConfig);\n * ```\n *\n * @summary Registers signal hooks with the configured composing implementation, or configures\n * them with `setupSignals` when there is none.\n * @since 5.10.0\n * @public\n * @param buildConfig - a function that takes options and returns a configuration object\n */\nexport function registerSignals<T>(buildConfig: (options: HooksOptions) => SignalHooks<T>): void {\n const signalHooks: SignalHooks | null = peekTransient('signalHooks');\n if (signalHooks?.register) {\n signalHooks.register(buildConfig);\n } else {\n setupSignals(buildConfig);\n }\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-mirror/build-config/env';\nimport { assert } from '@warp-drive-mirror/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-mirror/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-mirror/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 * @summary Reactive download progress for a request, such as bytes loaded and timing, built by lazily\n * reading its response stream.\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 that was aborted before it settled.\n *\n * A cancelled request has `status: 'cancelled'` and its `reason` is an\n * `AbortError`. `isError` is also `true`, as for a {@link RejectedRequest},\n * so check `status` or `isCancelled` to tell the two apart.\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 * @summary The reactive pending, fulfilled, rejected, or cancelled state of a request `Future`, as\n * returned by `getRequestState`.\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 = isAbortError(state.result) ? 'cancelled' : '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 = isAbortError(error) ? 'cancelled' : '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 * It returns a {@link RequestState}: a reactive object that updates as the\n * request advances. Calling it again with the same {@link Future} returns the\n * same object. Check `status` to narrow it to one of four states:\n *\n * - {@link PendingRequest} (`'pending'`) is the initial state, before the\n * request settles.\n * - {@link ResolvedRequest} (`'fulfilled'`) holds the response content on `value`.\n * - {@link RejectedRequest} (`'rejected'`) holds the error on `reason`.\n * - {@link CancelledRequest} (`'cancelled'`) is a request that was aborted.\n * `isError` is also `true` for a cancelled request, so check `status` or\n * `isCancelled` rather than `isError` if you handle it differently.\n *\n * Every state also exposes a {@link RequestLoadingState} on `loadingState`\n * for tracking the progress of the response stream.\n *\n * The [Reactive Control Flow](/guides/the-manual/reactivity/control-flow) guide shows\n * how to render request states with it, and\n * [Using The Response](/guides/the-manual/requests/using-the-response) covers the\n * `Future` it reads.\n *\n * ```ts\n * import { getRequestState } from '@warp-drive-mirror/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-mirror/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 * @param future - the request {@link Future} to track, as returned by `store.request` or `requestManager.request`\n * @return the cached {@link RequestState} for `future`\n * @summary Returns a cached, reactive state object tracking a request `Future` through pending, success,\n * error, and cancellation.\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-mirror/build-config/env';\nimport { assert } from '@warp-drive-mirror/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 *\n * @summary One autorefresh trigger for a request subscription: on reconnecting (`online`), on a timer\n * (`interval`), or on store invalidation (`invalid`).\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 *\n * @summary The accepted values for a request subscription's `autorefresh` option: a boolean or a\n * comma-separated mix of `online`, `interval`, and `invalid`.\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 *\n * @summary The online and visibility state plus a `retry` function that a request subscription exposes\n * for recovering from a failed request.\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 *\n * @summary The online, visibility, and refreshing state plus `refresh`, `reload`, and `abort` functions a\n * request subscription exposes alongside successful content.\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 *\n * @summary The arguments of the `<Request />` component: the request or query to run, autorefresh\n * options, and an optional store or subscription.\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 * @summary Options for a request subscription: the request or query to monitor and its autorefresh settings.\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 * @summary Reactive subscription that monitors a request or query, tracking online, visibility and refresh state and\n * handling autorefresh, reload and retry.\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 *\n * @summary Creates a reactive subscription to a request or query that tracks its state and handles\n * autorefresh, retry, and refresh.\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-mirror/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 * @summary Experimental: one page of a paginated collection, exposing its request, loading and error status, data,\n * and links to neighboring pages.\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 this.request = request;\n this.state = getRequestState<RT, E>(this.request);\n let content: ReactiveDocument<unknown>;\n try {\n content = (await this.request).content as ReactiveDocument<unknown>;\n } catch {\n // a rejected request is surfaced reactively through the page's state\n return null;\n }\n\n this.applyDocument(content);\n return content;\n }\n\n /**\n * Re-applies an already-loaded page from a newer request for the same page\n * (a reload, or a route-driven navigation back to it). The newer document is\n * authoritative: its links and page hints replace the ones recorded from\n * the earlier load, and the collection total is updated from it. The page\n * keeps its current request until the newer one resolves, so a page on\n * screen does not flash a loading state; a rejected request leaves the\n * page untouched.\n *\n * @internal\n */\n async update(request: Future<RT>): Promise<ReactiveDocument<unknown> | null> {\n const state = getRequestState<RT, E>(request);\n let content: ReactiveDocument<unknown>;\n try {\n content = (await request).content as ReactiveDocument<unknown>;\n } catch {\n return null;\n }\n\n this.request = request;\n this.state = state;\n this.applyDocument(content);\n return content;\n }\n\n /**\n * Records a loaded document's links and page number, and links this page\n * into the shared page graph.\n *\n * The document is authoritative for what it states: a link it names\n * explicitly (including an explicit `null`) overwrites whatever a neighbor\n * or an earlier load of this page recorded, and a link it omits is kept.\n * `next`/`prev` name the adjacent pages; `first`/`last` name the ends of\n * the collection, beyond which nothing may remain linked.\n *\n * For a numbered collection the document must also agree with the page\n * numbers: `next` is the page after this one, `prev` the page before, a\n * page without `prev` is page 1, a page without `next` is the last page,\n * `first` is page 1 and `last` is page `totalPages`. A document that\n * contradicts this is a server (or collection-mixing) bug and is asserted\n * in development, before anything is recorded from it. A cursor collection\n * has no numbers, so there its links are the only authority.\n *\n * @internal\n */\n applyDocument(content: ReactiveDocument<unknown>): void {\n const links = (content?.links ?? {}) as Record<string, unknown>;\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 // Both hints may be `0` (unknown, e.g. cursor pagination).\n const { currentPage, totalPages } = this.manager.readPageHints(content);\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 (this.manager.isNumbered) {\n // a page's number as known so far: this document's hint for this page,\n // otherwise what is recorded — its own document's hint, or the number a\n // neighbor assigned by position (in a numbered collection those are\n // consistent, so a mismatch is a contradiction either way); `0` is unknown\n const ownNumber = (page: Readonly<PageCache<RT, E>>): number => (page === this ? currentPage : page.pageNumber);\n\n assert(\n `Page ${self} is page ${currentPage} but the collection has ${totalPages} pages: it lies beyond the collection total`,\n !currentPage || !totalPages || currentPage <= totalPages\n );\n assert(\n `Page ${self} is page ${currentPage} and has no prev link but is not the first page`,\n !('prev' in links && !prev && currentPage > 1)\n );\n assert(\n `Page ${self} is page ${currentPage} of ${totalPages} and has no next link but is not the last page`,\n !('next' in links && !next && currentPage > 0 && totalPages > 0 && currentPage < totalPages)\n );\n assert(\n `Page ${self} is page ${currentPage} but its next link names page ${nextPage ? ownNumber(nextPage) : 0}, expected page ${currentPage + 1}`,\n !nextPage || !currentPage || !ownNumber(nextPage) || ownNumber(nextPage) === currentPage + 1\n );\n assert(\n `Page ${self} is page ${currentPage} but its prev link names page ${prevPage ? ownNumber(prevPage) : 0}, expected page ${currentPage - 1}`,\n !prevPage || !currentPage || !ownNumber(prevPage) || ownNumber(prevPage) === currentPage - 1\n );\n assert(\n `Page ${self} has a first link that names page ${firstPage ? ownNumber(firstPage) : 0}, expected page 1`,\n !firstPage || !ownNumber(firstPage) || ownNumber(firstPage) === 1\n );\n assert(\n `Page ${self} has a last link that names page ${lastPage ? ownNumber(lastPage) : 0}, expected the last page ${totalPages}`,\n !lastPage || !totalPages || !ownNumber(lastPage) || ownNumber(lastPage) === totalPages\n );\n assert(\n `Page ${self} has a first link to ${first} but that first page has a page linked before it`,\n !firstPage?.before\n );\n }\n\n // The page number is a hint. When the response exposes it, rely on it. When\n // absent, keep whatever relative number a neighbor already assigned via\n // `setPageNumber` rather than clobbering it.\n if (currentPage) {\n this.pageNumber = currentPage;\n }\n this.manager.totalPages = totalPages;\n\n const stated: Links = {};\n if ('first' in links) stated.first = first;\n if ('last' in links) stated.last = last;\n if ('next' in links) stated.next = next;\n if ('prev' in links) stated.prev = prev;\n this.updateLinks(stated);\n\n // An explicit `null` next/prev link, or a first/last link, marks an end\n // of the collection: nothing in the graph may extend past it, and the end\n // page has no link past it either. Detaching drops pages that no longer\n // exist (e.g. the collection shrank) from the chain; they stay cached and\n // relink if a later document reaches them. A neighbor whose own link\n // still named this page is contradicted by this newer document, so that\n // link is cleared too — links and graph must agree.\n if ('next' in links && !next) {\n const after = this.after;\n this.detachAfter();\n if (after?.prevLink === self) after.updateLinks({ prev: null });\n }\n if ('prev' in links && !prev) {\n const before = this.before;\n this.detachBefore();\n if (before?.nextLink === self) before.updateLinks({ next: null });\n }\n if (lastPage) {\n lastPage.detachAfter();\n lastPage.updateLinks({ next: null });\n }\n if (firstPage) {\n firstPage.detachBefore();\n firstPage.updateLinks({ prev: null });\n }\n\n // first/last are sparse hints: the end page belongs beyond every page\n // reachable from this one, not necessarily right beside it.\n if (firstPage) {\n firstPage.setPageNumber(1);\n if (firstPage !== this && !firstPage.after) {\n this.linkFirst(firstPage);\n }\n }\n\n if (lastPage) {\n lastPage.setPageNumber(this.manager.totalPages);\n if (lastPage !== this && !lastPage.before) {\n this.linkLast(lastPage);\n }\n }\n\n if (nextPage) {\n nextPage.setPageNumber(this.pageNumber + 1);\n nextPage.updateLinks({ prev: self });\n }\n\n if (prevPage) {\n prevPage.setPageNumber(this.pageNumber - 1);\n prevPage.updateLinks({ next: self });\n }\n\n // next/prev are adjacency: a page currently linked beside this one that\n // the document names differently stays only when its page number proves\n // it lies beyond the named neighbor (a sparse first/last placement).\n // Otherwise it is stale — e.g. a cursor that moved — and detaches.\n if (nextPage && this.after && this.after !== nextPage && this.after.pageNumber <= nextPage.pageNumber) {\n this.detachAfter();\n }\n if (prevPage && this.before && this.before !== prevPage && this.before.pageNumber >= prevPage.pageNumber) {\n this.detachBefore();\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\n /** @internal */\n detachAfter(): void {\n const after = this.after;\n if (after) {\n if (after.before === this) after.setBefore(null);\n this.setAfter(null);\n }\n }\n\n /** @internal */\n detachBefore(): void {\n const before = this.before;\n if (before) {\n if (before.after === this) before.setAfter(null);\n this.setBefore(null);\n }\n }\n\n /**\n * Links an unlinked `first` page before the earliest page reachable\n * backwards from this one that must follow it.\n *\n * @internal\n */\n linkFirst(firstPage: PageCache<RT, E>): void {\n // oxlint-disable-next-line typescript/no-this-alias\n let head: PageCache<RT, E> = this;\n while (\n head.before &&\n head.before !== firstPage &&\n (!head.before.pageNumber || head.before.pageNumber > firstPage.pageNumber)\n ) {\n head = head.before;\n }\n firstPage.updateLinkage({ after: head });\n }\n\n /**\n * Links an unlinked `last` page after the furthest page reachable forwards\n * from this one that must precede it.\n *\n * @internal\n */\n linkLast(lastPage: PageCache<RT, E>): void {\n // oxlint-disable-next-line typescript/no-this-alias\n let tail: PageCache<RT, E> = this;\n while (\n tail.after &&\n tail.after !== lastPage &&\n (!tail.after.pageNumber || !lastPage.pageNumber || tail.after.pageNumber < lastPage.pageNumber)\n ) {\n tail = tail.after;\n }\n lastPage.updateLinkage({ before: tail });\n }\n\n /**\n * Places this page between `before` and `after` in the graph (a missing side\n * is taken from the given side's current neighbor, so a single side splices\n * this page in). Pointers this page or the displaced neighbors held to their\n * old positions are cleared first, so a page moved within the graph never\n * leaves a dangling link behind that could close a cycle.\n *\n * @internal\n */\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 if (this.before !== leftSide) this.detachBefore();\n const displaced = leftSide.after;\n if (displaced && displaced !== this && displaced !== rightSide && displaced.before === leftSide) {\n displaced.setBefore(null);\n }\n leftSide.setAfter(this);\n this.setBefore(leftSide);\n }\n\n if (rightSide && rightSide !== this) {\n if (this.after !== rightSide) this.detachAfter();\n const displaced = rightSide.before;\n if (displaced && displaced !== this && displaced !== leftSide && displaced.after === rightSide) {\n displaced.setAfter(null);\n }\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 /**\n * Records the given links. Only the keys present are applied, so a caller\n * states exactly what it knows: an explicit `null` clears a link, an\n * omitted key leaves the recorded link alone.\n *\n * @internal\n */\n updateLinks = (links: Links): void => {\n if ('prev' in links) {\n this.prevLink = links.prev ?? null;\n }\n if ('next' in links) {\n this.nextLink = links.next ?? null;\n }\n if ('first' in links) {\n this.firstLink = links.first ?? null;\n }\n if ('last' in links) {\n this.lastLink = links.last ?? null;\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-mirror/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 * @summary Experimental: a function you pass to `<Paginate />` that reads `currentPage` and `totalPages` from a\n * loaded document when they are not in the default `meta` locations.\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 * @summary Experimental: the fallback page-hints function, reading `meta.page` or `meta.currentPage` and\n * `meta.totalPages` from a document, with `0` meaning unknown.\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 * @summary Experimental: the shared, app-wide store of loaded pages, page order, and `totalPages` for one paginated\n * collection, keyed by its `first` or `self` link.\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 /**\n * Loads the page at `url` with `request` when it is not loaded (or its load\n * failed), or re-applies `request`'s document when it is a newer request\n * for an already-loaded page (a reload, or navigating back to it: the newer\n * document is authoritative for the page's links and the collection total,\n * which may have changed since the first load).\n *\n * Resolves to the page once that has settled. A rejected request settles\n * too — it is surfaced through the page's state, not thrown. The promise\n * rejects only when the document contradicts the collection (see\n * {@link PageCache.applyDocument}), so the caller that triggered the load\n * is the one that hears about it.\n *\n * @internal\n */\n async loadPage(url: string, request: Future<RT> | null): Promise<Readonly<PageCache<RT, E>>> {\n const page = this.getPageCache(url);\n if ((!page.isLoaded || page.isError) && request) {\n await page.load(request);\n this.updateFirstPage(page);\n } else if (request && page.isSuccess && request !== page.request) {\n const document = await page.update(request);\n if (document) {\n this.updateFirstPage(page);\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 /**\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 // materialized (not a lazy iterable) so every link read while walking is\n // a dependency of this memo, and a consumer iterating it re-runs when the\n // graph changes\n const pages: Readonly<PageCache<RT, E>>[] = [];\n let page: Readonly<PageCache<RT, E>> | null = this.firstPage;\n while (page) {\n pages.push(page);\n page = page.after;\n }\n return pages;\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 // materialized for the same reason as `pages`\n const items: ContentItem<RT>[] = [];\n for (const page of this.pages) {\n if (page.data) {\n items.push(...(page.data as ContentItem<RT>[]));\n }\n }\n return items;\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 * @summary Experimental: returns the shared pagination cache for a collection's `first` or `self` link, creating it\n * on first use.\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 * @summary Experimental: discards every shared pagination cache, mainly so tests start from a clean state.\n * @since 5.9.0\n * @public\n */\nexport function clearPaginationCache(): void {\n PaginationCacheMap.clear();\n}\n","import { assert } from '@warp-drive-mirror/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 *\n * @summary Experimental: the `@mode` value of `<Paginate />`, either `'paged'` for a single-page view or\n * `'infinite'` for an accumulated view, which selects the yielded pagination API.\n */\nexport type PaginateMode = 'paged' | 'infinite';\n\n/**\n * The part of a {@link PaginationState} available to both navigation surfaces.\n *\n * @summary Experimental: the pagination state members available in both paged and infinite mode, namely\n * `totalPages` and `adoptPage`.\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 *\n * @summary Experimental: the pagination state `<Paginate />` yields in paged mode, exposing the active page, its\n * request, and `loadPage` for navigating to a page by URL.\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 *\n * @summary Experimental: the pagination state `<Paginate />` yields in infinite mode, exposing the accumulated\n * items and pages plus `loadNext` and `loadPrev` to extend them.\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 *\n * @summary Experimental: resolves a pagination mode to its state type, the infinite-mode state for `'infinite'`\n * and the paged-mode state otherwise.\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 * @summary Experimental: one component's pagination state over a shared collection, tracking the active page and\n * the loaded run and providing paged and infinite navigation.\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 * Only ever written through {@link extendRun} and {@link restartRun}, which\n * keep {@link runMembers} in step.\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 * Every page this component has loaded into its run — what the frontier\n * spanned each time it moved. Bounds the walk in {@link pages}: the shared\n * graph may relink a page in the run to one that another component sharing\n * the collection loaded, and that page is not part of this run until it is\n * loaded through here. Untracked bookkeeping — it only changes together with\n * the frontier signals, which carry the notification.\n *\n * @internal\n */\n declare private runMembers: Set<Readonly<PageCache<RT, E>>>;\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 this.runMembers = new Set();\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 * The run is walked through the shared graph, so it ends early when a page\n * that was in it no longer follows the page before it — a reload that showed\n * the collection now ends sooner, or that its next cursor moved. It also ends\n * before a page this component never loaded: a reload may relink a page in\n * the run to one another component sharing the collection scrolled to, and\n * that page joins this run only through {@link loadNext}.\n */\n @memoized\n get pages(): Iterable<Readonly<PageCache<RT, E>>> {\n // materialized (not a lazy iterable) so every link and page state read\n // while walking is a dependency of this memo, and a consumer iterating it\n // re-runs when any of them changes\n const pages: Readonly<PageCache<RT, E>>[] = [];\n const end = this.frontierEnd;\n let page: Readonly<PageCache<RT, E>> | null = this.frontierStart;\n while (page) {\n pages.push(page);\n if (page === end) {\n break;\n }\n const next = page.after;\n if (!next?.isSuccess || !this.runMembers.has(next)) {\n break;\n }\n page = next;\n }\n return pages;\n }\n\n /**\n * The last page of the run {@link pages} walks — the forward frontier, or\n * the page before the first one that no longer follows in the graph or that\n * this component never loaded.\n *\n * @internal\n */\n @memoized\n get runEnd(): Readonly<PageCache<RT, E>> | null {\n let end: Readonly<PageCache<RT, E>> | null = null;\n for (const page of this.pages) {\n end = page;\n }\n return end;\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 // materialized for the same reason as `pages`\n const items: ContentItem<RT>[] = [];\n for (const page of this.pages) {\n if (page.data) {\n items.push(...(page.data as ContentItem<RT>[]));\n }\n }\n return items;\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.runEnd?.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 * and while the page sits loaded in the shared cache (another component\n * scrolled to it) but outside this run — {@link loadNext} then joins it\n * without a request of its own.\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.runEnd?.nextLink;\n if (!url) {\n return null;\n }\n return this.pendingRequest(url);\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.pendingRequest(url);\n }\n\n /**\n * The request of the page at `url` unless it already succeeded, in which\n * case there is nothing pending: the page either sits in this run, or joins\n * it on the next {@link loadNext}/{@link loadPrev} without a new request.\n *\n * @internal\n */\n private pendingRequest(url: string): Future<RT> | null {\n const page = this.paginationCache?.getPageCache(url);\n if (!page || page.isSuccess) {\n return null;\n }\n return page.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 const page = cache.getPageCache(selfLink);\n this.activePage = this.initialPage = page;\n this.restartRun(page);\n await cache.loadPage(selfLink, this.request);\n }\n\n /**\n * Moves the frontier onto a page adjacent to the run, recording it as a\n * member.\n *\n * @internal\n */\n private extendRun(dir: 'prev' | 'next', page: Readonly<PageCache<RT, E>>): void {\n this.runMembers.add(page);\n if (dir === 'next') {\n this.frontierEnd = page;\n } else {\n this.frontierStart = page;\n }\n }\n\n /**\n * Restarts the run at a single page, forgetting every earlier member.\n *\n * @internal\n */\n private restartRun(page: Readonly<PageCache<RT, E>>): void {\n this.runMembers.clear();\n this.runMembers.add(page);\n this.frontierStart = this.frontierEnd = page;\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.runEnd?.nextLink === url) {\n this.extendRun('next', page);\n } else if (this.frontierStart?.prevLink === url) {\n this.extendRun('prev', page);\n } else {\n this.restartRun(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 * In development, a document that contradicts the collection's page\n * numbers (a `next` that skips a page, a `first` that is not page 1, ...)\n * rejects instead of resolving: the graph is not updated from it.\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 // the request already resolved above, so the load settles without failing;\n // a document that contradicts the collection rejects here (see loadPage)\n const page = await cache.loadPage(selfLink, request);\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.runEnd : 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 await cache.loadPage(url, request as Future<RT>);\n } else {\n try {\n // in flight for another component sharing the collection\n await page.request;\n } catch {\n // surfaced through the page's state, handled below\n }\n }\n\n if (!page.isSuccess) {\n // the failure (or cancellation) 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 this.extendRun(dir, page);\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. In development, a document that\n * contradicts the collection's page numbers rejects instead (see\n * {@link adoptPage}).\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 await cache.loadPage(url, request as Future<RT>);\n if (!page.isSuccess) {\n // the failure (or cancellation) 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 * @summary Experimental: returns the pagination state for a request, creating it on first call and returning the\n * same instance for the same request thereafter.\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 * @summary Experimental: a numbered page link with its page number, whether it is current, its distance from the\n * active page, and `setActive` to load and show that page.\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 * @summary Experimental: a non-navigable gap marker in numbered pagination links, standing in for a range of\n * not-yet-loaded pages, usually shown as an ellipsis.\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 * @summary Experimental: a `first`, `prev`, `next`, or `last` link relative to the active page, with `setActive`\n * to load it, and the only kind of link cursor-based pagination has.\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 *\n * @summary Experimental: an entry in the numbered pagination links list, either a navigable numbered link or a\n * placeholder for a gap, told apart by `isReal`.\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 * @summary Experimental: the reactive navigation links for a pagination state, with numbered links and gap\n * placeholders plus `first`, `prev`, `next`, and `last` links for the active page.\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 * @summary Experimental: returns the navigation links for a paged pagination state, creating them on first call and\n * returning the same instance for the same state.\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 *\n * @summary Experimental: the request status flags and controls, like `isRefreshing`, `refresh`, and `reload`,\n * that `<Paginate />` yields to its content block in both modes.\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 *\n * @summary Experimental: the request controls `<Paginate />` yields to its content block in paged mode, adding\n * `loadPage` to navigate to a page by URL.\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 *\n * @summary Experimental: the request controls `<Paginate />` yields to its content block in infinite mode, adding\n * `loadNext` and `loadPrev` to extend the loaded pages.\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 *\n * @summary Experimental: the combined paged and infinite content features a pagination subscription builds, before\n * `<Paginate />` narrows them to one mode.\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 *\n * @summary Experimental: resolves a pagination mode to the content features `<Paginate />` yields, the infinite\n * set for `'infinite'` and the paged set otherwise.\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 * @summary Experimental: the lifecycle core of `<Paginate />`, owning the initial request subscription and the\n * component's pagination state.\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 * @summary Experimental: creates the subscription that manages a `<Paginate />` component's initial request\n * lifecycle and pagination state, for managing that lifecycle yourself.\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-mirror/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 * @summary Experimental: the framework-agnostic lifecycle core of a pagination links component such as\n * `<EachLink />`, exposing the navigation links for a paged pagination state.\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 * @summary Experimental: creates the subscription a pagination links component such as `<EachLink />` uses to\n * derive navigation links from a paged pagination state.\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-mirror/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 * @summary The `getPromiseState` state for a promise that has not yet settled, with `isPending` true and\n * no value or reason.\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 * @summary The `getPromiseState` state for a promise that resolved, with `isSuccess` true and the\n * resolved `value`.\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 * @summary The `getPromiseState` state for a promise that rejected, with `isError` true and the\n * rejection `reason`.\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 * @summary The reactive pending, fulfilled, or rejected state of a promise, as returned by\n * `getPromiseState`.\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 * The [Async as Reactive State](/guides/the-manual/reactivity/derivation) guide shows\n * how to use it in place of tracked loading and error state.\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-mirror/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-mirror/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 *\n * @summary Returns a cached, reactive state object tracking whether a promise is pending, fulfilled, or\n * rejected, for use in JS or templates.\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"],"ignoreList":[4],"mappings":";;;;;AAMA,MAAaK,eAA0CL,eAAe,OAAOM,OAAO,KAAK,CAAC;AAC1F,MAAaC,gBAA2CP,eAAe,OAAOM,OAAO,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwL3F,SAAgBE,aAAgBC,aAA8D;CAK5F,MAAMC,QAAQD,YAAY,EACxBE,WAAW,EACTC,OAAOP,aACT,EACF,CAAC;CACDH,aAAa,eAAeQ,KAAK;AACnC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgBG,gBAAmBJ,aAA8D;CAC/F,MAAMK,cAAkCb,cAAc,aAAa;CACnE,IAAIa,aAAaC,UACfD,YAAYC,SAASN,WAAW;MAEhCD,aAAaC,WAAW;AAE5B;;;;;;AAOA,SAAgBO,aAAaC,KAAaC,KAAiC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