@frontic/nuxt 1.1.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -1
- package/dist/module.json +1 -1
- package/dist/runtime/composables/analytics.d.ts +7 -1
- package/dist/runtime/composables/blocks.js +3 -3
- package/dist/runtime/composables/listings.d.ts +22 -0
- package/dist/runtime/composables/listings.js +30 -15
- package/dist/runtime/composables/pages.js +3 -3
- package/dist/runtime/composables/trees.js +3 -3
- package/dist/runtime/composables/useFronticBlock.js +4 -2
- package/dist/runtime/composables/useFronticClient.d.ts +30 -0
- package/dist/runtime/composables/useFronticClient.js +45 -22
- package/dist/runtime/composables/useFronticContext.d.ts +4 -1
- package/dist/runtime/composables/useFronticContext.js +15 -20
- package/dist/runtime/composables/useFronticListing.d.ts +10 -4
- package/dist/runtime/composables/useFronticListing.js +6 -2
- package/dist/runtime/composables/useFronticPage.js +4 -2
- package/dist/runtime/composables/useFronticSearch.js +49 -13
- package/dist/runtime/composables/useFronticTree.js +4 -2
- package/dist/runtime/composables/useSearchUrlSync.d.ts +39 -0
- package/dist/runtime/composables/useSearchUrlSync.js +53 -0
- package/dist/runtime/server/client.d.ts +55 -0
- package/dist/runtime/server/client.js +53 -0
- package/dist/runtime/types/index.d.ts +1 -1
- package/dist/runtime/types/listing.d.ts +38 -2
- package/dist/runtime/types/options.d.ts +18 -4
- package/dist/runtime/types/registry.d.ts +21 -2
- package/dist/runtime/types/search.d.ts +63 -2
- package/dist/runtime/utils/describe-error.d.ts +19 -0
- package/dist/runtime/utils/describe-error.js +16 -0
- package/dist/runtime/utils/query-keys.d.ts +10 -5
- package/dist/runtime/utils/query-keys.js +5 -0
- package/dist/runtime/utils/request-defaults.d.ts +11 -0
- package/dist/runtime/utils/request-defaults.js +8 -0
- package/dist/runtime/utils/resolve-context-key.d.ts +30 -0
- package/dist/runtime/utils/resolve-context-key.js +37 -0
- package/dist/runtime/utils/search-url.d.ts +90 -0
- package/dist/runtime/utils/search-url.js +184 -0
- package/dist/runtime/utils/state-helpers.d.ts +13 -0
- package/dist/runtime/utils/state-helpers.js +6 -0
- package/package.json +5 -1
|
@@ -2,6 +2,7 @@ import { useState, useNuxtApp } from "nuxt/app";
|
|
|
2
2
|
import { computed, ref, toValue, watch } from "vue";
|
|
3
3
|
import { useQuery, useInfiniteQuery, useQueryCache, setInfiniteQueryData } from "@pinia/colada";
|
|
4
4
|
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
5
|
+
import { resolveContextKey, resolveCallContextKey } from "../utils/resolve-context-key.js";
|
|
5
6
|
import { useDebounceFn } from "@vueuse/core";
|
|
6
7
|
import {
|
|
7
8
|
makeLogicalFilter,
|
|
@@ -13,19 +14,22 @@ import {
|
|
|
13
14
|
seedFilterLists
|
|
14
15
|
} from "../utils/filter-helpers.js";
|
|
15
16
|
import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
|
|
16
|
-
import {
|
|
17
|
+
import { normalizeUrlQuerySyncConfig } from "../utils/search-url.js";
|
|
18
|
+
import { fetchListingQuery, listingQueryOptions, seedInitialData, LISTING_QUERY_KEYS } from "./listings.js";
|
|
17
19
|
import { useFronticClient } from "./useFronticClient.js";
|
|
20
|
+
import { useSearchUrlSync } from "./useSearchUrlSync.js";
|
|
18
21
|
import { emit, emitOnce, bindRouteReset, toAnalyticsItems, FRONTIC_ANALYTICS_VERSION } from "./analytics.js";
|
|
19
22
|
export function useFronticSearch(name, ...args) {
|
|
20
23
|
const [rawParams, options] = args;
|
|
21
24
|
const params = rawParams ?? {};
|
|
22
25
|
const queryCache = useQueryCache();
|
|
23
|
-
const _client = useFronticClient({ contextDomain: false });
|
|
26
|
+
const _client = useFronticClient({ contextDomain: false, contextKey: false });
|
|
24
27
|
const listingName = name;
|
|
25
28
|
const nuxtApp = useNuxtApp();
|
|
26
29
|
bindRouteReset(nuxtApp);
|
|
27
30
|
const cacheKey = options?.cacheKey ?? String(name);
|
|
28
|
-
const
|
|
31
|
+
const autoContextKey = resolveContextKey();
|
|
32
|
+
const contextKey = computed(() => resolveCallContextKey(toValue(options?.contextKey), autoContextKey));
|
|
29
33
|
const autoContextDomain = resolveContextDomain();
|
|
30
34
|
const contextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
31
35
|
const requestUrl = options?.requestUrl;
|
|
@@ -98,6 +102,32 @@ export function useFronticSearch(name, ...args) {
|
|
|
98
102
|
limit: toValue(options?.limit)
|
|
99
103
|
})
|
|
100
104
|
);
|
|
105
|
+
const urlSyncConfig = options?.urlQuerySync ? normalizeUrlQuerySyncConfig(options.urlQuerySync, { filterConfig, sortConfig, orFilter, disableSearch, disableFilter, disableSorting }) : void 0;
|
|
106
|
+
if (urlSyncConfig) {
|
|
107
|
+
useSearchUrlSync({
|
|
108
|
+
config: urlSyncConfig,
|
|
109
|
+
refs: { searchTerm, committedSearch: _search, orFilterList: _orFilterList, andFilterList: _andFilterList, rangeFilterList: _rangeFilterList, sortQuery: _sortQuery, page: _page },
|
|
110
|
+
gatedSearch: () => apiQuery.value.search,
|
|
111
|
+
onExternalChange: () => withIntent("url")
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (import.meta.dev && options?.initialData) {
|
|
115
|
+
const seededState = [
|
|
116
|
+
!disableFilter && (_orFilterList.value.length || _andFilterList.value.length || _rangeFilterList.value.length) ? "filters" : "",
|
|
117
|
+
!disableSorting && _sortQuery.value ? "a sort" : "",
|
|
118
|
+
!disableSearch && _search.value ? "a search term" : "",
|
|
119
|
+
// `_page` starts undefined and only a navigation or the URL sync writes
|
|
120
|
+
// it, so `initialPage` has to be read the same way the cursor below reads
|
|
121
|
+
// it. In infinite mode this is the one mismatch the key guard cannot
|
|
122
|
+
// catch at all — page is a cursor there, deliberately absent from the key.
|
|
123
|
+
(_page.value ?? initialPage) > 1 ? "a page" : ""
|
|
124
|
+
].filter(Boolean);
|
|
125
|
+
if (seededState.length) {
|
|
126
|
+
console.warn(
|
|
127
|
+
`[@frontic/nuxt] useFronticSearch('${String(name)}') starts with ${seededState.join(", ")} applied and was given \`initialData\`. The seed is used for that query, so it must be the response to it \u2014 return \`undefined\` from the getter when your payload does not match.`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
101
131
|
const queryConfig = {
|
|
102
132
|
name: listingName,
|
|
103
133
|
params,
|
|
@@ -109,6 +139,8 @@ export function useFronticSearch(name, ...args) {
|
|
|
109
139
|
gcTime: options?.gcTime,
|
|
110
140
|
enabled: options?.enabled,
|
|
111
141
|
keepPreviousData: options?.keepPreviousData,
|
|
142
|
+
initialData: options?.initialData,
|
|
143
|
+
initialDataUpdatedAt: options?.initialDataUpdatedAt,
|
|
112
144
|
_client
|
|
113
145
|
};
|
|
114
146
|
let data;
|
|
@@ -121,9 +153,10 @@ export function useFronticSearch(name, ...args) {
|
|
|
121
153
|
let loadNextFn;
|
|
122
154
|
let loadPrevFn;
|
|
123
155
|
let loadPageFn;
|
|
156
|
+
const infiniteKey = () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value, toValue(contextKey), toValue(contextDomain));
|
|
124
157
|
if (infinite) {
|
|
125
158
|
const infiniteResult = useInfiniteQuery({
|
|
126
|
-
key:
|
|
159
|
+
key: infiniteKey,
|
|
127
160
|
// `_page` seeds the starting cursor (e.g. deep-linked page from the URL); it deliberately does NOT enter the
|
|
128
161
|
// key above — in infinite mode page is a cursor, not an identity, so keying on it would reset accumulation.
|
|
129
162
|
initialPageParam: _page.value ?? initialPage,
|
|
@@ -152,7 +185,17 @@ export function useFronticSearch(name, ...args) {
|
|
|
152
185
|
// Typed against the accumulated page set, not a single response: in
|
|
153
186
|
// infinite mode `placeholderData` receives what the cache holds, which is
|
|
154
187
|
// every page fetched so far.
|
|
155
|
-
...listingQueryOptions(
|
|
188
|
+
...listingQueryOptions({
|
|
189
|
+
...queryConfig,
|
|
190
|
+
// Assigned rather than conditionally spread: it has to *replace* the
|
|
191
|
+
// single-response getter `queryConfig` carries, not union with it.
|
|
192
|
+
// The caller hands over one response, the same as in standard mode; the
|
|
193
|
+
// page set it seeds is this module's shape, not theirs.
|
|
194
|
+
initialData: options?.initialData && seedInitialData(infiniteKey, () => {
|
|
195
|
+
const seed = options.initialData();
|
|
196
|
+
return seed === void 0 ? void 0 : { pages: [seed], pageParams: [_page.value ?? initialPage] };
|
|
197
|
+
})
|
|
198
|
+
})
|
|
156
199
|
});
|
|
157
200
|
const flattenedData = computed(() => {
|
|
158
201
|
const pages = infiniteResult.data.value?.pages;
|
|
@@ -188,14 +231,7 @@ export function useFronticSearch(name, ...args) {
|
|
|
188
231
|
});
|
|
189
232
|
const response = await pagedQueryFactory.query();
|
|
190
233
|
if (response) {
|
|
191
|
-
|
|
192
|
-
String(listingName),
|
|
193
|
-
toValue(params),
|
|
194
|
-
apiQuery.value,
|
|
195
|
-
toValue(contextKey),
|
|
196
|
-
toValue(contextDomain)
|
|
197
|
-
);
|
|
198
|
-
setInfiniteQueryData(queryCache, listKey, { pages: [response], pageParams: [page] });
|
|
234
|
+
setInfiniteQueryData(queryCache, infiniteKey(), { pages: [response], pageParams: [page] });
|
|
199
235
|
updateState(response);
|
|
200
236
|
emitListingResolved(response, "page");
|
|
201
237
|
}
|
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import { computed, toValue } from "vue";
|
|
2
2
|
import { useQuery } from "@pinia/colada";
|
|
3
3
|
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
4
|
+
import { resolveContextKey, resolveCallContextKey } from "../utils/resolve-context-key.js";
|
|
4
5
|
import { fetchTreeQuery } from "./trees.js";
|
|
5
6
|
import { useFronticClient } from "./useFronticClient.js";
|
|
6
7
|
export function useFronticTree(name, options) {
|
|
7
|
-
const _client = useFronticClient({ contextDomain: false });
|
|
8
|
+
const _client = useFronticClient({ contextDomain: false, contextKey: false });
|
|
8
9
|
const autoContextDomain = resolveContextDomain();
|
|
10
|
+
const autoContextKey = resolveContextKey();
|
|
9
11
|
const resolvedContextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
10
12
|
const treeQuery = fetchTreeQuery({
|
|
11
13
|
name,
|
|
12
14
|
key: options?.key,
|
|
13
15
|
depth: options?.depth,
|
|
14
|
-
contextKey: options?.contextKey,
|
|
16
|
+
contextKey: computed(() => resolveCallContextKey(toValue(options?.contextKey), autoContextKey)),
|
|
15
17
|
contextDomain: resolvedContextDomain,
|
|
16
18
|
requestUrl: options?.requestUrl,
|
|
17
19
|
staleTime: options?.staleTime,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useSearchUrlSync
|
|
3
|
+
*
|
|
4
|
+
* Router glue for useFronticSearch's opt-in URL query sync. Kept separate from the pure codec
|
|
5
|
+
* (utils/search-url) so all decisions stay testable and only this thin layer touches Nuxt.
|
|
6
|
+
*
|
|
7
|
+
* Internal — not auto-imported. Consumers enable it via `useFronticSearch(..., { urlQuerySync })`.
|
|
8
|
+
*/
|
|
9
|
+
import { type Ref } from 'vue';
|
|
10
|
+
import type { EqualsFilter, RangeFilter } from '../utils/filter-helpers.js';
|
|
11
|
+
import { type SearchUrlCodecConfig } from '../utils/search-url.js';
|
|
12
|
+
interface SearchUrlSyncRefs {
|
|
13
|
+
searchTerm: Ref<string>;
|
|
14
|
+
/**
|
|
15
|
+
* The committed term the query body reads. Written alongside `searchTerm` and never gated by
|
|
16
|
+
* `searchTermThreshold`: the threshold exists to stop a request per keystroke, and a term that
|
|
17
|
+
* arrived in the URL was not typed. The watcher that normally promotes one to the other does not
|
|
18
|
+
* run during SSR, so a URL term that only reached `searchTerm` would never reach the request.
|
|
19
|
+
*/
|
|
20
|
+
committedSearch: Ref<string | undefined>;
|
|
21
|
+
orFilterList: Ref<EqualsFilter[]>;
|
|
22
|
+
andFilterList: Ref<EqualsFilter[]>;
|
|
23
|
+
rangeFilterList: Ref<RangeFilter[]>;
|
|
24
|
+
sortQuery: Ref<{
|
|
25
|
+
field: string;
|
|
26
|
+
order: 'asc' | 'desc';
|
|
27
|
+
} | undefined>;
|
|
28
|
+
page: Ref<number | undefined>;
|
|
29
|
+
}
|
|
30
|
+
export interface UseSearchUrlSyncContext {
|
|
31
|
+
config: SearchUrlCodecConfig;
|
|
32
|
+
refs: SearchUrlSyncRefs;
|
|
33
|
+
/** The threshold-gated search term (apiQuery.search) — what the URL should reflect. */
|
|
34
|
+
gatedSearch: () => string | undefined;
|
|
35
|
+
/** Called after state is changed by an external URL change (back/forward), to refetch. */
|
|
36
|
+
onExternalChange: () => unknown;
|
|
37
|
+
}
|
|
38
|
+
export declare function useSearchUrlSync(ctx: UseSearchUrlSyncContext): void;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { useRoute, useRouter } from "nuxt/app";
|
|
2
|
+
import { watch } from "vue";
|
|
3
|
+
import { createSearchUrlCodec } from "../utils/search-url.js";
|
|
4
|
+
export function useSearchUrlSync(ctx) {
|
|
5
|
+
const { config, refs } = ctx;
|
|
6
|
+
if (import.meta.dev) {
|
|
7
|
+
for (const warning of config.warnings) console.warn(`[@frontic/nuxt] useFronticSearch urlQuerySync: ${warning}`);
|
|
8
|
+
}
|
|
9
|
+
const route = useRoute();
|
|
10
|
+
const router = useRouter();
|
|
11
|
+
if (!route || !router) {
|
|
12
|
+
if (import.meta.dev) console.warn("[@frontic/nuxt] useFronticSearch `urlQuerySync` needs a Nuxt app with a router \u2014 skipping URL sync.");
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const codec = createSearchUrlCodec(config);
|
|
16
|
+
const readState = () => ({
|
|
17
|
+
search: refs.searchTerm.value,
|
|
18
|
+
sort: refs.sortQuery.value,
|
|
19
|
+
or: refs.orFilterList.value,
|
|
20
|
+
and: refs.andFilterList.value,
|
|
21
|
+
range: refs.rangeFilterList.value,
|
|
22
|
+
page: refs.page.value
|
|
23
|
+
});
|
|
24
|
+
function applyFromUrl() {
|
|
25
|
+
const current = readState();
|
|
26
|
+
const next = codec.decode(route.query, current);
|
|
27
|
+
if (codec.canonical(next) === codec.canonical(current)) return false;
|
|
28
|
+
refs.searchTerm.value = next.search ?? "";
|
|
29
|
+
refs.committedSearch.value = next.search || void 0;
|
|
30
|
+
refs.sortQuery.value = next.sort;
|
|
31
|
+
refs.orFilterList.value = next.or;
|
|
32
|
+
refs.andFilterList.value = next.and;
|
|
33
|
+
refs.rangeFilterList.value = next.range;
|
|
34
|
+
refs.page.value = next.page;
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
applyFromUrl();
|
|
38
|
+
if (import.meta.server) return;
|
|
39
|
+
watch(
|
|
40
|
+
() => codec.ownedSignature(route.query),
|
|
41
|
+
() => {
|
|
42
|
+
if (applyFromUrl()) void ctx.onExternalChange();
|
|
43
|
+
}
|
|
44
|
+
);
|
|
45
|
+
function flush(history) {
|
|
46
|
+
const owned = codec.encode({ ...readState(), search: ctx.gatedSearch() });
|
|
47
|
+
const { query, changed } = codec.merge(route.query, owned);
|
|
48
|
+
if (!changed) return;
|
|
49
|
+
void router[history]({ path: route.path, query, hash: route.hash });
|
|
50
|
+
}
|
|
51
|
+
watch([refs.orFilterList, refs.andFilterList, refs.rangeFilterList, refs.sortQuery, refs.page], () => flush(config.history));
|
|
52
|
+
watch(refs.committedSearch, () => flush("replace"));
|
|
53
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frontic client for Nitro.
|
|
3
|
+
*
|
|
4
|
+
* `useFronticClient` is a Nuxt app composable — it reaches for `useNuxtApp`,
|
|
5
|
+
* `useRequestURL` and `nuxt/app`'s `useRuntimeConfig`, none of which exist in a
|
|
6
|
+
* server route. Without this, a `server/` handler builds the generated client
|
|
7
|
+
* itself and silently loses everything the app client resolves: the context
|
|
8
|
+
* domain, the visitor's token, the originating URL, and any report of a
|
|
9
|
+
* failure.
|
|
10
|
+
*
|
|
11
|
+
* The token matters most. It sits in the request's own `fs-context` cookie, and
|
|
12
|
+
* a route that does not forward it answers with the domain's defaults — the
|
|
13
|
+
* same silent wrong-context bug the composables had, in the one place there is
|
|
14
|
+
* no rendered page to notice it on.
|
|
15
|
+
*
|
|
16
|
+
* The API secret is not resolved here: the module's Nitro plugin stamps
|
|
17
|
+
* `fs-secret` onto every request the generated client makes, this one included.
|
|
18
|
+
*/
|
|
19
|
+
import { type H3Event } from 'h3';
|
|
20
|
+
import type { FronticClient } from '../types/client.js';
|
|
21
|
+
export interface FronticServerClientOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Override the context domain sent as `fs-domain`
|
|
24
|
+
* - `false`: send none
|
|
25
|
+
* - `string`: use this domain
|
|
26
|
+
* - `undefined`: use the module's configured `contextDomain`
|
|
27
|
+
*
|
|
28
|
+
* `contextDomain: true` (read the active i18n locale) cannot be honoured here
|
|
29
|
+
* — there is no i18n instance in Nitro — so a project configured that way
|
|
30
|
+
* resolves nothing and should pass the domain per call.
|
|
31
|
+
*/
|
|
32
|
+
contextDomain?: false | string;
|
|
33
|
+
/**
|
|
34
|
+
* Override the context token sent as `fs-context`
|
|
35
|
+
* - `false`: send none, so the request resolves through the domain alone
|
|
36
|
+
* - `string`: use this token
|
|
37
|
+
* - `undefined`: read the request's context cookie
|
|
38
|
+
*
|
|
39
|
+
* Whether that cookie is read at all follows the **module's** `disableContext`,
|
|
40
|
+
* not any per-instance override. `useFronticContext({ disableContext })` is a
|
|
41
|
+
* decision made inside the Nuxt app, and a Nitro route has no way to learn it —
|
|
42
|
+
* it has the request and the config, nothing else. An app that overrides the
|
|
43
|
+
* module setting in a component and also fetches from a server route passes
|
|
44
|
+
* `contextKey` here explicitly.
|
|
45
|
+
*/
|
|
46
|
+
contextKey?: false | string;
|
|
47
|
+
/**
|
|
48
|
+
* Override the URL recorded with the request
|
|
49
|
+
* - `false`: send none
|
|
50
|
+
* - `string`: use this URL
|
|
51
|
+
* - `undefined`: the URL of the incoming request
|
|
52
|
+
*/
|
|
53
|
+
requestUrl?: false | string;
|
|
54
|
+
}
|
|
55
|
+
export declare function createFronticServerClient(event: H3Event, options?: FronticServerClientOptions): FronticClient;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { getCookie, getRequestURL } from "h3";
|
|
2
|
+
import { useRuntimeConfig, useNitroApp } from "nitropack/runtime";
|
|
3
|
+
import { createClient } from "@frontic/stack/generated-client";
|
|
4
|
+
import { withDefaults } from "../utils/request-defaults.js";
|
|
5
|
+
import { toFronticFetchError } from "../utils/describe-error.js";
|
|
6
|
+
function resolveOverride(override, fallback) {
|
|
7
|
+
return override === false ? void 0 : override ?? fallback();
|
|
8
|
+
}
|
|
9
|
+
export function createFronticServerClient(event, options) {
|
|
10
|
+
const config = useRuntimeConfig(event);
|
|
11
|
+
const fronticConfig = config.public.frontic;
|
|
12
|
+
const contextDomain = resolveOverride(
|
|
13
|
+
options?.contextDomain,
|
|
14
|
+
() => (
|
|
15
|
+
// `contextDomain: true` means "read the active i18n locale", and there is no
|
|
16
|
+
// i18n instance here. Resolving nothing beats guessing another region.
|
|
17
|
+
typeof fronticConfig?.contextDomain === "string" ? fronticConfig.contextDomain : void 0
|
|
18
|
+
)
|
|
19
|
+
);
|
|
20
|
+
const contextKey = resolveOverride(options?.contextKey, () => {
|
|
21
|
+
if (fronticConfig?.disableContext) return void 0;
|
|
22
|
+
return getCookie(event, fronticConfig?.contextCookieName ?? "fs-context");
|
|
23
|
+
});
|
|
24
|
+
const requestUrl = resolveOverride(options?.requestUrl, () => getRequestURL(event).href);
|
|
25
|
+
const baseClient = createClient({});
|
|
26
|
+
function reporting(operation, identity, reqOptions, run) {
|
|
27
|
+
return run().catch((error) => {
|
|
28
|
+
const reported = reqOptions?.contextKey === false ? void 0 : reqOptions?.contextKey ?? contextKey;
|
|
29
|
+
const payload = toFronticFetchError(operation, identity, { contextDomain, contextKey: reported, requestUrl }, error);
|
|
30
|
+
const hooks = useNitroApp().hooks;
|
|
31
|
+
void Promise.resolve(hooks.callHook("frontic:fetch:error", payload)).catch(() => {
|
|
32
|
+
});
|
|
33
|
+
throw error;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const defaults = {
|
|
37
|
+
...contextDomain && { contextDomain },
|
|
38
|
+
...contextKey && { contextKey },
|
|
39
|
+
...requestUrl && { requestUrl }
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
block: (name, key, reqOptions) => reporting("block", { name: String(name) }, reqOptions, () => baseClient.block(name, key, withDefaults(defaults, reqOptions))),
|
|
43
|
+
listing: (name, params, reqOptions) => reporting("listing", { name: String(name) }, reqOptions, () => baseClient.listing(name, params, withDefaults(defaults, reqOptions))),
|
|
44
|
+
tree: (name, reqOptions) => reporting("tree", { name: String(name) }, reqOptions, () => baseClient.tree(name, withDefaults(defaults, reqOptions))),
|
|
45
|
+
// A page is addressed by a slug that already carries its domain
|
|
46
|
+
page: (slug, reqOptions) => reporting("page", { slug }, reqOptions, () => baseClient.page(slug, withDefaults({ ...contextKey && { contextKey }, ...requestUrl && { requestUrl } }, reqOptions))),
|
|
47
|
+
context: (token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.context(token, withDefaults({}, reqOptions))),
|
|
48
|
+
contextList: (token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.contextList(token, withDefaults({ ...contextDomain && { contextDomain } }, reqOptions))),
|
|
49
|
+
contextUpdate: (context, token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.contextUpdate(context, token, withDefaults({}, reqOptions))),
|
|
50
|
+
// The Frontic domain is an explicit parameter, so no contextDomain injection
|
|
51
|
+
sitemap: (domain, index, reqOptions) => reporting("sitemap", { domain }, reqOptions, () => baseClient.sitemap(domain, index, withDefaults({ ...requestUrl && { requestUrl } }, reqOptions)))
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -11,7 +11,7 @@ export type { FronticRequestOptions, FronticQueryOptions, InclusionMode, FilterF
|
|
|
11
11
|
export type { RangeFilterValue } from '../utils/filter-helpers.js';
|
|
12
12
|
export type { FronticAnalyticsItem, FronticListingTrigger, FronticListingResolved, FronticSearchCommitted, FronticPageResolved } from '../composables/analytics.js';
|
|
13
13
|
export type { FronticFetchError, FronticFetchOperation } from './errors.js';
|
|
14
|
-
export type { SearchState, UseFronticSearchOptions, UseSearchReturn } from './search.js';
|
|
14
|
+
export type { SearchState, UseFronticSearchOptions, UseSearchReturn, SearchUrlSlice, SearchUrlQuerySyncOptions } from './search.js';
|
|
15
15
|
export type { UseFronticClientOptions } from '../composables/useFronticClient.js';
|
|
16
16
|
export type { UseFronticBlockOptions } from '../composables/useFronticBlock.js';
|
|
17
17
|
export type { UseFronticPageOptions } from '../composables/useFronticPage.js';
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* factory. All schema-derived typing flows from the registry (./registry).
|
|
6
6
|
*/
|
|
7
7
|
import type { MaybeRef, MaybeRefOrGetter } from 'vue';
|
|
8
|
-
import type { ListingName, ListingParamsOf, ListingFiltersOf, ListingSortsOf, RequestOptions, FilterGroup, AggregationGroup, DefaultFilterOption, DefaultAggregationStats, FilterData, AggregationData, Pagination } from './registry.js';
|
|
8
|
+
import type { ListingName, ListingParamsOf, ListingFiltersOf, ListingSortsOf, ResponseOf, RequestOptions, FilterGroup, AggregationGroup, DefaultFilterOption, DefaultAggregationStats, FilterData, AggregationData, Pagination } from './registry.js';
|
|
9
9
|
import type { Query } from './query.js';
|
|
10
10
|
export type { Blocks, Listings, ListingParameters, ListingQueryFilters, ListingQuerySorts, Trees, Responses, ResponseOf, ListingParamsOf, ListingFiltersOf, ListingSortsOf, RequestOptions, TreeQuery, Pagination, FilterData, AggregationData, FilterGroup, AggregationGroup, } from './registry.js';
|
|
11
11
|
export type { Query, Sort, SortField as QuerySortField, EqualsFilter, LogicalFilter, Filter, RangeFilter, ContainsFilter } from './query.js';
|
|
@@ -50,6 +50,42 @@ export interface FronticQueryOptions {
|
|
|
50
50
|
*/
|
|
51
51
|
keepPreviousData?: boolean;
|
|
52
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Seeding a query with data that already arrived by another route — typically
|
|
55
|
+
* a listing embedded in the page or block payload that carries it, so the
|
|
56
|
+
* route renders without a second round trip.
|
|
57
|
+
*
|
|
58
|
+
* Separate from {@link FronticQueryOptions} because the payload type differs
|
|
59
|
+
* per composable, and a shared non-generic option would type it as `unknown`.
|
|
60
|
+
*/
|
|
61
|
+
export interface FronticInitialDataOptions<TData> {
|
|
62
|
+
/**
|
|
63
|
+
* Data to seed the cache with, as a getter. The query reports `success`
|
|
64
|
+
* immediately and does not fetch while the seed is within `staleTime`.
|
|
65
|
+
*
|
|
66
|
+
* Only the query this composable starts on is seeded: the payload describes
|
|
67
|
+
* one set of filters, sort and page, so a later interaction fetches for real
|
|
68
|
+
* rather than being handed data that answers a different question.
|
|
69
|
+
*
|
|
70
|
+
* Use it only for data that *is* the response. To merely avoid a skeleton on
|
|
71
|
+
* data that may be wrong, let `keepPreviousData` do it — a seed reports
|
|
72
|
+
* `success`, so nothing downstream can tell it apart from a fetch.
|
|
73
|
+
*
|
|
74
|
+
* Returning `undefined` seeds nothing and fetches as usual, so a getter may
|
|
75
|
+
* read a payload that has not arrived yet without a guard of its own.
|
|
76
|
+
*/
|
|
77
|
+
initialData?: () => TData | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* When the seeded data was produced, as an epoch millisecond timestamp.
|
|
80
|
+
* Drives its staleness: with a `staleTime` of 5 minutes, a seed stamped 10
|
|
81
|
+
* minutes ago refetches in the background on mount instead of being trusted.
|
|
82
|
+
*
|
|
83
|
+
* Worth setting whenever the payload can outlive the request that renders it
|
|
84
|
+
* — an ISR or CDN-cached page hands the same block to every visitor.
|
|
85
|
+
* @default Date.now() (the seed counts as fresh)
|
|
86
|
+
*/
|
|
87
|
+
initialDataUpdatedAt?: number | (() => number);
|
|
88
|
+
}
|
|
53
89
|
/**
|
|
54
90
|
* Resolves to the typed `Query<filter, sort>` shape for a given listing name.
|
|
55
91
|
* Falls back to an untyped query when the listing isn't in the generated maps.
|
|
@@ -211,7 +247,7 @@ export interface ListingEnvelope {
|
|
|
211
247
|
* Configuration for listing queries
|
|
212
248
|
* @template TListing - The listing name, constrained to the registry's listing names
|
|
213
249
|
*/
|
|
214
|
-
export interface FetchListingConfig<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions {
|
|
250
|
+
export interface FetchListingConfig<TListing extends ListingName = ListingName> extends FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions<ResponseOf<TListing>> {
|
|
215
251
|
/**
|
|
216
252
|
* The listing name to fetch (e.g., 'ProductSearch', 'CategoryProducts')
|
|
217
253
|
*/
|
|
@@ -157,11 +157,25 @@ export interface FronticOptions {
|
|
|
157
157
|
};
|
|
158
158
|
/**
|
|
159
159
|
* API secret for authenticating Fetch API requests
|
|
160
|
-
* Required for protected environments (e.g., development/staging)
|
|
161
|
-
* Stored in private runtime config (server-only, never exposed to browser)
|
|
162
160
|
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
161
|
+
* Only for a project whose Fetch API is protected. A project is readable by
|
|
162
|
+
* anyone holding its URL until a secret is created for it, and creating one
|
|
163
|
+
* is itself the switch — there is no separate toggle. That is a decision
|
|
164
|
+
* about the data (a B2B or partner catalogue, pricing worth scraping, a
|
|
165
|
+
* protect-by-default rule), not about an environment: the same project is
|
|
166
|
+
* protected or not wherever it is served from. Like any other project
|
|
167
|
+
* configuration it moves through Release Control, develop to preview to
|
|
168
|
+
* public, so a storefront against public keeps working until the release
|
|
169
|
+
* carrying the secret lands.
|
|
170
|
+
*
|
|
171
|
+
* Stored in private runtime config (server-only, never exposed to browser),
|
|
172
|
+
* and injected server-side on both paths: by the proxy for browser requests,
|
|
173
|
+
* by a Nitro plugin for SSR and server routes. Nothing enforces that —
|
|
174
|
+
* handing the value to the browser works and simply makes the protection
|
|
175
|
+
* meaningless.
|
|
176
|
+
*
|
|
177
|
+
* On a protected project a missing or wrong secret is 401 on every call at
|
|
178
|
+
* once, never partial.
|
|
165
179
|
*
|
|
166
180
|
* @example process.env.FRONTIC_FETCH_SECRET
|
|
167
181
|
*/
|
|
@@ -98,8 +98,27 @@ export type ListingSortsOf<TName> = TName extends keyof FronticListingQuerySorts
|
|
|
98
98
|
* `fs-secret` header; older clients ignore it.
|
|
99
99
|
*/
|
|
100
100
|
export interface RequestOptions {
|
|
101
|
-
|
|
102
|
-
|
|
101
|
+
/**
|
|
102
|
+
* URL recorded with the request for attribution and tracking. The Nuxt
|
|
103
|
+
* wrapper fills it in from the current URL unless told otherwise.
|
|
104
|
+
*
|
|
105
|
+
* `false` is an instruction to that wrapper, not a value: it opts the call
|
|
106
|
+
* out, and `useFronticClient` drops the key before the generated client sees
|
|
107
|
+
* it. Reach for it when the response goes behind a shared cache, where a
|
|
108
|
+
* per-visitor URL would vary a request that is otherwise identical.
|
|
109
|
+
*/
|
|
110
|
+
requestUrl?: string | false;
|
|
111
|
+
/**
|
|
112
|
+
* Context token identifying the visitor's region and locale selection, sent
|
|
113
|
+
* as `fs-context`. The Nuxt wrapper fills it in from the context
|
|
114
|
+
* `useFronticContext` manages unless told otherwise.
|
|
115
|
+
*
|
|
116
|
+
* `false` is an instruction to that wrapper, not a value: it opts the call
|
|
117
|
+
* out, so the request resolves through `fs-domain` alone. Reach for it when
|
|
118
|
+
* the response goes behind a shared cache, where one visitor's context must
|
|
119
|
+
* not decide what the next one sees.
|
|
120
|
+
*/
|
|
121
|
+
contextKey?: string | false;
|
|
103
122
|
contextDomain?: string;
|
|
104
123
|
proxyUrl?: string;
|
|
105
124
|
secret?: string;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import type { Ref, ShallowRef, MaybeRef } from 'vue';
|
|
8
8
|
import type { UseQueryReturn } from '@pinia/colada';
|
|
9
9
|
import type { ListingName, ListingFiltersOf, ListingSortsOf, ResponseOf } from './registry.js';
|
|
10
|
-
import type { FronticRequestOptions, FronticQueryOptions, ListingFieldConfig, SortStringOf, UiFilter, UiSort } from './listing.js';
|
|
10
|
+
import type { FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions, ListingFieldConfig, SortStringOf, UiFilter, UiSort } from './listing.js';
|
|
11
11
|
import type { RangeFilterValue } from '../utils/filter-helpers.js';
|
|
12
12
|
export type { FronticRequestOptions, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationStats, InclusionMode, SortString, SortStringOf } from './listing.js';
|
|
13
13
|
export type { Listings, ListingQueryFilters, ListingQuerySorts, Responses, ResponseOf } from './registry.js';
|
|
@@ -70,7 +70,7 @@ export interface SearchState<TFilters = Record<string, unknown>, TSorts = Record
|
|
|
70
70
|
* @template TFilters - Filter fields for this listing (defaults to the registry's filter map)
|
|
71
71
|
* @template TSorts - Sort fields for this listing (defaults to the registry's sort map)
|
|
72
72
|
*/
|
|
73
|
-
export interface UseFronticSearchOptions<TSearch extends ListingName = ListingName, TFilters = ListingFiltersOf<TSearch>, TSorts = ListingSortsOf<TSearch>> extends FronticRequestOptions, FronticQueryOptions {
|
|
73
|
+
export interface UseFronticSearchOptions<TSearch extends ListingName = ListingName, TFilters = ListingFiltersOf<TSearch>, TSorts = ListingSortsOf<TSearch>> extends FronticRequestOptions, FronticQueryOptions, FronticInitialDataOptions<ResponseOf<TSearch>> {
|
|
74
74
|
/**
|
|
75
75
|
* Cache key for the query (defaults to name)
|
|
76
76
|
*/
|
|
@@ -218,6 +218,67 @@ export interface UseFronticSearchOptions<TSearch extends ListingName = ListingNa
|
|
|
218
218
|
* @default 1
|
|
219
219
|
*/
|
|
220
220
|
initialPage?: number;
|
|
221
|
+
/**
|
|
222
|
+
* Opt-in two-way sync of search state with the URL query string.
|
|
223
|
+
*
|
|
224
|
+
* When enabled, the current search term, sorting, filters and page are reflected in the URL
|
|
225
|
+
* (shareable, reload-safe, back/forward-aware) and restored from it on load — server-side, so
|
|
226
|
+
* the first render already reflects the URL. Off by default: no router APIs are touched unless set.
|
|
227
|
+
*
|
|
228
|
+
* `true` uses all defaults. Pass an object to namespace or rename params, choose which slices to
|
|
229
|
+
* sync, or push history entries instead of replacing.
|
|
230
|
+
*
|
|
231
|
+
* @default false
|
|
232
|
+
* @example
|
|
233
|
+
* // Everything, default param names: ?q=…&sort=…&<field>=…&page=…
|
|
234
|
+
* urlQuerySync: true
|
|
235
|
+
*
|
|
236
|
+
* // Namespaced + renamed params: ?p_query=…&p_color=Red&p_price_min=20
|
|
237
|
+
* urlQuerySync: {
|
|
238
|
+
* prefix: 'p_',
|
|
239
|
+
* params: { search: 'query', 'properties.color': 'color', 'price.amount': 'price' },
|
|
240
|
+
* }
|
|
241
|
+
*/
|
|
242
|
+
urlQuerySync?: boolean | SearchUrlQuerySyncOptions<TFilters>;
|
|
243
|
+
}
|
|
244
|
+
/** State slices that {@link SearchUrlQuerySyncOptions} can sync to the URL. */
|
|
245
|
+
export type SearchUrlSlice = 'search' | 'sort' | 'filter' | 'page';
|
|
246
|
+
/**
|
|
247
|
+
* Configuration for URL query-param sync on {@link UseFronticSearchOptions.urlQuerySync}.
|
|
248
|
+
*
|
|
249
|
+
* @template TFilters - Filter fields for this listing (provides autocomplete for `params` keys)
|
|
250
|
+
*/
|
|
251
|
+
export interface SearchUrlQuerySyncOptions<TFilters = Record<string, unknown>> {
|
|
252
|
+
/**
|
|
253
|
+
* Prefix applied to every param this instance owns. Required to run two synced searches on one
|
|
254
|
+
* page without their params colliding (e.g. `prefix: 'a_'` and `prefix: 'b_'`).
|
|
255
|
+
* @default ''
|
|
256
|
+
*/
|
|
257
|
+
prefix?: string;
|
|
258
|
+
/**
|
|
259
|
+
* Which state slices to sync. Also gated by the matching `disable*` option.
|
|
260
|
+
* @default ['search', 'sort', 'filter', 'page']
|
|
261
|
+
*/
|
|
262
|
+
include?: SearchUrlSlice[];
|
|
263
|
+
/**
|
|
264
|
+
* Rename URL params. Keys are either a slice (`'search'` | `'sort'` | `'page'`) or a filter field
|
|
265
|
+
* name; values are the param name to use. Unlisted entries fall back to their default
|
|
266
|
+
* (`'search'` → `'q'`, `'sort'` → `'sort'`, `'page'` → `'page'`, filter fields → the raw field name;
|
|
267
|
+
* range filters get `_min`/`_max` suffixes on their param).
|
|
268
|
+
*
|
|
269
|
+
* Note: this is unrelated to the composable's second `params` argument (the backend listing
|
|
270
|
+
* parameters). The three slice names are reserved, so a filter field literally named
|
|
271
|
+
* `search`/`sort`/`page` cannot be renamed here.
|
|
272
|
+
*
|
|
273
|
+
* @example { search: 'query', 'properties.color': 'color', 'price.amount': 'price' }
|
|
274
|
+
*/
|
|
275
|
+
params?: Partial<Record<'search' | 'sort' | 'page' | (keyof TFilters & string), string>>;
|
|
276
|
+
/**
|
|
277
|
+
* History strategy for URL writes. `'replace'` avoids a history entry per interaction (so Back
|
|
278
|
+
* leaves the page rather than stepping through filter states); `'push'` makes Back an undo.
|
|
279
|
+
* @default 'replace'
|
|
280
|
+
*/
|
|
281
|
+
history?: 'replace' | 'push';
|
|
221
282
|
}
|
|
222
283
|
/**
|
|
223
284
|
* Return type for the search composable — the declared contract of
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* `cause` is non-enumerable, so it is absent from `console.error(err)` and from
|
|
7
7
|
* anything that serialises the error, and has to be walked explicitly.
|
|
8
8
|
*/
|
|
9
|
+
import { type FronticFetchError, type FronticFetchOperation } from '../types/errors.js';
|
|
9
10
|
/**
|
|
10
11
|
* Flatten an error and its `cause` chain, outermost first.
|
|
11
12
|
*
|
|
@@ -36,3 +37,21 @@ export interface FronticFetchErrorDetail {
|
|
|
36
37
|
}
|
|
37
38
|
/** Describe a failure once, so every call site reports it the same way. */
|
|
38
39
|
export declare function toFetchErrorDetail(error: unknown): FronticFetchErrorDetail;
|
|
40
|
+
/**
|
|
41
|
+
* Build the `frontic:fetch:error` payload.
|
|
42
|
+
*
|
|
43
|
+
* Shared by both clients so a consumer's handler reads the same shape whichever
|
|
44
|
+
* runtime failed — the app composable announces it on the Nuxt app, the server
|
|
45
|
+
* client on the Nitro app, and neither should invent its own fields.
|
|
46
|
+
*/
|
|
47
|
+
export declare function toFronticFetchError(operation: FronticFetchOperation, identity: {
|
|
48
|
+
name?: string;
|
|
49
|
+
slug?: string;
|
|
50
|
+
domain?: string;
|
|
51
|
+
}, request: {
|
|
52
|
+
contextDomain?: string;
|
|
53
|
+
contextKey?: string;
|
|
54
|
+
requestUrl?: string;
|
|
55
|
+
proxyUrl?: string;
|
|
56
|
+
targetUrl?: string;
|
|
57
|
+
}, error: unknown): FronticFetchError;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FRONTIC_FETCH_ERROR_VERSION } from "../types/errors.js";
|
|
1
2
|
const MAX_CAUSE_DEPTH = 5;
|
|
2
3
|
export function describeErrorChain(error) {
|
|
3
4
|
const chain = [];
|
|
@@ -36,3 +37,18 @@ export function toFetchErrorDetail(error) {
|
|
|
36
37
|
...statusOf(error) !== void 0 && { status: statusOf(error) }
|
|
37
38
|
};
|
|
38
39
|
}
|
|
40
|
+
export function toFronticFetchError(operation, identity, request, error) {
|
|
41
|
+
return {
|
|
42
|
+
operation,
|
|
43
|
+
...identity.name !== void 0 && { name: identity.name },
|
|
44
|
+
...identity.slug !== void 0 && { slug: identity.slug },
|
|
45
|
+
...identity.domain !== void 0 && { domain: identity.domain },
|
|
46
|
+
...request.contextDomain && { contextDomain: request.contextDomain },
|
|
47
|
+
...request.contextKey && { contextKey: request.contextKey },
|
|
48
|
+
...request.requestUrl && { requestUrl: request.requestUrl },
|
|
49
|
+
...request.proxyUrl && { proxyUrl: request.proxyUrl },
|
|
50
|
+
...request.targetUrl && { targetUrl: request.targetUrl },
|
|
51
|
+
...toFetchErrorDetail(error),
|
|
52
|
+
version: FRONTIC_FETCH_ERROR_VERSION
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Query Key Utilities
|
|
3
|
-
*
|
|
4
|
-
* Shared building blocks for the per-entity query key factories.
|
|
5
|
-
*/
|
|
1
|
+
import type { MaybeRef } from 'vue';
|
|
6
2
|
/** Default stale time for all Frontic queries (5 minutes) */
|
|
7
3
|
export declare const DEFAULT_STALE_TIME: number;
|
|
8
4
|
/**
|
|
@@ -25,3 +21,12 @@ export declare function requestContextSlot(contextKey?: string, contextDomain?:
|
|
|
25
21
|
* not matter — the cache normalises objects order-insensitively.
|
|
26
22
|
*/
|
|
27
23
|
export declare function toKeyPart(value: Record<string, unknown>): Record<string, unknown>;
|
|
24
|
+
/**
|
|
25
|
+
* The token a query factory should use: its configured value, with an explicit
|
|
26
|
+
* opt-out normalised away. Factories reach for this rather than `toValue` so the
|
|
27
|
+
* cache key and the request are derived from one value — a key built from a
|
|
28
|
+
* different value than the request is what FSC-4523 was.
|
|
29
|
+
*/
|
|
30
|
+
export declare function contextKeyOf(config: {
|
|
31
|
+
contextKey?: MaybeRef<string | false | undefined>;
|
|
32
|
+
}): string | undefined;
|