@gears-frontx/react 0.2.0-alpha.0 → 0.2.0-alpha.15

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/testing.cjs CHANGED
@@ -38,19 +38,22 @@ __export(testing_exports, {
38
38
  module.exports = __toCommonJS(testing_exports);
39
39
 
40
40
  // src/queryClient.tsx
41
- var import_react = __toESM(require("react"), 1);
41
+ var import_react2 = __toESM(require("react"), 1);
42
42
  var import_react_query = require("@tanstack/react-query");
43
43
  var import_framework2 = require("@gears-frontx/framework");
44
44
 
45
45
  // src/hooks/QueryCache.ts
46
46
  var import_framework = require("@gears-frontx/framework");
47
47
 
48
+ // src/hooks/useLatest.ts
49
+ var import_react = require("react");
50
+
48
51
  // src/queryClient.tsx
49
52
  var import_jsx_runtime = require("react/jsx-runtime");
50
53
  var APP_QUERY_CLIENT_SYMBOL = /* @__PURE__ */ Symbol.for("frontx:query-cache:app-client");
51
54
  var APP_QUERY_CLIENT_RESOLVER_SYMBOL = /* @__PURE__ */ Symbol.for("frontx:query-cache:app-client-resolver");
52
- var FrontXQueryClientContext = (0, import_react.createContext)(void 0);
53
- var useCommitEffect = typeof globalThis.window === "undefined" ? import_react.useEffect : import_react.useLayoutEffect;
55
+ var FrontXQueryClientContext = (0, import_react2.createContext)(void 0);
56
+ var useCommitEffect = typeof globalThis.window === "undefined" ? import_react2.useEffect : import_react2.useLayoutEffect;
54
57
  function resolveFrontXQueryClient(app) {
55
58
  const clientApp = app;
56
59
  return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();
@@ -59,7 +62,7 @@ function bootstrapFrontXQueryClient(app) {
59
62
  return resolveFrontXQueryClient(app);
60
63
  }
61
64
  function useOptionalFrontXQueryClient() {
62
- return (0, import_react.useContext)(FrontXQueryClientContext);
65
+ return (0, import_react2.useContext)(FrontXQueryClientContext);
63
66
  }
64
67
 
65
68
  // src/testing.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/testing.ts","../src/queryClient.tsx","../src/hooks/QueryCache.ts"],"sourcesContent":["/**\n * Test-only entry for @gears-frontx/react.\n *\n * Utilities here are intended for Vitest (or similar) suites that need access\n * to query-client wiring without importing package internals directly.\n */\n\n// @cpt-dod:cpt-frontx-dod-react-bindings-provider:p1\n\n// @cpt-begin:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\nexport {\n bootstrapFrontXQueryClient,\n resolveFrontXQueryClient,\n useOptionalFrontXQueryClient,\n} from './queryClient';\n\n/** App-layer tests must import this from `@gears-frontx/react/testing`, not `@gears-frontx/framework/testing`. */\nexport { describeBootstrapMfeContract } from '@gears-frontx/framework/testing';\nexport type {\n BootstrapMfeResolveArgs,\n BootstrapMfeTestSpecOptions,\n} from '@gears-frontx/framework/testing';\n// @cpt-end:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\n","import React, {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\nimport {\n QueryClientContext,\n QueryClientProvider,\n type QueryClient,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseInfiniteQuery,\n useSuspenseQuery,\n type MutationFunctionContext,\n} from '@tanstack/react-query';\nimport {\n subscribeQueryCacheRuntimeChanged,\n type EndpointDescriptor,\n type FrontXApp,\n} from '@gears-frontx/framework';\nimport type { ApiQueryOverrides } from './hooks/useApiQuery';\nimport type {\n ApiInfiniteQueryOptions,\n ApiInfiniteQueryPageContext,\n} from './hooks/useApiInfiniteQuery';\nimport type { UseApiMutationOptions } from './hooks/useApiMutation';\nimport { createQueryCache, type MutationCallbackContext, type QueryCacheKey } from './hooks/QueryCache';\n\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-query-provider:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-query:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-react-query-client-symbols\nconst APP_QUERY_CLIENT_SYMBOL = Symbol.for('frontx:query-cache:app-client');\nconst APP_QUERY_CLIENT_RESOLVER_SYMBOL = Symbol.for('frontx:query-cache:app-client-resolver');\nconst APP_QUERY_CLIENT_ACTIVATOR_SYMBOL = Symbol.for('frontx:query-cache:app-client-activator');\n\ntype QueryClientApp = FrontXApp & {\n [APP_QUERY_CLIENT_SYMBOL]?: QueryClient;\n [APP_QUERY_CLIENT_RESOLVER_SYMBOL]?: () => QueryClient | undefined;\n [APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?: () => QueryClient | undefined;\n};\n\nconst FrontXQueryClientContext = createContext<QueryClient | undefined>(undefined);\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-react-query-client-symbols\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-resolve-app-query-client\ntype RuntimeAwareEndpointDescriptor<TData> = EndpointDescriptor<TData> & {\n fetch(options?: { signal?: AbortSignal; staleTime?: number }): Promise<TData>;\n};\n\ntype AppResolvedQueryClient = {\n app: FrontXApp;\n queryClient: QueryClient;\n};\n\nconst useCommitEffect = typeof globalThis.window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function resolveFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();\n}\n\nexport function hasFrontXQueryClientActivator(app: FrontXApp): boolean {\n return typeof (app as QueryClientApp)[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL] === 'function';\n}\n\nexport function activateFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?.();\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-resolve-app-query-client\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-imperative-cache-bootstrap\n/**\n * Imperatively invalidates cache entries for `target` on the QueryClient bound to `app`.\n * Use from non-React code (e.g. MFE actions); in components prefer `useQueryCache().invalidate`.\n */\nexport async function invalidateQueryCacheForApp(\n app: FrontXApp,\n target: EndpointDescriptor<unknown> | QueryCacheKey\n): Promise<void> {\n const queryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (!queryClient) {\n throw new Error(\n '[invalidateQueryCacheForApp] No QueryClient on app. Ensure queryCache() or queryCacheShared() is in the plugin chain.'\n );\n }\n await createQueryCache(queryClient).invalidate(target);\n}\n\n/** Resolves the app-bound QueryClient without triggering plugin activation during render. */\nexport function bootstrapFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n return resolveFrontXQueryClient(app);\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-imperative-cache-bootstrap\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-use-bootstrapped-query-client\nexport function useBootstrappedFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const fromApp = useMemo(() => bootstrapFrontXQueryClient(app), [app]);\n const [eventResolvedClient, setEventResolvedClient] = useState<AppResolvedQueryClient | undefined>(\n undefined\n );\n const queryClient =\n fromApp ?? (eventResolvedClient?.app === app ? eventResolvedClient.queryClient : undefined);\n\n useCommitEffect(() => {\n if (fromApp || !hasFrontXQueryClientActivator(app)) {\n return;\n }\n\n const tryResolveQueryClient = () => {\n const nextQueryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (nextQueryClient) {\n setEventResolvedClient((current) => {\n if (current?.app === app && current.queryClient === nextQueryClient) {\n return current;\n }\n\n return {\n app,\n queryClient: nextQueryClient,\n };\n });\n }\n };\n\n // Only activate after commit so abandoned renders cannot leak retainers/listeners.\n tryResolveQueryClient();\n\n const subscription = subscribeQueryCacheRuntimeChanged(() => {\n tryResolveQueryClient();\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [app, fromApp]);\n\n return queryClient;\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-use-bootstrapped-query-client\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-frontx-query-client-provider\nexport function FrontXQueryClientProvider({\n queryClient,\n children,\n}: Readonly<{\n queryClient: QueryClient | undefined;\n children: React.ReactNode;\n}>) {\n if (!queryClient) {\n return (\n <FrontXQueryClientContext.Provider value={undefined}>\n <QueryClientContext.Provider value={undefined}>{children}</QueryClientContext.Provider>\n </FrontXQueryClientContext.Provider>\n );\n }\n\n return (\n <FrontXQueryClientContext.Provider value={queryClient}>\n <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\n </FrontXQueryClientContext.Provider>\n );\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-frontx-query-client-provider\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-query-client-context-hooks\nexport function useOptionalFrontXQueryClient(): QueryClient | undefined {\n return useContext(FrontXQueryClientContext);\n}\n\nexport function useRequiredFrontXQueryClient(): QueryClient {\n const queryClient = useOptionalFrontXQueryClient();\n if (!queryClient) {\n throw new Error(\n '[FrontXProvider] No query cache available. Add queryCache() or queryCacheShared() to your plugin composition.'\n );\n }\n\n return queryClient;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-query-client-context-hooks\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-descriptor-fetch-stale-helpers\nfunction buildPageContext<TPage>(\n page: TPage,\n pages: readonly TPage[],\n descriptor: EndpointDescriptor<TPage>,\n descriptors: readonly EndpointDescriptor<TPage>[]\n): ApiInfiniteQueryPageContext<TPage> {\n return {\n page,\n pages,\n descriptor,\n descriptors,\n };\n}\n\nfunction normalizeFetchStaleTime(staleTime: unknown): number | undefined {\n if (staleTime === 'static') {\n return Number.POSITIVE_INFINITY;\n }\n\n return typeof staleTime === 'number' ? staleTime : undefined;\n}\n\nfunction resolveFetchStaleTime<TData>(\n queryClient: QueryClient,\n descriptor: EndpointDescriptor<TData>,\n overrideStaleTime?: number\n): number | undefined {\n return normalizeFetchStaleTime(\n overrideStaleTime ??\n descriptor.staleTime ??\n queryClient.getDefaultOptions().queries?.staleTime\n );\n}\n\nfunction fetchDescriptor<TData>(\n descriptor: EndpointDescriptor<TData>,\n options?: { signal?: AbortSignal; staleTime?: number }\n): Promise<TData> {\n return (descriptor as RuntimeAwareEndpointDescriptor<TData>).fetch(options);\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-descriptor-fetch-stale-helpers\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-query\nexport function useFrontXQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(queryClient, descriptor, overrides?.staleTime);\n const result = useQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n staleTime: overrides?.staleTime ?? descriptor.staleTime,\n gcTime: overrides?.gcTime ?? descriptor.gcTime,\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n refetch: result.refetch,\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-query\nexport function useFrontXSuspenseQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(queryClient, descriptor, overrides?.staleTime);\n const result = useSuspenseQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n staleTime: overrides?.staleTime ?? descriptor.staleTime,\n gcTime: overrides?.gcTime ?? descriptor.gcTime,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-infinite-query\nexport function useFrontXInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(queryClient, pageParam, options.staleTime),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n staleTime: options.staleTime ?? options.initialPage.staleTime,\n gcTime: options.gcTime ?? options.initialPage.gcTime,\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-infinite-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-infinite-query\nexport function useFrontXSuspenseInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useSuspenseInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(queryClient, pageParam, options.staleTime),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n staleTime: options.staleTime ?? options.initialPage.staleTime,\n gcTime: options.gcTime ?? options.initialPage.gcTime,\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-infinite-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-delegate-frontx-use-mutation\nexport function useFrontXMutation<\n TData = unknown,\n TError = Error,\n TVariables = void,\n TContext = unknown,\n>(\n options: UseApiMutationOptions<TData, TError, TVariables, TContext>,\n callbackCtx: MutationCallbackContext\n) {\n useRequiredFrontXQueryClient();\n\n const latestRef = React.useRef({ options, callbackCtx });\n latestRef.current = { options, callbackCtx };\n const fetchAbortControllersRef = React.useRef<Set<AbortController>>(new Set());\n\n React.useEffect(() => {\n const fetchAbortControllers = fetchAbortControllersRef.current;\n return () => {\n if (latestRef.current.options.abortOnUnmount) {\n for (const controller of fetchAbortControllers) {\n controller.abort();\n }\n fetchAbortControllers.clear();\n }\n };\n }, []);\n\n const mutationFn = React.useCallback((variables: TVariables, context: MutationFunctionContext) => {\n const cancelOnSupersede = latestRef.current.options.cancelOnSupersede;\n if (cancelOnSupersede) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n\n const controller = new AbortController();\n fetchAbortControllersRef.current.add(controller);\n\n const librarySignal = (context as MutationFunctionContext & { signal?: AbortSignal }).signal;\n if (cancelOnSupersede && librarySignal) {\n if (librarySignal.aborted) {\n controller.abort();\n } else {\n librarySignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return latestRef.current.options.endpoint\n .fetch(variables, { signal: controller.signal })\n .finally(() => {\n fetchAbortControllersRef.current.delete(controller);\n });\n }, []);\n\n const onMutate = React.useCallback((variables: TVariables, _context: MutationFunctionContext) => {\n const current = latestRef.current;\n if (!current.options.onMutate) {\n return undefined as TContext;\n }\n\n return current.options.onMutate(variables, current.callbackCtx);\n }, []);\n\n const onSuccess = React.useCallback((data: TData, variables: TVariables, context: TContext | undefined) => {\n const current = latestRef.current;\n return current.options.onSuccess?.(data, variables, context, current.callbackCtx);\n }, []);\n\n const onError = React.useCallback((error: TError, variables: TVariables, context: TContext | undefined) => {\n const current = latestRef.current;\n return current.options.onError?.(error, variables, context, current.callbackCtx);\n }, []);\n\n const onSettled = React.useCallback((\n data: TData | undefined,\n error: TError | null,\n variables: TVariables,\n context: TContext | undefined\n ) => {\n const current = latestRef.current;\n return current.options.onSettled?.(\n data,\n error,\n variables,\n context,\n current.callbackCtx\n );\n }, []);\n\n const mutation = useMutation<TData, TError, TVariables, TContext>({\n mutationFn,\n onMutate: options.onMutate ? onMutate : undefined,\n onSuccess: options.onSuccess ? onSuccess : undefined,\n onError: options.onError ? onError : undefined,\n onSettled: options.onSettled ? onSettled : undefined,\n });\n\n return {\n mutate: mutation.mutate as (variables: TVariables) => void,\n mutateAsync: mutation.mutateAsync as (variables: TVariables) => Promise<TData>,\n isPending: mutation.isPending,\n error: mutation.error,\n data: mutation.data,\n reset: mutation.reset,\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-delegate-frontx-use-mutation\n","/**\n * QueryCache — restricted interface for interacting with the shared QueryClient.\n *\n * MFEs and screen-set components access the cache only through this sanctioned\n * public interface. It is injected as { queryCache } into useApiMutation\n * callbacks and also returned by useQueryCache() for controlled imperative\n * cache access.\n */\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-create-query-cache\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n\nimport type { EndpointDescriptor } from '@gears-frontx/framework';\nimport { eventBus } from '@gears-frontx/framework';\nimport { type QueryClient, type QueryState } from '@tanstack/react-query';\n\nexport type QueryCacheKey = readonly unknown[];\nexport type QueryCacheRefetchMode = 'active' | 'inactive' | 'all' | 'none';\nexport type QueryCacheInvalidateTarget =\n | EndpointDescriptor<unknown>\n | QueryCacheKey\n | null\n | undefined;\n\nexport interface QueryCacheState<TData = unknown, TError = Error> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n fetchFailureCount: number;\n fetchFailureReason: TError | null;\n fetchStatus: 'fetching' | 'paused' | 'idle';\n isInvalidated: boolean;\n status: 'pending' | 'error' | 'success';\n}\n\nexport type QueryCacheInvalidateFilters = {\n queryKey?: QueryCacheInvalidateTarget;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n};\n\ntype QueryCacheUpdater<T> = T | ((old: T | undefined) => T | undefined);\n\ntype CacheInvalidateEvent = {\n queryKey: QueryCacheKey;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n source?: string;\n};\n\ntype CacheSetEvent = {\n queryKey: QueryCacheKey;\n dataOrUpdater: QueryCacheUpdater<unknown>;\n source?: string;\n};\n\ntype CacheRemoveEvent = {\n queryKey: QueryCacheKey;\n source?: string;\n};\n\nconst QUERY_CLIENT_BROADCAST_TARGET = Symbol.for('frontx:query-cache:broadcast-target');\nconst QUERY_CLIENT_BROADCAST_COUNTER = Symbol.for('frontx:query-cache:broadcast-counter');\n\ntype QueryClientWithMetadata = QueryClient & {\n [QUERY_CLIENT_BROADCAST_TARGET]?: string;\n};\n\ntype QueryClientCounterHost = typeof globalThis & {\n [QUERY_CLIENT_BROADCAST_COUNTER]?: number;\n};\n\nfunction emitCacheEvent(event: string, payload: unknown): void {\n (eventBus.emit as (eventType: string, payload: unknown) => void)(event, payload);\n}\n\nfunction ensureBroadcastSource(queryClient: QueryClient): string {\n const clientWithMetadata = queryClient as QueryClientWithMetadata;\n const existingSource = clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET];\n if (typeof existingSource === 'string' && existingSource.length > 0) {\n return existingSource;\n }\n\n const host = globalThis as QueryClientCounterHost;\n const nextCounter = (host[QUERY_CLIENT_BROADCAST_COUNTER] ?? 0) + 1;\n host[QUERY_CLIENT_BROADCAST_COUNTER] = nextCounter;\n\n const source = `query-cache-${nextCounter}`;\n clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET] = source;\n return source;\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-resolve-key\nexport function resolveKey(target: EndpointDescriptor<unknown> | QueryCacheKey): readonly unknown[] {\n if (\n target !== null &&\n typeof target === 'object' &&\n !Array.isArray(target) &&\n 'key' in target &&\n 'fetch' in target &&\n Array.isArray(target.key) &&\n typeof target.fetch === 'function'\n ) {\n return target.key;\n }\n\n return target as readonly unknown[];\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-resolve-key\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\nexport interface QueryCache {\n get<T>(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined;\n getState<TData = unknown, TError = Error>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey\n ): QueryCacheState<TData, TError> | undefined;\n set<T>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey,\n dataOrUpdater: T | ((old: T | undefined) => T | undefined)\n ): void;\n cancel(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidate(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidateMany(filters?: QueryCacheInvalidateFilters | null): Promise<void>;\n remove(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): void;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\nexport interface MutationCallbackContext {\n queryCache: QueryCache;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\n\nfunction toQueryUpdater<T>(\n dataOrUpdater: QueryCacheUpdater<T>\n): (old: T | undefined) => T | undefined {\n if (typeof dataOrUpdater === 'function') {\n return dataOrUpdater as (old: T | undefined) => T | undefined;\n }\n\n return () => dataOrUpdater;\n}\n\nfunction mapQueryState<TData, TError = Error>(\n state: QueryState<TData, TError>\n): QueryCacheState<TData, TError> {\n return {\n data: state.data,\n dataUpdatedAt: state.dataUpdatedAt,\n error: state.error,\n errorUpdatedAt: state.errorUpdatedAt,\n fetchFailureCount: state.fetchFailureCount,\n fetchFailureReason: state.fetchFailureReason,\n fetchStatus: state.fetchStatus,\n isInvalidated: state.isInvalidated,\n status: state.status,\n };\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-create-query-cache\nexport function createQueryCache(queryClient: QueryClient): QueryCache {\n return {\n get: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined => {\n return queryClient.getQueryData<T>(resolveKey(key));\n },\n getState: <TData = unknown, TError = Error>(key: EndpointDescriptor<unknown> | QueryCacheKey) => {\n const state = queryClient.getQueryState<TData, TError>(resolveKey(key));\n return state ? mapQueryState(state) : undefined;\n },\n set: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey, dataOrUpdater: QueryCacheUpdater<T>): void => {\n const resolvedKey = resolveKey(key);\n queryClient.setQueryData<T>(resolvedKey, toQueryUpdater(dataOrUpdater));\n emitCacheEvent('cache/set', {\n queryKey: resolvedKey,\n dataOrUpdater: dataOrUpdater as QueryCacheUpdater<unknown>,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheSetEvent);\n },\n cancel: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n return queryClient.cancelQueries({ queryKey: resolveKey(key) });\n },\n invalidate: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n const resolvedKey = resolveKey(key);\n const result = queryClient.invalidateQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/invalidate', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n invalidateMany: (filters): Promise<void> => {\n if (filters?.queryKey == null) {\n return Promise.resolve();\n }\n\n const resolvedKey = resolveKey(filters.queryKey);\n if (!Array.isArray(resolvedKey) || resolvedKey.length === 0) {\n return Promise.resolve();\n }\n\n const payload = {\n ...filters,\n queryKey: resolvedKey,\n };\n const result = queryClient.invalidateQueries(payload);\n emitCacheEvent('cache/invalidate', {\n ...payload,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n remove: (key: EndpointDescriptor<unknown> | QueryCacheKey): void => {\n const resolvedKey = resolveKey(key);\n queryClient.removeQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/remove', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheRemoveEvent);\n },\n };\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-create-query-cache\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAOO;AACP,yBAUO;AACP,IAAAA,oBAIO;;;ACVP,uBAAyB;;;ADmJjB;AAzHR,IAAM,0BAA0B,uBAAO,IAAI,+BAA+B;AAC1E,IAAM,mCAAmC,uBAAO,IAAI,wCAAwC;AAS5F,IAAM,+BAA2B,4BAAuC,MAAS;AAajF,IAAM,kBAAkB,OAAO,WAAW,WAAW,cAAc,yBAAY;AAExE,SAAS,yBAAyB,KAAyC;AAChF,QAAM,YAAY;AAClB,SAAO,UAAU,uBAAuB,KAAK,UAAU,gCAAgC,IAAI;AAC7F;AA+BO,SAAS,2BAA2B,KAAyC;AAClF,SAAO,yBAAyB,GAAG;AACrC;AA0EO,SAAS,+BAAwD;AACtE,aAAO,yBAAW,wBAAwB;AAC5C;;;AD/JA,qBAA6C;","names":["import_framework"]}
1
+ {"version":3,"sources":["../src/testing.ts","../src/queryClient.tsx","../src/hooks/QueryCache.ts","../src/hooks/useLatest.ts"],"sourcesContent":["/**\n * Test-only entry for @gears-frontx/react.\n *\n * Utilities here are intended for Vitest (or similar) suites that need access\n * to query-client wiring without importing package internals directly.\n */\n\n// @cpt-dod:cpt-frontx-dod-react-bindings-provider:p1\n\n// @cpt-begin:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\nexport {\n bootstrapFrontXQueryClient,\n resolveFrontXQueryClient,\n useOptionalFrontXQueryClient,\n} from './queryClient';\n\n/** App-layer tests must import this from `@gears-frontx/react/testing`, not `@gears-frontx/framework/testing`. */\nexport { describeBootstrapMfeContract } from '@gears-frontx/framework/testing';\nexport type {\n BootstrapMfeResolveArgs,\n BootstrapMfeTestSpecOptions,\n} from '@gears-frontx/framework/testing';\n// @cpt-end:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\n","import React, {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\nimport {\n QueryClientContext,\n QueryClientProvider,\n type QueryClient,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseInfiniteQuery,\n useSuspenseQuery,\n type MutationFunctionContext,\n} from '@tanstack/react-query';\nimport {\n readQueryCacheScopeGeneration,\n recordQueryCacheScopeWriteDropped,\n subscribeQueryCacheRuntimeChanged,\n type EndpointDescriptor,\n type FrontXApp,\n} from '@gears-frontx/framework';\nimport type { ApiQueryOverrides, ApiSuspenseQueryOverrides } from './hooks/useApiQuery';\nimport type {\n ApiInfiniteQueryOptions,\n ApiInfiniteQueryPageContext,\n ApiSuspenseInfiniteQueryOptions,\n} from './hooks/useApiInfiniteQuery';\nimport type { UseApiMutationOptions } from './hooks/useApiMutation';\nimport {\n createQueryCache,\n type MutationCallbackContext,\n type QueryCache,\n type QueryCacheKey,\n} from './hooks/QueryCache';\nimport { useLatest } from './hooks/useLatest';\n\nconst APP_QUERY_CLIENT_SYMBOL = Symbol.for('frontx:query-cache:app-client');\nconst APP_QUERY_CLIENT_RESOLVER_SYMBOL = Symbol.for('frontx:query-cache:app-client-resolver');\nconst APP_QUERY_CLIENT_ACTIVATOR_SYMBOL = Symbol.for('frontx:query-cache:app-client-activator');\n\ntype QueryClientApp = FrontXApp & {\n [APP_QUERY_CLIENT_SYMBOL]?: QueryClient;\n [APP_QUERY_CLIENT_RESOLVER_SYMBOL]?: () => QueryClient | undefined;\n [APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?: () => QueryClient | undefined;\n};\n\nconst FrontXQueryClientContext = createContext<QueryClient | undefined>(undefined);\n\ntype RuntimeAwareEndpointDescriptor<TData> = EndpointDescriptor<TData> & {\n fetch(options?: { signal?: AbortSignal; staleTime?: number }): Promise<TData>;\n};\n\ntype AppResolvedQueryClient = {\n app: FrontXApp;\n queryClient: QueryClient;\n};\n\nconst useCommitEffect = typeof globalThis.window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function resolveFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();\n}\n\nexport function hasFrontXQueryClientActivator(app: FrontXApp): boolean {\n return typeof (app as QueryClientApp)[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL] === 'function';\n}\n\nexport function activateFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?.();\n}\n\n/**\n * Imperatively invalidates cache entries for `target` on the QueryClient bound to `app`.\n * Use from non-React code (e.g. MFE actions); in components prefer `useQueryCache().invalidate`.\n */\nexport async function invalidateQueryCacheForApp(\n app: FrontXApp,\n target: EndpointDescriptor<unknown> | QueryCacheKey\n): Promise<void> {\n const queryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (!queryClient) {\n throw new Error(\n '[invalidateQueryCacheForApp] No QueryClient on app. Ensure queryCache() or queryCacheShared() is in the plugin chain.'\n );\n }\n await createQueryCache(queryClient).invalidate(target);\n}\n\n/** Resolves the app-bound QueryClient without triggering plugin activation during render. */\nexport function bootstrapFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n return resolveFrontXQueryClient(app);\n}\n\nexport function useBootstrappedFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const fromApp = useMemo(() => bootstrapFrontXQueryClient(app), [app]);\n const [eventResolvedClient, setEventResolvedClient] = useState<AppResolvedQueryClient | undefined>(\n undefined\n );\n const queryClient =\n fromApp ?? (eventResolvedClient?.app === app ? eventResolvedClient.queryClient : undefined);\n\n useCommitEffect(() => {\n if (fromApp || !hasFrontXQueryClientActivator(app)) {\n return;\n }\n\n const tryResolveQueryClient = () => {\n const nextQueryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (nextQueryClient) {\n setEventResolvedClient((current) => {\n if (current?.app === app && current.queryClient === nextQueryClient) {\n return current;\n }\n\n return {\n app,\n queryClient: nextQueryClient,\n };\n });\n }\n };\n\n // Only activate after commit so abandoned renders cannot leak retainers/listeners.\n tryResolveQueryClient();\n\n const subscription = subscribeQueryCacheRuntimeChanged(() => {\n tryResolveQueryClient();\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [app, fromApp]);\n\n return queryClient;\n}\n\nexport function FrontXQueryClientProvider({\n queryClient,\n children,\n}: Readonly<{\n queryClient: QueryClient | undefined;\n children: React.ReactNode;\n}>) {\n if (!queryClient) {\n return (\n <FrontXQueryClientContext.Provider value={undefined}>\n <QueryClientContext.Provider value={undefined}>{children}</QueryClientContext.Provider>\n </FrontXQueryClientContext.Provider>\n );\n }\n\n return (\n <FrontXQueryClientContext.Provider value={queryClient}>\n <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\n </FrontXQueryClientContext.Provider>\n );\n}\n\nexport function useOptionalFrontXQueryClient(): QueryClient | undefined {\n return useContext(FrontXQueryClientContext);\n}\n\nexport function useRequiredFrontXQueryClient(): QueryClient {\n const queryClient = useOptionalFrontXQueryClient();\n if (!queryClient) {\n throw new Error(\n '[FrontXProvider] No query cache available. Add queryCache() or queryCacheShared() to your plugin composition.'\n );\n }\n\n return queryClient;\n}\n\nfunction buildPageContext<TPage>(\n page: TPage,\n pages: readonly TPage[],\n descriptor: EndpointDescriptor<TPage>,\n descriptors: readonly EndpointDescriptor<TPage>[]\n): ApiInfiniteQueryPageContext<TPage> {\n return {\n page,\n pages,\n descriptor,\n descriptors,\n };\n}\n\nfunction normalizeFetchStaleTime(staleTime: unknown): number | undefined {\n if (staleTime === 'static') {\n return Number.POSITIVE_INFINITY;\n }\n\n // A function staleTime is resolved per query by TanStack; 0 keeps the fetch\n // cache from serving a response older than the query would accept.\n if (typeof staleTime === 'function') {\n return 0;\n }\n\n return typeof staleTime === 'number' ? staleTime : undefined;\n}\n\n/**\n * The staleTime the shared fetch cache uses, resolved the way TanStack\n * resolves it for the query: call site, then descriptor, then the\n * QueryClient defaults for the query key (global defaults with every\n * matching setQueryDefaults prefix spread over them).\n */\nfunction resolveFetchStaleTime<TData>(\n queryClient: QueryClient,\n queryKey: readonly unknown[],\n descriptor: EndpointDescriptor<TData>,\n overrideStaleTime?: number\n): number | undefined {\n const clientDefaults = {\n ...queryClient.getDefaultOptions().queries,\n ...queryClient.getQueryDefaults(queryKey),\n };\n return normalizeFetchStaleTime(\n overrideStaleTime ?? descriptor.staleTime ?? clientDefaults.staleTime\n );\n}\n\n/**\n * staleTime/gcTime for a query, with only the keys that are set. An explicit\n * `undefined` would override the QueryClient defaults (TanStack spreads the\n * query options over them), so a screen that remounts would refetch instead of\n * painting from cache.\n */\nfunction cacheTimeOptions(\n staleTime: number | undefined,\n gcTime: number | undefined\n): { staleTime?: number; gcTime?: number } {\n return {\n ...(staleTime === undefined ? {} : { staleTime }),\n ...(gcTime === undefined ? {} : { gcTime }),\n };\n}\n\nfunction fetchDescriptor<TData>(\n descriptor: EndpointDescriptor<TData>,\n options?: { signal?: AbortSignal; staleTime?: number }\n): Promise<TData> {\n return (descriptor as RuntimeAwareEndpointDescriptor<TData>).fetch(options);\n}\n\nexport function useFrontXQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(\n queryClient,\n descriptor.key,\n descriptor,\n overrides?.staleTime\n );\n const result = useQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n ...cacheTimeOptions(\n overrides?.staleTime ?? descriptor.staleTime,\n overrides?.gcTime ?? descriptor.gcTime\n ),\n ...(overrides?.enabled === undefined ? {} : { enabled: overrides.enabled }),\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n refetch: result.refetch,\n };\n}\n\nexport function useFrontXSuspenseQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiSuspenseQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(\n queryClient,\n descriptor.key,\n descriptor,\n overrides?.staleTime\n );\n const result = useSuspenseQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n ...cacheTimeOptions(\n overrides?.staleTime ?? descriptor.staleTime,\n overrides?.gcTime ?? descriptor.gcTime\n ),\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\nexport function useFrontXInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(\n queryClient,\n options.initialPage.key,\n pageParam,\n options.staleTime\n ),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n ...cacheTimeOptions(\n options.staleTime ?? options.initialPage.staleTime,\n options.gcTime ?? options.initialPage.gcTime\n ),\n maxPages: options.maxPages,\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\nexport function useFrontXSuspenseInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiSuspenseInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useSuspenseInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(\n queryClient,\n options.initialPage.key,\n pageParam,\n options.staleTime\n ),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n ...cacheTimeOptions(\n options.staleTime ?? options.initialPage.staleTime,\n options.gcTime ?? options.initialPage.gcTime\n ),\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\n/** The cache scope a mutation started under: its QueryClient and that client's scope generation. */\ntype MutationScope = {\n queryClient: QueryClient;\n generation: number;\n};\n\n/**\n * The scope each mutation run started under, keyed by the context object\n * TanStack builds once per run and passes as the last argument to onMutate,\n * onSuccess, onError and onSettled. Recorded before the caller's onMutate\n * runs, so the callbacks find it even when that onMutate throws and TanStack\n * keeps no onMutate result.\n */\nconst mutationScopes = new WeakMap<MutationFunctionContext, MutationScope>();\n\n/**\n * A queryCache whose writes do nothing once the cache scope (mock mode,\n * tenant, session) has changed since the mutation started, so a response or a\n * snapshot from the old scope never lands in the new scope's cache. Reads\n * still go through.\n */\nfunction scopeBoundQueryCache(queryCache: QueryCache, scope: MutationScope): QueryCache {\n const scopeChanged = () => readQueryCacheScopeGeneration(scope.queryClient) !== scope.generation;\n // A dropped write that would change the cache is recorded, so a session check that keeps the\n // session knows it has something to refresh. A dropped cancel changes nothing.\n const dropped = (): boolean => {\n if (!scopeChanged()) return false;\n recordQueryCacheScopeWriteDropped(scope.queryClient, scope.generation);\n return true;\n };\n return {\n get: queryCache.get,\n getState: queryCache.getState,\n set: (key, dataOrUpdater) => {\n if (!dropped()) queryCache.set(key, dataOrUpdater);\n },\n cancel: (key) => (scopeChanged() ? Promise.resolve() : queryCache.cancel(key)),\n invalidate: (key) => (dropped() ? Promise.resolve() : queryCache.invalidate(key)),\n invalidateMany: (filters) => (dropped() ? Promise.resolve() : queryCache.invalidateMany(filters)),\n remove: (key) => {\n if (!dropped()) queryCache.remove(key);\n },\n };\n}\n\n// The cache is built from the recorded QueryClient, not the latest render's,\n// so the scope check and the writes always target the same client even when\n// the provider swaps its QueryClient mid-flight. No scope only for a run that\n// skipped onMutate (TanStack resuming a restored paused mutation).\nfunction scopeBoundCallbackCtx(\n callbackCtx: MutationCallbackContext,\n scope: MutationScope | undefined\n): MutationCallbackContext {\n return scope\n ? { queryCache: scopeBoundQueryCache(createQueryCache(scope.queryClient), scope) }\n : callbackCtx;\n}\n\nexport function useFrontXMutation<\n TData = unknown,\n TError = Error,\n TVariables = void,\n TContext = unknown,\n>(\n options: UseApiMutationOptions<TData, TError, TVariables, TContext>,\n callbackCtx: MutationCallbackContext\n) {\n const queryClient = useRequiredFrontXQueryClient();\n\n const latestRef = useLatest({ options, callbackCtx, queryClient });\n const fetchAbortControllersRef = React.useRef<Set<AbortController>>(new Set());\n\n // Effect event: reads abortOnUnmount from the most recent render, not\n // whatever option value was current when the unmount effect was set up.\n const abortFetchesOnUnmount = React.useEffectEvent(() => {\n if (options.abortOnUnmount) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n });\n\n React.useEffect(() => {\n return () => {\n abortFetchesOnUnmount();\n };\n }, []);\n\n const mutationFn = React.useCallback((variables: TVariables, context: MutationFunctionContext) => {\n const cancelOnSupersede = latestRef.current.options.cancelOnSupersede;\n if (cancelOnSupersede) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n\n const controller = new AbortController();\n fetchAbortControllersRef.current.add(controller);\n\n const librarySignal = (context as MutationFunctionContext & { signal?: AbortSignal }).signal;\n if (cancelOnSupersede && librarySignal) {\n if (librarySignal.aborted) {\n controller.abort();\n } else {\n librarySignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return latestRef.current.options.endpoint\n .fetch(variables, { signal: controller.signal })\n .finally(() => {\n fetchAbortControllersRef.current.delete(controller);\n });\n // latestRef's identity never changes (useLatest returns a stable ref\n // object) — listing it satisfies exhaustive-deps without recreating this\n // callback on every render.\n }, [latestRef]);\n\n // onMutate always runs: it records the scope the mutation starts under,\n // and every callback gets a queryCache bound to that scope.\n const onMutate = React.useCallback(async (\n variables: TVariables,\n mutationFnContext: MutationFunctionContext\n ): Promise<TContext | undefined> => {\n const current = latestRef.current;\n const scope: MutationScope = {\n queryClient: current.queryClient,\n generation: readQueryCacheScopeGeneration(current.queryClient),\n };\n mutationScopes.set(mutationFnContext, scope);\n return current.options.onMutate?.(\n variables,\n scopeBoundCallbackCtx(current.callbackCtx, scope)\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onSuccess = React.useCallback((\n data: TData,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onSuccess?.(\n data,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onError = React.useCallback((\n error: TError,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onError?.(\n error,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onSettled = React.useCallback((\n data: TData | undefined,\n error: TError | null,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onSettled?.(\n data,\n error,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const mutation = useMutation<TData, TError, TVariables, TContext | undefined>({\n mutationFn,\n onMutate,\n onSuccess: options.onSuccess ? onSuccess : undefined,\n onError: options.onError ? onError : undefined,\n onSettled: options.onSettled ? onSettled : undefined,\n });\n\n return {\n mutate: mutation.mutate as (variables: TVariables) => void,\n mutateAsync: mutation.mutateAsync as (variables: TVariables) => Promise<TData>,\n isPending: mutation.isPending,\n error: mutation.error,\n data: mutation.data,\n reset: mutation.reset,\n };\n}\n","/**\n * QueryCache — restricted interface for interacting with the shared QueryClient.\n *\n * MFEs and screen-set components access the cache only through this sanctioned\n * public interface. It is injected as { queryCache } into useApiMutation\n * callbacks and also returned by useQueryCache() for controlled imperative\n * cache access.\n */\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-create-query-cache\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n\nimport type { EndpointDescriptor } from '@gears-frontx/framework';\nimport { eventBus } from '@gears-frontx/framework';\nimport { type QueryClient, type QueryState } from '@tanstack/react-query';\n\nexport type QueryCacheKey = readonly unknown[];\nexport type QueryCacheRefetchMode = 'active' | 'inactive' | 'all' | 'none';\nexport type QueryCacheInvalidateTarget =\n | EndpointDescriptor<unknown>\n | QueryCacheKey\n | null\n | undefined;\n\nexport interface QueryCacheState<TData = unknown, TError = Error> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n fetchFailureCount: number;\n fetchFailureReason: TError | null;\n fetchStatus: 'fetching' | 'paused' | 'idle';\n isInvalidated: boolean;\n status: 'pending' | 'error' | 'success';\n}\n\nexport type QueryCacheInvalidateFilters = {\n queryKey?: QueryCacheInvalidateTarget;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n};\n\ntype QueryCacheUpdater<T> = T | ((old: T | undefined) => T | undefined);\n\ntype CacheInvalidateEvent = {\n queryKey: QueryCacheKey;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n source?: string;\n};\n\ntype CacheSetEvent = {\n queryKey: QueryCacheKey;\n dataOrUpdater: QueryCacheUpdater<unknown>;\n source?: string;\n};\n\ntype CacheRemoveEvent = {\n queryKey: QueryCacheKey;\n source?: string;\n};\n\nconst QUERY_CLIENT_BROADCAST_TARGET = Symbol.for('frontx:query-cache:broadcast-target');\nconst QUERY_CLIENT_BROADCAST_COUNTER = Symbol.for('frontx:query-cache:broadcast-counter');\n\ntype QueryClientWithMetadata = QueryClient & {\n [QUERY_CLIENT_BROADCAST_TARGET]?: string;\n};\n\ntype QueryClientCounterHost = typeof globalThis & {\n [QUERY_CLIENT_BROADCAST_COUNTER]?: number;\n};\n\nfunction emitCacheEvent(event: string, payload: unknown): void {\n (eventBus.emit as (eventType: string, payload: unknown) => void)(event, payload);\n}\n\nfunction ensureBroadcastSource(queryClient: QueryClient): string {\n const clientWithMetadata = queryClient as QueryClientWithMetadata;\n const existingSource = clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET];\n if (typeof existingSource === 'string' && existingSource.length > 0) {\n return existingSource;\n }\n\n const host = globalThis as QueryClientCounterHost;\n const nextCounter = (host[QUERY_CLIENT_BROADCAST_COUNTER] ?? 0) + 1;\n host[QUERY_CLIENT_BROADCAST_COUNTER] = nextCounter;\n\n const source = `query-cache-${nextCounter}`;\n clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET] = source;\n return source;\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-resolve-key\nexport function resolveKey(target: EndpointDescriptor<unknown> | QueryCacheKey): readonly unknown[] {\n if (\n target !== null &&\n typeof target === 'object' &&\n !Array.isArray(target) &&\n 'key' in target &&\n 'fetch' in target &&\n Array.isArray(target.key) &&\n typeof target.fetch === 'function'\n ) {\n return target.key;\n }\n\n return target as readonly unknown[];\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-resolve-key\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\nexport interface QueryCache {\n get<T>(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined;\n getState<TData = unknown, TError = Error>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey\n ): QueryCacheState<TData, TError> | undefined;\n set<T>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey,\n dataOrUpdater: T | ((old: T | undefined) => T | undefined)\n ): void;\n cancel(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidate(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidateMany(filters?: QueryCacheInvalidateFilters | null): Promise<void>;\n remove(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): void;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\nexport interface MutationCallbackContext {\n queryCache: QueryCache;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\n\nfunction toQueryUpdater<T>(\n dataOrUpdater: QueryCacheUpdater<T>\n): (old: T | undefined) => T | undefined {\n if (typeof dataOrUpdater === 'function') {\n return dataOrUpdater as (old: T | undefined) => T | undefined;\n }\n\n return () => dataOrUpdater;\n}\n\nfunction mapQueryState<TData, TError = Error>(\n state: QueryState<TData, TError>\n): QueryCacheState<TData, TError> {\n return {\n data: state.data,\n dataUpdatedAt: state.dataUpdatedAt,\n error: state.error,\n errorUpdatedAt: state.errorUpdatedAt,\n fetchFailureCount: state.fetchFailureCount,\n fetchFailureReason: state.fetchFailureReason,\n fetchStatus: state.fetchStatus,\n isInvalidated: state.isInvalidated,\n status: state.status,\n };\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-create-query-cache\nexport function createQueryCache(queryClient: QueryClient): QueryCache {\n return {\n get: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined => {\n return queryClient.getQueryData<T>(resolveKey(key));\n },\n getState: <TData = unknown, TError = Error>(key: EndpointDescriptor<unknown> | QueryCacheKey) => {\n const state = queryClient.getQueryState<TData, TError>(resolveKey(key));\n return state ? mapQueryState(state) : undefined;\n },\n set: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey, dataOrUpdater: QueryCacheUpdater<T>): void => {\n const resolvedKey = resolveKey(key);\n queryClient.setQueryData<T>(resolvedKey, toQueryUpdater(dataOrUpdater));\n emitCacheEvent('cache/set', {\n queryKey: resolvedKey,\n dataOrUpdater: dataOrUpdater as QueryCacheUpdater<unknown>,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheSetEvent);\n },\n cancel: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n return queryClient.cancelQueries({ queryKey: resolveKey(key) });\n },\n invalidate: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n const resolvedKey = resolveKey(key);\n const result = queryClient.invalidateQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/invalidate', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n invalidateMany: (filters): Promise<void> => {\n if (filters?.queryKey == null) {\n return Promise.resolve();\n }\n\n const resolvedKey = resolveKey(filters.queryKey);\n if (!Array.isArray(resolvedKey) || resolvedKey.length === 0) {\n return Promise.resolve();\n }\n\n const payload = {\n ...filters,\n queryKey: resolvedKey,\n };\n const result = queryClient.invalidateQueries(payload);\n emitCacheEvent('cache/invalidate', {\n ...payload,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n remove: (key: EndpointDescriptor<unknown> | QueryCacheKey): void => {\n const resolvedKey = resolveKey(key);\n queryClient.removeQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/remove', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheRemoveEvent);\n },\n };\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-create-query-cache\n","/**\n * useLatest - keeps a ref pinned to the most recently rendered value\n *\n * A handful of hooks/components in this package need to read the current\n * value of a prop or option from inside a callback or effect-cleanup closure\n * that must NOT re-run every time that value changes (e.g. a stable\n * useCallback with `[]` deps, or a mount/unmount effect keyed on identity\n * rather than on every option). Stashing the value in a ref sidesteps the\n * closure staleness without pulling the value into the dependency array.\n *\n * The write happens inside a deps-less effect (runs after every commit)\n * rather than during render, because refs must not be mutated while\n * rendering: render can be invoked more than once per commit (React\n * StrictMode's double-invoke, and future concurrent-rendering paths that\n * may discard a render), so a render-time write can leave the ref out of\n * sync with what was actually committed to the DOM. A deps-less effect\n * runs exactly once per real commit, so the ref always reflects the value\n * that was last rendered.\n */\n\nimport { useEffect, useRef, type RefObject } from 'react';\n\n/**\n * Returns a ref that always holds the most recently rendered `value`.\n *\n * The ref identity is stable across renders (same object returned every\n * time), so it is safe to add to a `useCallback`/`useEffect` dependency\n * array without causing the callback/effect to be recreated.\n */\nexport function useLatest<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n\n // Deps-less: must run after every render so `ref.current` never lags\n // behind the value that was just committed. See module doc for why this\n // write cannot happen during render itself.\n useEffect(() => {\n ref.current = value;\n });\n\n return ref;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAOO;AACP,yBAUO;AACP,IAAAC,oBAMO;;;ACZP,uBAAyB;;;ACOzB,mBAAkD;;;AFsI1C;AAjHR,IAAM,0BAA0B,uBAAO,IAAI,+BAA+B;AAC1E,IAAM,mCAAmC,uBAAO,IAAI,wCAAwC;AAS5F,IAAM,+BAA2B,6BAAuC,MAAS;AAWjF,IAAM,kBAAkB,OAAO,WAAW,WAAW,cAAc,0BAAY;AAExE,SAAS,yBAAyB,KAAyC;AAChF,QAAM,YAAY;AAClB,SAAO,UAAU,uBAAuB,KAAK,UAAU,gCAAgC,IAAI;AAC7F;AA6BO,SAAS,2BAA2B,KAAyC;AAClF,SAAO,yBAAyB,GAAG;AACrC;AAoEO,SAAS,+BAAwD;AACtE,aAAO,0BAAW,wBAAwB;AAC5C;;;ADvJA,qBAA6C;","names":["import_react","import_framework"]}
package/dist/testing.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import React, {
3
3
  createContext,
4
4
  useContext,
5
- useEffect,
5
+ useEffect as useEffect2,
6
6
  useLayoutEffect,
7
7
  useMemo,
8
8
  useState
@@ -17,18 +17,23 @@ import {
17
17
  useSuspenseQuery
18
18
  } from "@tanstack/react-query";
19
19
  import {
20
+ readQueryCacheScopeGeneration,
21
+ recordQueryCacheScopeWriteDropped,
20
22
  subscribeQueryCacheRuntimeChanged
21
23
  } from "@gears-frontx/framework";
22
24
 
23
25
  // src/hooks/QueryCache.ts
24
26
  import { eventBus } from "@gears-frontx/framework";
25
27
 
28
+ // src/hooks/useLatest.ts
29
+ import { useEffect, useRef } from "react";
30
+
26
31
  // src/queryClient.tsx
27
32
  import { jsx } from "react/jsx-runtime";
28
33
  var APP_QUERY_CLIENT_SYMBOL = /* @__PURE__ */ Symbol.for("frontx:query-cache:app-client");
29
34
  var APP_QUERY_CLIENT_RESOLVER_SYMBOL = /* @__PURE__ */ Symbol.for("frontx:query-cache:app-client-resolver");
30
35
  var FrontXQueryClientContext = createContext(void 0);
31
- var useCommitEffect = typeof globalThis.window === "undefined" ? useEffect : useLayoutEffect;
36
+ var useCommitEffect = typeof globalThis.window === "undefined" ? useEffect2 : useLayoutEffect;
32
37
  function resolveFrontXQueryClient(app) {
33
38
  const clientApp = app;
34
39
  return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/queryClient.tsx","../src/hooks/QueryCache.ts","../src/testing.ts"],"sourcesContent":["import React, {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\nimport {\n QueryClientContext,\n QueryClientProvider,\n type QueryClient,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseInfiniteQuery,\n useSuspenseQuery,\n type MutationFunctionContext,\n} from '@tanstack/react-query';\nimport {\n subscribeQueryCacheRuntimeChanged,\n type EndpointDescriptor,\n type FrontXApp,\n} from '@gears-frontx/framework';\nimport type { ApiQueryOverrides } from './hooks/useApiQuery';\nimport type {\n ApiInfiniteQueryOptions,\n ApiInfiniteQueryPageContext,\n} from './hooks/useApiInfiniteQuery';\nimport type { UseApiMutationOptions } from './hooks/useApiMutation';\nimport { createQueryCache, type MutationCallbackContext, type QueryCacheKey } from './hooks/QueryCache';\n\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-query-provider:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-query:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-react-query-client-symbols\nconst APP_QUERY_CLIENT_SYMBOL = Symbol.for('frontx:query-cache:app-client');\nconst APP_QUERY_CLIENT_RESOLVER_SYMBOL = Symbol.for('frontx:query-cache:app-client-resolver');\nconst APP_QUERY_CLIENT_ACTIVATOR_SYMBOL = Symbol.for('frontx:query-cache:app-client-activator');\n\ntype QueryClientApp = FrontXApp & {\n [APP_QUERY_CLIENT_SYMBOL]?: QueryClient;\n [APP_QUERY_CLIENT_RESOLVER_SYMBOL]?: () => QueryClient | undefined;\n [APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?: () => QueryClient | undefined;\n};\n\nconst FrontXQueryClientContext = createContext<QueryClient | undefined>(undefined);\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-react-query-client-symbols\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-resolve-app-query-client\ntype RuntimeAwareEndpointDescriptor<TData> = EndpointDescriptor<TData> & {\n fetch(options?: { signal?: AbortSignal; staleTime?: number }): Promise<TData>;\n};\n\ntype AppResolvedQueryClient = {\n app: FrontXApp;\n queryClient: QueryClient;\n};\n\nconst useCommitEffect = typeof globalThis.window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function resolveFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();\n}\n\nexport function hasFrontXQueryClientActivator(app: FrontXApp): boolean {\n return typeof (app as QueryClientApp)[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL] === 'function';\n}\n\nexport function activateFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?.();\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-resolve-app-query-client\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-imperative-cache-bootstrap\n/**\n * Imperatively invalidates cache entries for `target` on the QueryClient bound to `app`.\n * Use from non-React code (e.g. MFE actions); in components prefer `useQueryCache().invalidate`.\n */\nexport async function invalidateQueryCacheForApp(\n app: FrontXApp,\n target: EndpointDescriptor<unknown> | QueryCacheKey\n): Promise<void> {\n const queryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (!queryClient) {\n throw new Error(\n '[invalidateQueryCacheForApp] No QueryClient on app. Ensure queryCache() or queryCacheShared() is in the plugin chain.'\n );\n }\n await createQueryCache(queryClient).invalidate(target);\n}\n\n/** Resolves the app-bound QueryClient without triggering plugin activation during render. */\nexport function bootstrapFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n return resolveFrontXQueryClient(app);\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-imperative-cache-bootstrap\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-use-bootstrapped-query-client\nexport function useBootstrappedFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const fromApp = useMemo(() => bootstrapFrontXQueryClient(app), [app]);\n const [eventResolvedClient, setEventResolvedClient] = useState<AppResolvedQueryClient | undefined>(\n undefined\n );\n const queryClient =\n fromApp ?? (eventResolvedClient?.app === app ? eventResolvedClient.queryClient : undefined);\n\n useCommitEffect(() => {\n if (fromApp || !hasFrontXQueryClientActivator(app)) {\n return;\n }\n\n const tryResolveQueryClient = () => {\n const nextQueryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (nextQueryClient) {\n setEventResolvedClient((current) => {\n if (current?.app === app && current.queryClient === nextQueryClient) {\n return current;\n }\n\n return {\n app,\n queryClient: nextQueryClient,\n };\n });\n }\n };\n\n // Only activate after commit so abandoned renders cannot leak retainers/listeners.\n tryResolveQueryClient();\n\n const subscription = subscribeQueryCacheRuntimeChanged(() => {\n tryResolveQueryClient();\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [app, fromApp]);\n\n return queryClient;\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-query-client-lifecycle:p2:inst-use-bootstrapped-query-client\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-frontx-query-client-provider\nexport function FrontXQueryClientProvider({\n queryClient,\n children,\n}: Readonly<{\n queryClient: QueryClient | undefined;\n children: React.ReactNode;\n}>) {\n if (!queryClient) {\n return (\n <FrontXQueryClientContext.Provider value={undefined}>\n <QueryClientContext.Provider value={undefined}>{children}</QueryClientContext.Provider>\n </FrontXQueryClientContext.Provider>\n );\n }\n\n return (\n <FrontXQueryClientContext.Provider value={queryClient}>\n <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\n </FrontXQueryClientContext.Provider>\n );\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-frontx-query-client-provider\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-query-client-context-hooks\nexport function useOptionalFrontXQueryClient(): QueryClient | undefined {\n return useContext(FrontXQueryClientContext);\n}\n\nexport function useRequiredFrontXQueryClient(): QueryClient {\n const queryClient = useOptionalFrontXQueryClient();\n if (!queryClient) {\n throw new Error(\n '[FrontXProvider] No query cache available. Add queryCache() or queryCacheShared() to your plugin composition.'\n );\n }\n\n return queryClient;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-query-provider:p2:inst-query-client-context-hooks\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-descriptor-fetch-stale-helpers\nfunction buildPageContext<TPage>(\n page: TPage,\n pages: readonly TPage[],\n descriptor: EndpointDescriptor<TPage>,\n descriptors: readonly EndpointDescriptor<TPage>[]\n): ApiInfiniteQueryPageContext<TPage> {\n return {\n page,\n pages,\n descriptor,\n descriptors,\n };\n}\n\nfunction normalizeFetchStaleTime(staleTime: unknown): number | undefined {\n if (staleTime === 'static') {\n return Number.POSITIVE_INFINITY;\n }\n\n return typeof staleTime === 'number' ? staleTime : undefined;\n}\n\nfunction resolveFetchStaleTime<TData>(\n queryClient: QueryClient,\n descriptor: EndpointDescriptor<TData>,\n overrideStaleTime?: number\n): number | undefined {\n return normalizeFetchStaleTime(\n overrideStaleTime ??\n descriptor.staleTime ??\n queryClient.getDefaultOptions().queries?.staleTime\n );\n}\n\nfunction fetchDescriptor<TData>(\n descriptor: EndpointDescriptor<TData>,\n options?: { signal?: AbortSignal; staleTime?: number }\n): Promise<TData> {\n return (descriptor as RuntimeAwareEndpointDescriptor<TData>).fetch(options);\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-descriptor-fetch-stale-helpers\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-query\nexport function useFrontXQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(queryClient, descriptor, overrides?.staleTime);\n const result = useQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n staleTime: overrides?.staleTime ?? descriptor.staleTime,\n gcTime: overrides?.gcTime ?? descriptor.gcTime,\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n refetch: result.refetch,\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-query\nexport function useFrontXSuspenseQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(queryClient, descriptor, overrides?.staleTime);\n const result = useSuspenseQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n staleTime: overrides?.staleTime ?? descriptor.staleTime,\n gcTime: overrides?.gcTime ?? descriptor.gcTime,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-infinite-query\nexport function useFrontXInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(queryClient, pageParam, options.staleTime),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n staleTime: options.staleTime ?? options.initialPage.staleTime,\n gcTime: options.gcTime ?? options.initialPage.gcTime,\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-infinite-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-infinite-query\nexport function useFrontXSuspenseInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useSuspenseInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(queryClient, pageParam, options.staleTime),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n staleTime: options.staleTime ?? options.initialPage.staleTime,\n gcTime: options.gcTime ?? options.initialPage.gcTime,\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-query:p2:inst-delegate-frontx-use-suspense-infinite-query\n\n// @cpt-begin:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-delegate-frontx-use-mutation\nexport function useFrontXMutation<\n TData = unknown,\n TError = Error,\n TVariables = void,\n TContext = unknown,\n>(\n options: UseApiMutationOptions<TData, TError, TVariables, TContext>,\n callbackCtx: MutationCallbackContext\n) {\n useRequiredFrontXQueryClient();\n\n const latestRef = React.useRef({ options, callbackCtx });\n latestRef.current = { options, callbackCtx };\n const fetchAbortControllersRef = React.useRef<Set<AbortController>>(new Set());\n\n React.useEffect(() => {\n const fetchAbortControllers = fetchAbortControllersRef.current;\n return () => {\n if (latestRef.current.options.abortOnUnmount) {\n for (const controller of fetchAbortControllers) {\n controller.abort();\n }\n fetchAbortControllers.clear();\n }\n };\n }, []);\n\n const mutationFn = React.useCallback((variables: TVariables, context: MutationFunctionContext) => {\n const cancelOnSupersede = latestRef.current.options.cancelOnSupersede;\n if (cancelOnSupersede) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n\n const controller = new AbortController();\n fetchAbortControllersRef.current.add(controller);\n\n const librarySignal = (context as MutationFunctionContext & { signal?: AbortSignal }).signal;\n if (cancelOnSupersede && librarySignal) {\n if (librarySignal.aborted) {\n controller.abort();\n } else {\n librarySignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return latestRef.current.options.endpoint\n .fetch(variables, { signal: controller.signal })\n .finally(() => {\n fetchAbortControllersRef.current.delete(controller);\n });\n }, []);\n\n const onMutate = React.useCallback((variables: TVariables, _context: MutationFunctionContext) => {\n const current = latestRef.current;\n if (!current.options.onMutate) {\n return undefined as TContext;\n }\n\n return current.options.onMutate(variables, current.callbackCtx);\n }, []);\n\n const onSuccess = React.useCallback((data: TData, variables: TVariables, context: TContext | undefined) => {\n const current = latestRef.current;\n return current.options.onSuccess?.(data, variables, context, current.callbackCtx);\n }, []);\n\n const onError = React.useCallback((error: TError, variables: TVariables, context: TContext | undefined) => {\n const current = latestRef.current;\n return current.options.onError?.(error, variables, context, current.callbackCtx);\n }, []);\n\n const onSettled = React.useCallback((\n data: TData | undefined,\n error: TError | null,\n variables: TVariables,\n context: TContext | undefined\n ) => {\n const current = latestRef.current;\n return current.options.onSettled?.(\n data,\n error,\n variables,\n context,\n current.callbackCtx\n );\n }, []);\n\n const mutation = useMutation<TData, TError, TVariables, TContext>({\n mutationFn,\n onMutate: options.onMutate ? onMutate : undefined,\n onSuccess: options.onSuccess ? onSuccess : undefined,\n onError: options.onError ? onError : undefined,\n onSettled: options.onSettled ? onSettled : undefined,\n });\n\n return {\n mutate: mutation.mutate as (variables: TVariables) => void,\n mutateAsync: mutation.mutateAsync as (variables: TVariables) => Promise<TData>,\n isPending: mutation.isPending,\n error: mutation.error,\n data: mutation.data,\n reset: mutation.reset,\n };\n}\n// @cpt-end:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-delegate-frontx-use-mutation\n","/**\n * QueryCache — restricted interface for interacting with the shared QueryClient.\n *\n * MFEs and screen-set components access the cache only through this sanctioned\n * public interface. It is injected as { queryCache } into useApiMutation\n * callbacks and also returned by useQueryCache() for controlled imperative\n * cache access.\n */\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-create-query-cache\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n\nimport type { EndpointDescriptor } from '@gears-frontx/framework';\nimport { eventBus } from '@gears-frontx/framework';\nimport { type QueryClient, type QueryState } from '@tanstack/react-query';\n\nexport type QueryCacheKey = readonly unknown[];\nexport type QueryCacheRefetchMode = 'active' | 'inactive' | 'all' | 'none';\nexport type QueryCacheInvalidateTarget =\n | EndpointDescriptor<unknown>\n | QueryCacheKey\n | null\n | undefined;\n\nexport interface QueryCacheState<TData = unknown, TError = Error> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n fetchFailureCount: number;\n fetchFailureReason: TError | null;\n fetchStatus: 'fetching' | 'paused' | 'idle';\n isInvalidated: boolean;\n status: 'pending' | 'error' | 'success';\n}\n\nexport type QueryCacheInvalidateFilters = {\n queryKey?: QueryCacheInvalidateTarget;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n};\n\ntype QueryCacheUpdater<T> = T | ((old: T | undefined) => T | undefined);\n\ntype CacheInvalidateEvent = {\n queryKey: QueryCacheKey;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n source?: string;\n};\n\ntype CacheSetEvent = {\n queryKey: QueryCacheKey;\n dataOrUpdater: QueryCacheUpdater<unknown>;\n source?: string;\n};\n\ntype CacheRemoveEvent = {\n queryKey: QueryCacheKey;\n source?: string;\n};\n\nconst QUERY_CLIENT_BROADCAST_TARGET = Symbol.for('frontx:query-cache:broadcast-target');\nconst QUERY_CLIENT_BROADCAST_COUNTER = Symbol.for('frontx:query-cache:broadcast-counter');\n\ntype QueryClientWithMetadata = QueryClient & {\n [QUERY_CLIENT_BROADCAST_TARGET]?: string;\n};\n\ntype QueryClientCounterHost = typeof globalThis & {\n [QUERY_CLIENT_BROADCAST_COUNTER]?: number;\n};\n\nfunction emitCacheEvent(event: string, payload: unknown): void {\n (eventBus.emit as (eventType: string, payload: unknown) => void)(event, payload);\n}\n\nfunction ensureBroadcastSource(queryClient: QueryClient): string {\n const clientWithMetadata = queryClient as QueryClientWithMetadata;\n const existingSource = clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET];\n if (typeof existingSource === 'string' && existingSource.length > 0) {\n return existingSource;\n }\n\n const host = globalThis as QueryClientCounterHost;\n const nextCounter = (host[QUERY_CLIENT_BROADCAST_COUNTER] ?? 0) + 1;\n host[QUERY_CLIENT_BROADCAST_COUNTER] = nextCounter;\n\n const source = `query-cache-${nextCounter}`;\n clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET] = source;\n return source;\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-resolve-key\nexport function resolveKey(target: EndpointDescriptor<unknown> | QueryCacheKey): readonly unknown[] {\n if (\n target !== null &&\n typeof target === 'object' &&\n !Array.isArray(target) &&\n 'key' in target &&\n 'fetch' in target &&\n Array.isArray(target.key) &&\n typeof target.fetch === 'function'\n ) {\n return target.key;\n }\n\n return target as readonly unknown[];\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-resolve-key\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\nexport interface QueryCache {\n get<T>(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined;\n getState<TData = unknown, TError = Error>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey\n ): QueryCacheState<TData, TError> | undefined;\n set<T>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey,\n dataOrUpdater: T | ((old: T | undefined) => T | undefined)\n ): void;\n cancel(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidate(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidateMany(filters?: QueryCacheInvalidateFilters | null): Promise<void>;\n remove(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): void;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\nexport interface MutationCallbackContext {\n queryCache: QueryCache;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\n\nfunction toQueryUpdater<T>(\n dataOrUpdater: QueryCacheUpdater<T>\n): (old: T | undefined) => T | undefined {\n if (typeof dataOrUpdater === 'function') {\n return dataOrUpdater as (old: T | undefined) => T | undefined;\n }\n\n return () => dataOrUpdater;\n}\n\nfunction mapQueryState<TData, TError = Error>(\n state: QueryState<TData, TError>\n): QueryCacheState<TData, TError> {\n return {\n data: state.data,\n dataUpdatedAt: state.dataUpdatedAt,\n error: state.error,\n errorUpdatedAt: state.errorUpdatedAt,\n fetchFailureCount: state.fetchFailureCount,\n fetchFailureReason: state.fetchFailureReason,\n fetchStatus: state.fetchStatus,\n isInvalidated: state.isInvalidated,\n status: state.status,\n };\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-create-query-cache\nexport function createQueryCache(queryClient: QueryClient): QueryCache {\n return {\n get: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined => {\n return queryClient.getQueryData<T>(resolveKey(key));\n },\n getState: <TData = unknown, TError = Error>(key: EndpointDescriptor<unknown> | QueryCacheKey) => {\n const state = queryClient.getQueryState<TData, TError>(resolveKey(key));\n return state ? mapQueryState(state) : undefined;\n },\n set: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey, dataOrUpdater: QueryCacheUpdater<T>): void => {\n const resolvedKey = resolveKey(key);\n queryClient.setQueryData<T>(resolvedKey, toQueryUpdater(dataOrUpdater));\n emitCacheEvent('cache/set', {\n queryKey: resolvedKey,\n dataOrUpdater: dataOrUpdater as QueryCacheUpdater<unknown>,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheSetEvent);\n },\n cancel: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n return queryClient.cancelQueries({ queryKey: resolveKey(key) });\n },\n invalidate: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n const resolvedKey = resolveKey(key);\n const result = queryClient.invalidateQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/invalidate', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n invalidateMany: (filters): Promise<void> => {\n if (filters?.queryKey == null) {\n return Promise.resolve();\n }\n\n const resolvedKey = resolveKey(filters.queryKey);\n if (!Array.isArray(resolvedKey) || resolvedKey.length === 0) {\n return Promise.resolve();\n }\n\n const payload = {\n ...filters,\n queryKey: resolvedKey,\n };\n const result = queryClient.invalidateQueries(payload);\n emitCacheEvent('cache/invalidate', {\n ...payload,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n remove: (key: EndpointDescriptor<unknown> | QueryCacheKey): void => {\n const resolvedKey = resolveKey(key);\n queryClient.removeQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/remove', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheRemoveEvent);\n },\n };\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-create-query-cache\n","/**\n * Test-only entry for @gears-frontx/react.\n *\n * Utilities here are intended for Vitest (or similar) suites that need access\n * to query-client wiring without importing package internals directly.\n */\n\n// @cpt-dod:cpt-frontx-dod-react-bindings-provider:p1\n\n// @cpt-begin:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\nexport {\n bootstrapFrontXQueryClient,\n resolveFrontXQueryClient,\n useOptionalFrontXQueryClient,\n} from './queryClient';\n\n/** App-layer tests must import this from `@gears-frontx/react/testing`, not `@gears-frontx/framework/testing`. */\nexport { describeBootstrapMfeContract } from '@gears-frontx/framework/testing';\nexport type {\n BootstrapMfeResolveArgs,\n BootstrapMfeTestSpecOptions,\n} from '@gears-frontx/framework/testing';\n// @cpt-end:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\n"],"mappings":";AAAA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAGK;;;ACVP,SAAS,gBAAgB;;;ADmJjB;AAzHR,IAAM,0BAA0B,uBAAO,IAAI,+BAA+B;AAC1E,IAAM,mCAAmC,uBAAO,IAAI,wCAAwC;AAS5F,IAAM,2BAA2B,cAAuC,MAAS;AAajF,IAAM,kBAAkB,OAAO,WAAW,WAAW,cAAc,YAAY;AAExE,SAAS,yBAAyB,KAAyC;AAChF,QAAM,YAAY;AAClB,SAAO,UAAU,uBAAuB,KAAK,UAAU,gCAAgC,IAAI;AAC7F;AA+BO,SAAS,2BAA2B,KAAyC;AAClF,SAAO,yBAAyB,GAAG;AACrC;AA0EO,SAAS,+BAAwD;AACtE,SAAO,WAAW,wBAAwB;AAC5C;;;AE/JA,SAAS,oCAAoC;","names":[]}
1
+ {"version":3,"sources":["../src/queryClient.tsx","../src/hooks/QueryCache.ts","../src/hooks/useLatest.ts","../src/testing.ts"],"sourcesContent":["import React, {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\nimport {\n QueryClientContext,\n QueryClientProvider,\n type QueryClient,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseInfiniteQuery,\n useSuspenseQuery,\n type MutationFunctionContext,\n} from '@tanstack/react-query';\nimport {\n readQueryCacheScopeGeneration,\n recordQueryCacheScopeWriteDropped,\n subscribeQueryCacheRuntimeChanged,\n type EndpointDescriptor,\n type FrontXApp,\n} from '@gears-frontx/framework';\nimport type { ApiQueryOverrides, ApiSuspenseQueryOverrides } from './hooks/useApiQuery';\nimport type {\n ApiInfiniteQueryOptions,\n ApiInfiniteQueryPageContext,\n ApiSuspenseInfiniteQueryOptions,\n} from './hooks/useApiInfiniteQuery';\nimport type { UseApiMutationOptions } from './hooks/useApiMutation';\nimport {\n createQueryCache,\n type MutationCallbackContext,\n type QueryCache,\n type QueryCacheKey,\n} from './hooks/QueryCache';\nimport { useLatest } from './hooks/useLatest';\n\nconst APP_QUERY_CLIENT_SYMBOL = Symbol.for('frontx:query-cache:app-client');\nconst APP_QUERY_CLIENT_RESOLVER_SYMBOL = Symbol.for('frontx:query-cache:app-client-resolver');\nconst APP_QUERY_CLIENT_ACTIVATOR_SYMBOL = Symbol.for('frontx:query-cache:app-client-activator');\n\ntype QueryClientApp = FrontXApp & {\n [APP_QUERY_CLIENT_SYMBOL]?: QueryClient;\n [APP_QUERY_CLIENT_RESOLVER_SYMBOL]?: () => QueryClient | undefined;\n [APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?: () => QueryClient | undefined;\n};\n\nconst FrontXQueryClientContext = createContext<QueryClient | undefined>(undefined);\n\ntype RuntimeAwareEndpointDescriptor<TData> = EndpointDescriptor<TData> & {\n fetch(options?: { signal?: AbortSignal; staleTime?: number }): Promise<TData>;\n};\n\ntype AppResolvedQueryClient = {\n app: FrontXApp;\n queryClient: QueryClient;\n};\n\nconst useCommitEffect = typeof globalThis.window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function resolveFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_RESOLVER_SYMBOL]?.();\n}\n\nexport function hasFrontXQueryClientActivator(app: FrontXApp): boolean {\n return typeof (app as QueryClientApp)[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL] === 'function';\n}\n\nexport function activateFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const clientApp = app as QueryClientApp;\n return clientApp[APP_QUERY_CLIENT_SYMBOL] ?? clientApp[APP_QUERY_CLIENT_ACTIVATOR_SYMBOL]?.();\n}\n\n/**\n * Imperatively invalidates cache entries for `target` on the QueryClient bound to `app`.\n * Use from non-React code (e.g. MFE actions); in components prefer `useQueryCache().invalidate`.\n */\nexport async function invalidateQueryCacheForApp(\n app: FrontXApp,\n target: EndpointDescriptor<unknown> | QueryCacheKey\n): Promise<void> {\n const queryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (!queryClient) {\n throw new Error(\n '[invalidateQueryCacheForApp] No QueryClient on app. Ensure queryCache() or queryCacheShared() is in the plugin chain.'\n );\n }\n await createQueryCache(queryClient).invalidate(target);\n}\n\n/** Resolves the app-bound QueryClient without triggering plugin activation during render. */\nexport function bootstrapFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n return resolveFrontXQueryClient(app);\n}\n\nexport function useBootstrappedFrontXQueryClient(app: FrontXApp): QueryClient | undefined {\n const fromApp = useMemo(() => bootstrapFrontXQueryClient(app), [app]);\n const [eventResolvedClient, setEventResolvedClient] = useState<AppResolvedQueryClient | undefined>(\n undefined\n );\n const queryClient =\n fromApp ?? (eventResolvedClient?.app === app ? eventResolvedClient.queryClient : undefined);\n\n useCommitEffect(() => {\n if (fromApp || !hasFrontXQueryClientActivator(app)) {\n return;\n }\n\n const tryResolveQueryClient = () => {\n const nextQueryClient = resolveFrontXQueryClient(app) ?? activateFrontXQueryClient(app);\n if (nextQueryClient) {\n setEventResolvedClient((current) => {\n if (current?.app === app && current.queryClient === nextQueryClient) {\n return current;\n }\n\n return {\n app,\n queryClient: nextQueryClient,\n };\n });\n }\n };\n\n // Only activate after commit so abandoned renders cannot leak retainers/listeners.\n tryResolveQueryClient();\n\n const subscription = subscribeQueryCacheRuntimeChanged(() => {\n tryResolveQueryClient();\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [app, fromApp]);\n\n return queryClient;\n}\n\nexport function FrontXQueryClientProvider({\n queryClient,\n children,\n}: Readonly<{\n queryClient: QueryClient | undefined;\n children: React.ReactNode;\n}>) {\n if (!queryClient) {\n return (\n <FrontXQueryClientContext.Provider value={undefined}>\n <QueryClientContext.Provider value={undefined}>{children}</QueryClientContext.Provider>\n </FrontXQueryClientContext.Provider>\n );\n }\n\n return (\n <FrontXQueryClientContext.Provider value={queryClient}>\n <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\n </FrontXQueryClientContext.Provider>\n );\n}\n\nexport function useOptionalFrontXQueryClient(): QueryClient | undefined {\n return useContext(FrontXQueryClientContext);\n}\n\nexport function useRequiredFrontXQueryClient(): QueryClient {\n const queryClient = useOptionalFrontXQueryClient();\n if (!queryClient) {\n throw new Error(\n '[FrontXProvider] No query cache available. Add queryCache() or queryCacheShared() to your plugin composition.'\n );\n }\n\n return queryClient;\n}\n\nfunction buildPageContext<TPage>(\n page: TPage,\n pages: readonly TPage[],\n descriptor: EndpointDescriptor<TPage>,\n descriptors: readonly EndpointDescriptor<TPage>[]\n): ApiInfiniteQueryPageContext<TPage> {\n return {\n page,\n pages,\n descriptor,\n descriptors,\n };\n}\n\nfunction normalizeFetchStaleTime(staleTime: unknown): number | undefined {\n if (staleTime === 'static') {\n return Number.POSITIVE_INFINITY;\n }\n\n // A function staleTime is resolved per query by TanStack; 0 keeps the fetch\n // cache from serving a response older than the query would accept.\n if (typeof staleTime === 'function') {\n return 0;\n }\n\n return typeof staleTime === 'number' ? staleTime : undefined;\n}\n\n/**\n * The staleTime the shared fetch cache uses, resolved the way TanStack\n * resolves it for the query: call site, then descriptor, then the\n * QueryClient defaults for the query key (global defaults with every\n * matching setQueryDefaults prefix spread over them).\n */\nfunction resolveFetchStaleTime<TData>(\n queryClient: QueryClient,\n queryKey: readonly unknown[],\n descriptor: EndpointDescriptor<TData>,\n overrideStaleTime?: number\n): number | undefined {\n const clientDefaults = {\n ...queryClient.getDefaultOptions().queries,\n ...queryClient.getQueryDefaults(queryKey),\n };\n return normalizeFetchStaleTime(\n overrideStaleTime ?? descriptor.staleTime ?? clientDefaults.staleTime\n );\n}\n\n/**\n * staleTime/gcTime for a query, with only the keys that are set. An explicit\n * `undefined` would override the QueryClient defaults (TanStack spreads the\n * query options over them), so a screen that remounts would refetch instead of\n * painting from cache.\n */\nfunction cacheTimeOptions(\n staleTime: number | undefined,\n gcTime: number | undefined\n): { staleTime?: number; gcTime?: number } {\n return {\n ...(staleTime === undefined ? {} : { staleTime }),\n ...(gcTime === undefined ? {} : { gcTime }),\n };\n}\n\nfunction fetchDescriptor<TData>(\n descriptor: EndpointDescriptor<TData>,\n options?: { signal?: AbortSignal; staleTime?: number }\n): Promise<TData> {\n return (descriptor as RuntimeAwareEndpointDescriptor<TData>).fetch(options);\n}\n\nexport function useFrontXQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(\n queryClient,\n descriptor.key,\n descriptor,\n overrides?.staleTime\n );\n const result = useQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n ...cacheTimeOptions(\n overrides?.staleTime ?? descriptor.staleTime,\n overrides?.gcTime ?? descriptor.gcTime\n ),\n ...(overrides?.enabled === undefined ? {} : { enabled: overrides.enabled }),\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n refetch: result.refetch,\n };\n}\n\nexport function useFrontXSuspenseQuery<TData = unknown, TError = Error>(\n descriptor: EndpointDescriptor<TData>,\n overrides?: ApiSuspenseQueryOverrides\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const staleTime = resolveFetchStaleTime(\n queryClient,\n descriptor.key,\n descriptor,\n overrides?.staleTime\n );\n const result = useSuspenseQuery<TData, TError>({\n queryKey: descriptor.key as unknown[],\n queryFn: ({ signal }) => fetchDescriptor(descriptor, { signal, staleTime }),\n ...cacheTimeOptions(\n overrides?.staleTime ?? descriptor.staleTime,\n overrides?.gcTime ?? descriptor.gcTime\n ),\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\nexport function useFrontXInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(\n queryClient,\n options.initialPage.key,\n pageParam,\n options.staleTime\n ),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n ...cacheTimeOptions(\n options.staleTime ?? options.initialPage.staleTime,\n options.gcTime ?? options.initialPage.gcTime\n ),\n maxPages: options.maxPages,\n ...(options.enabled === undefined ? {} : { enabled: options.enabled }),\n });\n\n return {\n data: result.data,\n error: result.error,\n isLoading: result.isLoading,\n isFetching: result.isFetching,\n isError: result.isError,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\nexport function useFrontXSuspenseInfiniteQuery<TPage = unknown, TError = Error>(\n options: ApiSuspenseInfiniteQueryOptions<TPage>\n) {\n const queryClient = useRequiredFrontXQueryClient();\n const result = useSuspenseInfiniteQuery<\n TPage,\n TError,\n readonly TPage[],\n readonly unknown[],\n EndpointDescriptor<TPage>\n >({\n queryKey: options.initialPage.key,\n initialPageParam: options.initialPage,\n queryFn: ({ pageParam, signal }) =>\n fetchDescriptor(pageParam, {\n signal,\n staleTime: resolveFetchStaleTime(\n queryClient,\n options.initialPage.key,\n pageParam,\n options.staleTime\n ),\n }),\n getNextPageParam: (\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n ) =>\n options.getNextPage(\n buildPageContext(\n lastPage,\n allPages,\n lastPageDescriptor,\n allPageDescriptors\n )\n ),\n getPreviousPageParam: options.getPreviousPage\n ? (firstPage, allPages, firstPageDescriptor, allPageDescriptors) =>\n options.getPreviousPage?.(\n buildPageContext(\n firstPage,\n allPages,\n firstPageDescriptor,\n allPageDescriptors\n )\n )\n : undefined,\n select: (data) => data.pages,\n ...cacheTimeOptions(\n options.staleTime ?? options.initialPage.staleTime,\n options.gcTime ?? options.initialPage.gcTime\n ),\n maxPages: options.maxPages,\n });\n\n return {\n data: result.data,\n error: result.error,\n isFetching: result.isFetching,\n hasNextPage: result.hasNextPage ?? false,\n hasPreviousPage: result.hasPreviousPage ?? false,\n isFetchingNextPage: result.isFetchingNextPage,\n isFetchingPreviousPage: result.isFetchingPreviousPage,\n fetchNextPage: async () => {\n await result.fetchNextPage();\n },\n fetchPreviousPage: async () => {\n await result.fetchPreviousPage();\n },\n refetch: async () => {\n await result.refetch();\n },\n };\n}\n\n/** The cache scope a mutation started under: its QueryClient and that client's scope generation. */\ntype MutationScope = {\n queryClient: QueryClient;\n generation: number;\n};\n\n/**\n * The scope each mutation run started under, keyed by the context object\n * TanStack builds once per run and passes as the last argument to onMutate,\n * onSuccess, onError and onSettled. Recorded before the caller's onMutate\n * runs, so the callbacks find it even when that onMutate throws and TanStack\n * keeps no onMutate result.\n */\nconst mutationScopes = new WeakMap<MutationFunctionContext, MutationScope>();\n\n/**\n * A queryCache whose writes do nothing once the cache scope (mock mode,\n * tenant, session) has changed since the mutation started, so a response or a\n * snapshot from the old scope never lands in the new scope's cache. Reads\n * still go through.\n */\nfunction scopeBoundQueryCache(queryCache: QueryCache, scope: MutationScope): QueryCache {\n const scopeChanged = () => readQueryCacheScopeGeneration(scope.queryClient) !== scope.generation;\n // A dropped write that would change the cache is recorded, so a session check that keeps the\n // session knows it has something to refresh. A dropped cancel changes nothing.\n const dropped = (): boolean => {\n if (!scopeChanged()) return false;\n recordQueryCacheScopeWriteDropped(scope.queryClient, scope.generation);\n return true;\n };\n return {\n get: queryCache.get,\n getState: queryCache.getState,\n set: (key, dataOrUpdater) => {\n if (!dropped()) queryCache.set(key, dataOrUpdater);\n },\n cancel: (key) => (scopeChanged() ? Promise.resolve() : queryCache.cancel(key)),\n invalidate: (key) => (dropped() ? Promise.resolve() : queryCache.invalidate(key)),\n invalidateMany: (filters) => (dropped() ? Promise.resolve() : queryCache.invalidateMany(filters)),\n remove: (key) => {\n if (!dropped()) queryCache.remove(key);\n },\n };\n}\n\n// The cache is built from the recorded QueryClient, not the latest render's,\n// so the scope check and the writes always target the same client even when\n// the provider swaps its QueryClient mid-flight. No scope only for a run that\n// skipped onMutate (TanStack resuming a restored paused mutation).\nfunction scopeBoundCallbackCtx(\n callbackCtx: MutationCallbackContext,\n scope: MutationScope | undefined\n): MutationCallbackContext {\n return scope\n ? { queryCache: scopeBoundQueryCache(createQueryCache(scope.queryClient), scope) }\n : callbackCtx;\n}\n\nexport function useFrontXMutation<\n TData = unknown,\n TError = Error,\n TVariables = void,\n TContext = unknown,\n>(\n options: UseApiMutationOptions<TData, TError, TVariables, TContext>,\n callbackCtx: MutationCallbackContext\n) {\n const queryClient = useRequiredFrontXQueryClient();\n\n const latestRef = useLatest({ options, callbackCtx, queryClient });\n const fetchAbortControllersRef = React.useRef<Set<AbortController>>(new Set());\n\n // Effect event: reads abortOnUnmount from the most recent render, not\n // whatever option value was current when the unmount effect was set up.\n const abortFetchesOnUnmount = React.useEffectEvent(() => {\n if (options.abortOnUnmount) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n });\n\n React.useEffect(() => {\n return () => {\n abortFetchesOnUnmount();\n };\n }, []);\n\n const mutationFn = React.useCallback((variables: TVariables, context: MutationFunctionContext) => {\n const cancelOnSupersede = latestRef.current.options.cancelOnSupersede;\n if (cancelOnSupersede) {\n for (const controller of fetchAbortControllersRef.current) {\n controller.abort();\n }\n fetchAbortControllersRef.current.clear();\n }\n\n const controller = new AbortController();\n fetchAbortControllersRef.current.add(controller);\n\n const librarySignal = (context as MutationFunctionContext & { signal?: AbortSignal }).signal;\n if (cancelOnSupersede && librarySignal) {\n if (librarySignal.aborted) {\n controller.abort();\n } else {\n librarySignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return latestRef.current.options.endpoint\n .fetch(variables, { signal: controller.signal })\n .finally(() => {\n fetchAbortControllersRef.current.delete(controller);\n });\n // latestRef's identity never changes (useLatest returns a stable ref\n // object) — listing it satisfies exhaustive-deps without recreating this\n // callback on every render.\n }, [latestRef]);\n\n // onMutate always runs: it records the scope the mutation starts under,\n // and every callback gets a queryCache bound to that scope.\n const onMutate = React.useCallback(async (\n variables: TVariables,\n mutationFnContext: MutationFunctionContext\n ): Promise<TContext | undefined> => {\n const current = latestRef.current;\n const scope: MutationScope = {\n queryClient: current.queryClient,\n generation: readQueryCacheScopeGeneration(current.queryClient),\n };\n mutationScopes.set(mutationFnContext, scope);\n return current.options.onMutate?.(\n variables,\n scopeBoundCallbackCtx(current.callbackCtx, scope)\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onSuccess = React.useCallback((\n data: TData,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onSuccess?.(\n data,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onError = React.useCallback((\n error: TError,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onError?.(\n error,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const onSettled = React.useCallback((\n data: TData | undefined,\n error: TError | null,\n variables: TVariables,\n context: TContext | undefined,\n mutationFnContext: MutationFunctionContext\n ) => {\n const current = latestRef.current;\n return current.options.onSettled?.(\n data,\n error,\n variables,\n context,\n scopeBoundCallbackCtx(current.callbackCtx, mutationScopes.get(mutationFnContext))\n );\n // latestRef's identity never changes - see mutationFn above.\n }, [latestRef]);\n\n const mutation = useMutation<TData, TError, TVariables, TContext | undefined>({\n mutationFn,\n onMutate,\n onSuccess: options.onSuccess ? onSuccess : undefined,\n onError: options.onError ? onError : undefined,\n onSettled: options.onSettled ? onSettled : undefined,\n });\n\n return {\n mutate: mutation.mutate as (variables: TVariables) => void,\n mutateAsync: mutation.mutateAsync as (variables: TVariables) => Promise<TData>,\n isPending: mutation.isPending,\n error: mutation.error,\n data: mutation.data,\n reset: mutation.reset,\n };\n}\n","/**\n * QueryCache — restricted interface for interacting with the shared QueryClient.\n *\n * MFEs and screen-set components access the cache only through this sanctioned\n * public interface. It is injected as { queryCache } into useApiMutation\n * callbacks and also returned by useQueryCache() for controlled imperative\n * cache access.\n */\n// @cpt-dod:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2\n// @cpt-flow:cpt-frontx-flow-request-lifecycle-use-api-mutation:p2:inst-create-query-cache\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n\nimport type { EndpointDescriptor } from '@gears-frontx/framework';\nimport { eventBus } from '@gears-frontx/framework';\nimport { type QueryClient, type QueryState } from '@tanstack/react-query';\n\nexport type QueryCacheKey = readonly unknown[];\nexport type QueryCacheRefetchMode = 'active' | 'inactive' | 'all' | 'none';\nexport type QueryCacheInvalidateTarget =\n | EndpointDescriptor<unknown>\n | QueryCacheKey\n | null\n | undefined;\n\nexport interface QueryCacheState<TData = unknown, TError = Error> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n fetchFailureCount: number;\n fetchFailureReason: TError | null;\n fetchStatus: 'fetching' | 'paused' | 'idle';\n isInvalidated: boolean;\n status: 'pending' | 'error' | 'success';\n}\n\nexport type QueryCacheInvalidateFilters = {\n queryKey?: QueryCacheInvalidateTarget;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n};\n\ntype QueryCacheUpdater<T> = T | ((old: T | undefined) => T | undefined);\n\ntype CacheInvalidateEvent = {\n queryKey: QueryCacheKey;\n exact?: boolean;\n refetchType?: QueryCacheRefetchMode;\n source?: string;\n};\n\ntype CacheSetEvent = {\n queryKey: QueryCacheKey;\n dataOrUpdater: QueryCacheUpdater<unknown>;\n source?: string;\n};\n\ntype CacheRemoveEvent = {\n queryKey: QueryCacheKey;\n source?: string;\n};\n\nconst QUERY_CLIENT_BROADCAST_TARGET = Symbol.for('frontx:query-cache:broadcast-target');\nconst QUERY_CLIENT_BROADCAST_COUNTER = Symbol.for('frontx:query-cache:broadcast-counter');\n\ntype QueryClientWithMetadata = QueryClient & {\n [QUERY_CLIENT_BROADCAST_TARGET]?: string;\n};\n\ntype QueryClientCounterHost = typeof globalThis & {\n [QUERY_CLIENT_BROADCAST_COUNTER]?: number;\n};\n\nfunction emitCacheEvent(event: string, payload: unknown): void {\n (eventBus.emit as (eventType: string, payload: unknown) => void)(event, payload);\n}\n\nfunction ensureBroadcastSource(queryClient: QueryClient): string {\n const clientWithMetadata = queryClient as QueryClientWithMetadata;\n const existingSource = clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET];\n if (typeof existingSource === 'string' && existingSource.length > 0) {\n return existingSource;\n }\n\n const host = globalThis as QueryClientCounterHost;\n const nextCounter = (host[QUERY_CLIENT_BROADCAST_COUNTER] ?? 0) + 1;\n host[QUERY_CLIENT_BROADCAST_COUNTER] = nextCounter;\n\n const source = `query-cache-${nextCounter}`;\n clientWithMetadata[QUERY_CLIENT_BROADCAST_TARGET] = source;\n return source;\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-resolve-key\nexport function resolveKey(target: EndpointDescriptor<unknown> | QueryCacheKey): readonly unknown[] {\n if (\n target !== null &&\n typeof target === 'object' &&\n !Array.isArray(target) &&\n 'key' in target &&\n 'fetch' in target &&\n Array.isArray(target.key) &&\n typeof target.fetch === 'function'\n ) {\n return target.key;\n }\n\n return target as readonly unknown[];\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-resolve-key\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\nexport interface QueryCache {\n get<T>(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined;\n getState<TData = unknown, TError = Error>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey\n ): QueryCacheState<TData, TError> | undefined;\n set<T>(\n queryKey: EndpointDescriptor<unknown> | QueryCacheKey,\n dataOrUpdater: T | ((old: T | undefined) => T | undefined)\n ): void;\n cancel(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidate(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void>;\n invalidateMany(filters?: QueryCacheInvalidateFilters | null): Promise<void>;\n remove(queryKey: EndpointDescriptor<unknown> | QueryCacheKey): void;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-query-cache-interface\n\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\nexport interface MutationCallbackContext {\n queryCache: QueryCache;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-mutation:p2:inst-mutation-callback-context\n\nfunction toQueryUpdater<T>(\n dataOrUpdater: QueryCacheUpdater<T>\n): (old: T | undefined) => T | undefined {\n if (typeof dataOrUpdater === 'function') {\n return dataOrUpdater as (old: T | undefined) => T | undefined;\n }\n\n return () => dataOrUpdater;\n}\n\nfunction mapQueryState<TData, TError = Error>(\n state: QueryState<TData, TError>\n): QueryCacheState<TData, TError> {\n return {\n data: state.data,\n dataUpdatedAt: state.dataUpdatedAt,\n error: state.error,\n errorUpdatedAt: state.errorUpdatedAt,\n fetchFailureCount: state.fetchFailureCount,\n fetchFailureReason: state.fetchFailureReason,\n fetchStatus: state.fetchStatus,\n isInvalidated: state.isInvalidated,\n status: state.status,\n };\n}\n\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-create-query-cache\nexport function createQueryCache(queryClient: QueryClient): QueryCache {\n return {\n get: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey): T | undefined => {\n return queryClient.getQueryData<T>(resolveKey(key));\n },\n getState: <TData = unknown, TError = Error>(key: EndpointDescriptor<unknown> | QueryCacheKey) => {\n const state = queryClient.getQueryState<TData, TError>(resolveKey(key));\n return state ? mapQueryState(state) : undefined;\n },\n set: <T,>(key: EndpointDescriptor<unknown> | QueryCacheKey, dataOrUpdater: QueryCacheUpdater<T>): void => {\n const resolvedKey = resolveKey(key);\n queryClient.setQueryData<T>(resolvedKey, toQueryUpdater(dataOrUpdater));\n emitCacheEvent('cache/set', {\n queryKey: resolvedKey,\n dataOrUpdater: dataOrUpdater as QueryCacheUpdater<unknown>,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheSetEvent);\n },\n cancel: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n return queryClient.cancelQueries({ queryKey: resolveKey(key) });\n },\n invalidate: (key: EndpointDescriptor<unknown> | QueryCacheKey): Promise<void> => {\n const resolvedKey = resolveKey(key);\n const result = queryClient.invalidateQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/invalidate', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n invalidateMany: (filters): Promise<void> => {\n if (filters?.queryKey == null) {\n return Promise.resolve();\n }\n\n const resolvedKey = resolveKey(filters.queryKey);\n if (!Array.isArray(resolvedKey) || resolvedKey.length === 0) {\n return Promise.resolve();\n }\n\n const payload = {\n ...filters,\n queryKey: resolvedKey,\n };\n const result = queryClient.invalidateQueries(payload);\n emitCacheEvent('cache/invalidate', {\n ...payload,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheInvalidateEvent);\n return result;\n },\n remove: (key: EndpointDescriptor<unknown> | QueryCacheKey): void => {\n const resolvedKey = resolveKey(key);\n queryClient.removeQueries({ queryKey: resolvedKey });\n emitCacheEvent('cache/remove', {\n queryKey: resolvedKey,\n source: ensureBroadcastSource(queryClient),\n } satisfies CacheRemoveEvent);\n },\n };\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-create-query-cache\n","/**\n * useLatest - keeps a ref pinned to the most recently rendered value\n *\n * A handful of hooks/components in this package need to read the current\n * value of a prop or option from inside a callback or effect-cleanup closure\n * that must NOT re-run every time that value changes (e.g. a stable\n * useCallback with `[]` deps, or a mount/unmount effect keyed on identity\n * rather than on every option). Stashing the value in a ref sidesteps the\n * closure staleness without pulling the value into the dependency array.\n *\n * The write happens inside a deps-less effect (runs after every commit)\n * rather than during render, because refs must not be mutated while\n * rendering: render can be invoked more than once per commit (React\n * StrictMode's double-invoke, and future concurrent-rendering paths that\n * may discard a render), so a render-time write can leave the ref out of\n * sync with what was actually committed to the DOM. A deps-less effect\n * runs exactly once per real commit, so the ref always reflects the value\n * that was last rendered.\n */\n\nimport { useEffect, useRef, type RefObject } from 'react';\n\n/**\n * Returns a ref that always holds the most recently rendered `value`.\n *\n * The ref identity is stable across renders (same object returned every\n * time), so it is safe to add to a `useCallback`/`useEffect` dependency\n * array without causing the callback/effect to be recreated.\n */\nexport function useLatest<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n\n // Deps-less: must run after every render so `ref.current` never lags\n // behind the value that was just committed. See module doc for why this\n // write cannot happen during render itself.\n useEffect(() => {\n ref.current = value;\n });\n\n return ref;\n}\n","/**\n * Test-only entry for @gears-frontx/react.\n *\n * Utilities here are intended for Vitest (or similar) suites that need access\n * to query-client wiring without importing package internals directly.\n */\n\n// @cpt-dod:cpt-frontx-dod-react-bindings-provider:p1\n\n// @cpt-begin:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\nexport {\n bootstrapFrontXQueryClient,\n resolveFrontXQueryClient,\n useOptionalFrontXQueryClient,\n} from './queryClient';\n\n/** App-layer tests must import this from `@gears-frontx/react/testing`, not `@gears-frontx/framework/testing`. */\nexport { describeBootstrapMfeContract } from '@gears-frontx/framework/testing';\nexport type {\n BootstrapMfeResolveArgs,\n BootstrapMfeTestSpecOptions,\n} from '@gears-frontx/framework/testing';\n// @cpt-end:cpt-frontx-dod-react-bindings-provider:p1:inst-react-testing-reexports\n"],"mappings":";AAAA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACZP,SAAS,gBAAgB;;;ACOzB,SAAS,WAAW,cAA8B;;;AFsI1C;AAjHR,IAAM,0BAA0B,uBAAO,IAAI,+BAA+B;AAC1E,IAAM,mCAAmC,uBAAO,IAAI,wCAAwC;AAS5F,IAAM,2BAA2B,cAAuC,MAAS;AAWjF,IAAM,kBAAkB,OAAO,WAAW,WAAW,cAAcC,aAAY;AAExE,SAAS,yBAAyB,KAAyC;AAChF,QAAM,YAAY;AAClB,SAAO,UAAU,uBAAuB,KAAK,UAAU,gCAAgC,IAAI;AAC7F;AA6BO,SAAS,2BAA2B,KAAyC;AAClF,SAAO,yBAAyB,GAAG;AACrC;AAoEO,SAAS,+BAAwD;AACtE,SAAO,WAAW,wBAAwB;AAC5C;;;AGvJA,SAAS,oCAAoC;","names":["useEffect","useEffect"]}
@@ -1,6 +1,6 @@
1
1
  import * as React from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { ChildMfeBridge, AccessRecord, AccessQuery, FrontXConfig, FrontXApp, RootState, Formatters, Language } from '@gears-frontx/framework';
3
+ import { ChildMfeBridge, AccessRecord, AccessQuery, FrontXApp, RootState, Formatters, Language } from '@gears-frontx/framework';
4
4
 
5
5
  /**
6
6
  * MFE Context Value
@@ -112,18 +112,13 @@ type TranslationParams = Record<string, string | number | boolean>;
112
112
  *
113
113
  * @example
114
114
  * ```tsx
115
- * <FrontXProvider config={{ devMode: true }}>
116
- * <App />
117
- * </FrontXProvider>
118
- *
119
- * // With pre-built app
120
- * const app = createFrontX().use(microfrontends()).build();
115
+ * const app = createFrontX().use(microfrontends(config)).build();
121
116
  * <FrontXProvider app={app}>
122
117
  * <App />
123
118
  * </FrontXProvider>
124
119
  *
125
120
  * // With MFE bridge (for MFE components)
126
- * <FrontXProvider mfeBridge={{ bridge, extensionId, domainId }}>
121
+ * <FrontXProvider app={app} mfeBridge={{ bridge, extensionId, domainId }}>
127
122
  * <MyMfeApp />
128
123
  * </FrontXProvider>
129
124
  *
@@ -136,10 +131,8 @@ type TranslationParams = Record<string, string | number | boolean>;
136
131
  interface FrontXProviderProps {
137
132
  /** Child components */
138
133
  children: ReactNode;
139
- /** FrontX configuration */
140
- config?: FrontXConfig;
141
- /** Pre-built FrontX app instance (optional) */
142
- app?: FrontXApp;
134
+ /** The runtime's FrontX app, built once by the caller */
135
+ app: FrontXApp;
143
136
  /** MFE bridge context (for MFE components) */
144
137
  mfeBridge?: MfeContextValue;
145
138
  }
@@ -1,6 +1,6 @@
1
1
  import * as React from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { ChildMfeBridge, AccessRecord, AccessQuery, FrontXConfig, FrontXApp, RootState, Formatters, Language } from '@gears-frontx/framework';
3
+ import { ChildMfeBridge, AccessRecord, AccessQuery, FrontXApp, RootState, Formatters, Language } from '@gears-frontx/framework';
4
4
 
5
5
  /**
6
6
  * MFE Context Value
@@ -112,18 +112,13 @@ type TranslationParams = Record<string, string | number | boolean>;
112
112
  *
113
113
  * @example
114
114
  * ```tsx
115
- * <FrontXProvider config={{ devMode: true }}>
116
- * <App />
117
- * </FrontXProvider>
118
- *
119
- * // With pre-built app
120
- * const app = createFrontX().use(microfrontends()).build();
115
+ * const app = createFrontX().use(microfrontends(config)).build();
121
116
  * <FrontXProvider app={app}>
122
117
  * <App />
123
118
  * </FrontXProvider>
124
119
  *
125
120
  * // With MFE bridge (for MFE components)
126
- * <FrontXProvider mfeBridge={{ bridge, extensionId, domainId }}>
121
+ * <FrontXProvider app={app} mfeBridge={{ bridge, extensionId, domainId }}>
127
122
  * <MyMfeApp />
128
123
  * </FrontXProvider>
129
124
  *
@@ -136,10 +131,8 @@ type TranslationParams = Record<string, string | number | boolean>;
136
131
  interface FrontXProviderProps {
137
132
  /** Child components */
138
133
  children: ReactNode;
139
- /** FrontX configuration */
140
- config?: FrontXConfig;
141
- /** Pre-built FrontX app instance (optional) */
142
- app?: FrontXApp;
134
+ /** The runtime's FrontX app, built once by the caller */
135
+ app: FrontXApp;
143
136
  /** MFE bridge context (for MFE components) */
144
137
  mfeBridge?: MfeContextValue;
145
138
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * @gears-frontx/react - Type Definitions\n *\n * Core types for FrontX React bindings.\n * Provides type-safe hooks and components.\n *\n * Now using real imports from @gears-frontx/framework since packages are built together.\n */\n\nimport type { ReactNode } from 'react';\nimport type {\n FrontXConfig,\n FrontXApp,\n RootState,\n Language,\n Formatters,\n AccessQuery,\n AccessRecord,\n} from '@gears-frontx/framework';\nimport type { MfeContextValue } from './mfe/MfeContext';\n\n// Re-export imported types for convenience\nexport type { FrontXConfig, FrontXApp };\n\n// ============================================================================\n// API Hook Result Types\n// ============================================================================\n\n/**\n * Gears FrontX-owned query result type.\n * Returned by useApiQuery — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-api-query-result\nexport interface ApiQueryResult<TData, TError = Error> {\n data: TData | undefined;\n error: TError | null;\n isLoading: boolean;\n isFetching: boolean;\n isError: boolean;\n refetch: () => Promise<unknown>;\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-api-query-result\n\n/**\n * Gears FrontX-owned suspense query result type.\n * Returned by useApiSuspenseQuery — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-query-result\nexport interface ApiSuspenseQueryResult<TData, TError = Error> {\n data: TData;\n error: TError | null;\n isFetching: boolean;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-query-result\n\n/**\n * Gears FrontX-owned infinite query result type.\n * Returned by useApiInfiniteQuery for descriptor-driven pagination.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-infinite-query-result\nexport interface ApiInfiniteQueryResult<TPage, TError = Error> {\n data: readonly TPage[] | undefined;\n error: TError | null;\n isLoading: boolean;\n isFetching: boolean;\n isError: boolean;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n isFetchingPreviousPage: boolean;\n fetchNextPage: () => Promise<void>;\n fetchPreviousPage: () => Promise<void>;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-infinite-query-result\n\n/**\n * Gears FrontX-owned suspense infinite query result type.\n * Returned by useApiSuspenseInfiniteQuery for descriptor-driven pagination.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-infinite-query-result\nexport interface ApiSuspenseInfiniteQueryResult<TPage, TError = Error> {\n data: readonly TPage[];\n error: TError | null;\n isFetching: boolean;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n isFetchingPreviousPage: boolean;\n fetchNextPage: () => Promise<void>;\n fetchPreviousPage: () => Promise<void>;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-infinite-query-result\n\n/**\n * Gears FrontX-owned mutation result type.\n * Returned by useApiMutation — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-api-mutation-result\nexport interface ApiMutationResult<TData, TError = Error, TVariables = void> {\n mutate: (variables: TVariables) => void;\n mutateAsync: (variables: TVariables) => Promise<TData>;\n isPending: boolean;\n error: TError | null;\n data: TData | undefined;\n reset: () => void;\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-api-mutation-result\n\n// ============================================================================\n// Type Aliases\n// ============================================================================\n\n// From @gears-frontx/store\ntype Selector<TResult, TState = RootState> = (state: TState) => TResult;\n\n// Language is imported from @gears-frontx/framework\ntype TranslationParams = Record<string, string | number | boolean>;\n\n// ============================================================================\n// FrontX Provider Props\n// ============================================================================\n\n/**\n * FrontX Provider Props\n * Props for the main FrontXProvider component.\n *\n * @example\n * ```tsx\n * <FrontXProvider config={{ devMode: true }}>\n * <App />\n * </FrontXProvider>\n *\n * // With pre-built app\n * const app = createFrontX().use(microfrontends()).build();\n * <FrontXProvider app={app}>\n * <App />\n * </FrontXProvider>\n *\n * // With MFE bridge (for MFE components)\n * <FrontXProvider mfeBridge={{ bridge, extensionId, domainId }}>\n * <MyMfeApp />\n * </FrontXProvider>\n *\n * // QueryCache is resolved from the app's plugin composition\n * <FrontXProvider app={app}>\n * <MyMfeApp />\n * </FrontXProvider>\n * ```\n */\nexport interface FrontXProviderProps {\n /** Child components */\n children: ReactNode;\n /** FrontX configuration */\n config?: FrontXConfig;\n /** Pre-built FrontX app instance (optional) */\n app?: FrontXApp;\n /** MFE bridge context (for MFE components) */\n mfeBridge?: MfeContextValue;\n}\n\n// ============================================================================\n// Hook Return Types\n// ============================================================================\n\n/**\n * useFrontX Hook Return Type\n * Returns the FrontX app instance from context.\n */\nexport type UseFrontXReturn = FrontXApp;\n\n/**\n * useAppSelector Hook\n * Type-safe selector hook for Redux state.\n *\n * @template TResult - The result type of the selector\n */\nexport type UseAppSelector = <TResult>(selector: Selector<TResult>) => TResult;\n\n/**\n * useAppDispatch Hook Return Type\n * Returns the typed dispatch function.\n */\nexport type UseAppDispatchReturn = (action: unknown) => unknown;\n\n/**\n * useTranslation Hook Return Type\n * Translation utilities.\n */\nexport interface UseTranslationReturn {\n /** Translate a key */\n t: (key: string, params?: TranslationParams) => string;\n /** Current language */\n language: Language | null;\n /** Change language */\n setLanguage: (language: Language) => void;\n /** Check if current language is RTL */\n isRTL: boolean;\n}\n\n/**\n * useScreenTranslations Hook Return Type\n * Screen-level translation loading state.\n */\nexport interface UseScreenTranslationsReturn {\n /** Whether translations are loaded */\n isLoaded: boolean;\n /** Loading error (if any) */\n error: Error | null;\n}\n\n/**\n * useTheme Hook Return Type\n * Theme utilities.\n */\nexport interface UseThemeReturn {\n /** Current theme ID */\n currentTheme: string | undefined;\n /** All available themes */\n themes: Array<{ id: string; name: string }>;\n /** Change theme */\n setTheme: (themeId: string) => void;\n}\n\n/**\n * useFormatters Hook Return Type\n * Locale-aware formatters (locale from i18nRegistry.getLanguage()).\n * References @gears-frontx/i18n Formatters so signatures stay in sync.\n */\nexport type UseFormattersReturn = Formatters;\n\n/**\n * useCanAccess Hook Return Type\n * Result of an RBAC access check.\n * allow is false until an explicit 'allow' decision arrives (pessimistic default).\n */\nexport interface UseCanAccessResult {\n allow: boolean;\n isResolving: boolean;\n}\n\n/**\n * CanAccess Component Props.\n * Pessimistic: renders `denied` (or `loading`) until an authoritative 'allow' arrives.\n */\nexport interface CanAccessProps<TRecord extends AccessRecord = AccessRecord> {\n query: AccessQuery<TRecord>;\n /** Content rendered when access is explicitly allowed. */\n allowed: ReactNode;\n /** Content rendered on deny or error. Defaults to null. */\n denied?: ReactNode;\n /** Optional slot shown while the decision is resolving. Falls back to `denied`. */\n loading?: ReactNode;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * @gears-frontx/react - Type Definitions\n *\n * Core types for FrontX React bindings.\n * Provides type-safe hooks and components.\n *\n * Now using real imports from @gears-frontx/framework since packages are built together.\n */\n\nimport type { ReactNode } from 'react';\nimport type {\n FrontXConfig,\n FrontXApp,\n RootState,\n Language,\n Formatters,\n AccessQuery,\n AccessRecord,\n} from '@gears-frontx/framework';\nimport type { MfeContextValue } from './mfe/MfeContext';\n\n// Re-export imported types for convenience\nexport type { FrontXConfig, FrontXApp };\n\n// ============================================================================\n// API Hook Result Types\n// ============================================================================\n\n/**\n * Gears FrontX-owned query result type.\n * Returned by useApiQuery — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-FEATURE:implement-endpoint-descriptors:p3\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-api-query-result\nexport interface ApiQueryResult<TData, TError = Error> {\n data: TData | undefined;\n error: TError | null;\n isLoading: boolean;\n isFetching: boolean;\n isError: boolean;\n refetch: () => Promise<unknown>;\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-api-query-result\n\n/**\n * Gears FrontX-owned suspense query result type.\n * Returned by useApiSuspenseQuery — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-query-result\nexport interface ApiSuspenseQueryResult<TData, TError = Error> {\n data: TData;\n error: TError | null;\n isFetching: boolean;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-query-result\n\n/**\n * Gears FrontX-owned infinite query result type.\n * Returned by useApiInfiniteQuery for descriptor-driven pagination.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-infinite-query-result\nexport interface ApiInfiniteQueryResult<TPage, TError = Error> {\n data: readonly TPage[] | undefined;\n error: TError | null;\n isLoading: boolean;\n isFetching: boolean;\n isError: boolean;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n isFetchingPreviousPage: boolean;\n fetchNextPage: () => Promise<void>;\n fetchPreviousPage: () => Promise<void>;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-infinite-query-result\n\n/**\n * Gears FrontX-owned suspense infinite query result type.\n * Returned by useApiSuspenseInfiniteQuery for descriptor-driven pagination.\n */\n// @cpt-begin:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-infinite-query-result\nexport interface ApiSuspenseInfiniteQueryResult<TPage, TError = Error> {\n data: readonly TPage[];\n error: TError | null;\n isFetching: boolean;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n isFetchingPreviousPage: boolean;\n fetchNextPage: () => Promise<void>;\n fetchPreviousPage: () => Promise<void>;\n refetch: () => Promise<void>;\n}\n// @cpt-end:cpt-frontx-dod-request-lifecycle-use-api-query:p2:inst-suspense-infinite-query-result\n\n/**\n * Gears FrontX-owned mutation result type.\n * Returned by useApiMutation — callers depend on this contract, not on TanStack internals.\n */\n// @cpt-begin:implement-endpoint-descriptors:p3:inst-api-mutation-result\nexport interface ApiMutationResult<TData, TError = Error, TVariables = void> {\n mutate: (variables: TVariables) => void;\n mutateAsync: (variables: TVariables) => Promise<TData>;\n isPending: boolean;\n error: TError | null;\n data: TData | undefined;\n reset: () => void;\n}\n// @cpt-end:implement-endpoint-descriptors:p3:inst-api-mutation-result\n\n// ============================================================================\n// Type Aliases\n// ============================================================================\n\n// From @gears-frontx/store\ntype Selector<TResult, TState = RootState> = (state: TState) => TResult;\n\n// Language is imported from @gears-frontx/framework\ntype TranslationParams = Record<string, string | number | boolean>;\n\n// ============================================================================\n// FrontX Provider Props\n// ============================================================================\n\n/**\n * FrontX Provider Props\n * Props for the main FrontXProvider component.\n *\n * @example\n * ```tsx\n * const app = createFrontX().use(microfrontends(config)).build();\n * <FrontXProvider app={app}>\n * <App />\n * </FrontXProvider>\n *\n * // With MFE bridge (for MFE components)\n * <FrontXProvider app={app} mfeBridge={{ bridge, extensionId, domainId }}>\n * <MyMfeApp />\n * </FrontXProvider>\n *\n * // QueryCache is resolved from the app's plugin composition\n * <FrontXProvider app={app}>\n * <MyMfeApp />\n * </FrontXProvider>\n * ```\n */\nexport interface FrontXProviderProps {\n /** Child components */\n children: ReactNode;\n /** The runtime's FrontX app, built once by the caller */\n app: FrontXApp;\n /** MFE bridge context (for MFE components) */\n mfeBridge?: MfeContextValue;\n}\n\n// ============================================================================\n// Hook Return Types\n// ============================================================================\n\n/**\n * useFrontX Hook Return Type\n * Returns the FrontX app instance from context.\n */\nexport type UseFrontXReturn = FrontXApp;\n\n/**\n * useAppSelector Hook\n * Type-safe selector hook for Redux state.\n *\n * @template TResult - The result type of the selector\n */\nexport type UseAppSelector = <TResult>(selector: Selector<TResult>) => TResult;\n\n/**\n * useAppDispatch Hook Return Type\n * Returns the typed dispatch function.\n */\nexport type UseAppDispatchReturn = (action: unknown) => unknown;\n\n/**\n * useTranslation Hook Return Type\n * Translation utilities.\n */\nexport interface UseTranslationReturn {\n /** Translate a key */\n t: (key: string, params?: TranslationParams) => string;\n /** Current language */\n language: Language | null;\n /** Change language */\n setLanguage: (language: Language) => void;\n /** Check if current language is RTL */\n isRTL: boolean;\n}\n\n/**\n * useScreenTranslations Hook Return Type\n * Screen-level translation loading state.\n */\nexport interface UseScreenTranslationsReturn {\n /** Whether translations are loaded */\n isLoaded: boolean;\n /** Loading error (if any) */\n error: Error | null;\n}\n\n/**\n * useTheme Hook Return Type\n * Theme utilities.\n */\nexport interface UseThemeReturn {\n /** Current theme ID */\n currentTheme: string | undefined;\n /** All available themes */\n themes: Array<{ id: string; name: string }>;\n /** Change theme */\n setTheme: (themeId: string) => void;\n}\n\n/**\n * useFormatters Hook Return Type\n * Locale-aware formatters (locale from i18nRegistry.getLanguage()).\n * References @gears-frontx/i18n Formatters so signatures stay in sync.\n */\nexport type UseFormattersReturn = Formatters;\n\n/**\n * useCanAccess Hook Return Type\n * Result of an RBAC access check.\n * allow is false until an explicit 'allow' decision arrives (pessimistic default).\n */\nexport interface UseCanAccessResult {\n allow: boolean;\n isResolving: boolean;\n}\n\n/**\n * CanAccess Component Props.\n * Pessimistic: renders `denied` (or `loading`) until an authoritative 'allow' arrives.\n */\nexport interface CanAccessProps<TRecord extends AccessRecord = AccessRecord> {\n query: AccessQuery<TRecord>;\n /** Content rendered when access is explicitly allowed. */\n allowed: ReactNode;\n /** Content rendered on deny or error. Defaults to null. */\n denied?: ReactNode;\n /** Optional slot shown while the decision is resolving. Falls back to `denied`. */\n loading?: ReactNode;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
package/dist/types.d.cts CHANGED
@@ -1,3 +1,3 @@
1
1
  import 'react';
2
2
  export { FrontXApp, FrontXConfig } from '@gears-frontx/framework';
3
- export { a as ApiInfiniteQueryResult, b as ApiMutationResult, A as ApiQueryResult, g as ApiSuspenseInfiniteQueryResult, f as ApiSuspenseQueryResult, C as CanAccessProps, F as FrontXProviderProps, j as UseAppDispatchReturn, k as UseAppSelector, h as UseCanAccessResult, d as UseFormattersReturn, l as UseFrontXReturn, c as UseScreenTranslationsReturn, e as UseThemeReturn, U as UseTranslationReturn } from './types-Cjd20AT-.cjs';
3
+ export { a as ApiInfiniteQueryResult, b as ApiMutationResult, A as ApiQueryResult, g as ApiSuspenseInfiniteQueryResult, f as ApiSuspenseQueryResult, C as CanAccessProps, F as FrontXProviderProps, j as UseAppDispatchReturn, k as UseAppSelector, h as UseCanAccessResult, d as UseFormattersReturn, l as UseFrontXReturn, c as UseScreenTranslationsReturn, e as UseThemeReturn, U as UseTranslationReturn } from './types-JtpziA_B.cjs';
package/dist/types.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import 'react';
2
2
  export { FrontXApp, FrontXConfig } from '@gears-frontx/framework';
3
- export { a as ApiInfiniteQueryResult, b as ApiMutationResult, A as ApiQueryResult, g as ApiSuspenseInfiniteQueryResult, f as ApiSuspenseQueryResult, C as CanAccessProps, F as FrontXProviderProps, j as UseAppDispatchReturn, k as UseAppSelector, h as UseCanAccessResult, d as UseFormattersReturn, l as UseFrontXReturn, c as UseScreenTranslationsReturn, e as UseThemeReturn, U as UseTranslationReturn } from './types-Cjd20AT-.js';
3
+ export { a as ApiInfiniteQueryResult, b as ApiMutationResult, A as ApiQueryResult, g as ApiSuspenseInfiniteQueryResult, f as ApiSuspenseQueryResult, C as CanAccessProps, F as FrontXProviderProps, j as UseAppDispatchReturn, k as UseAppSelector, h as UseCanAccessResult, d as UseFormattersReturn, l as UseFrontXReturn, c as UseScreenTranslationsReturn, e as UseThemeReturn, U as UseTranslationReturn } from './types-JtpziA_B.js';