@frontic/nuxt 1.0.0 → 1.1.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 +35 -2
- package/dist/module.json +1 -1
- package/dist/module.mjs +70 -11
- package/dist/runtime/composables/useFronticBlock.js +6 -2
- package/dist/runtime/composables/useFronticClient.d.ts +3 -25
- package/dist/runtime/composables/useFronticClient.js +59 -48
- package/dist/runtime/composables/useFronticListing.js +6 -2
- package/dist/runtime/composables/useFronticPage.js +6 -13
- package/dist/runtime/composables/useFronticSearch.js +19 -14
- package/dist/runtime/composables/useFronticTree.js +6 -3
- package/dist/runtime/server/api/frontic/[...path].js +48 -10
- package/dist/runtime/server/middleware/sitemap.d.ts +2 -0
- package/dist/runtime/server/middleware/sitemap.js +55 -0
- package/dist/runtime/types/client.d.ts +2 -0
- package/dist/runtime/types/errors.d.ts +47 -0
- package/dist/runtime/types/errors.js +1 -0
- package/dist/runtime/types/index.d.ts +1 -0
- package/dist/runtime/types/options.d.ts +30 -0
- package/dist/runtime/types/search.d.ts +34 -2
- package/dist/runtime/utils/describe-error.d.ts +38 -0
- package/dist/runtime/utils/describe-error.js +38 -0
- package/dist/runtime/utils/filter-helpers.d.ts +13 -0
- package/dist/runtime/utils/filter-helpers.js +14 -0
- package/dist/runtime/utils/resolve-context-domain.d.ts +14 -0
- package/dist/runtime/utils/resolve-context-domain.js +9 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ npx nuxi@latest module add @frontic/nuxt
|
|
|
26
26
|
export default defineNuxtConfig({
|
|
27
27
|
modules: ['@frontic/nuxt'],
|
|
28
28
|
frontic: {
|
|
29
|
-
contextDomain: '
|
|
29
|
+
contextDomain: 'demo-shop.com',
|
|
30
30
|
},
|
|
31
31
|
})
|
|
32
32
|
```
|
|
@@ -108,7 +108,7 @@ const { contexts, current, update } = useFronticContext()
|
|
|
108
108
|
export default defineNuxtConfig({
|
|
109
109
|
frontic: {
|
|
110
110
|
// Page routing
|
|
111
|
-
contextDomain: '
|
|
111
|
+
contextDomain: 'demo-shop.com',
|
|
112
112
|
redirectOn301: true,
|
|
113
113
|
throwOn404: true,
|
|
114
114
|
|
|
@@ -116,6 +116,9 @@ export default defineNuxtConfig({
|
|
|
116
116
|
proxy: true, // or '/api/custom-path'
|
|
117
117
|
fetchApiSecret: process.env.FRONTIC_FETCH_SECRET,
|
|
118
118
|
|
|
119
|
+
// Sitemap
|
|
120
|
+
sitemap: true,
|
|
121
|
+
|
|
119
122
|
// Context cookies
|
|
120
123
|
contextCookieName: 'fs-context',
|
|
121
124
|
contextCookieMaxAge: 31536000,
|
|
@@ -130,6 +133,36 @@ export default defineNuxtConfig({
|
|
|
130
133
|
})
|
|
131
134
|
```
|
|
132
135
|
|
|
136
|
+
### Sitemap
|
|
137
|
+
|
|
138
|
+
With `sitemap: true`, requests to `/sitemap.xml` (and `/sitemapN.xml` for split sitemaps) on any locale prefix serve the Frontic sitemap for the matching domain — generated from the Pages marked "Visible in Sitemap". Responses carry the upstream `ETag` and are cached with stale-while-revalidate. When your config declares domains (`sitemap: { domains: [...] }`, a `contextDomain` string, or `contextDomain: true` with i18n locales carrying `contextDomain` properties), only those domains are served — other hosts get a 404. With no declared domains the route serves any well-formed forwarded host and the module warns at build time. When `@nuxtjs/robots` is installed, the sitemap is added to `robots.txt` automatically. Not compatible with `@nuxtjs/sitemap` yet — with both installed the option is ignored with a warning.
|
|
139
|
+
|
|
140
|
+
### Multi-locale domains
|
|
141
|
+
|
|
142
|
+
Frontic resolves scope, region and locale from the domain each request carries. Set `contextDomain: true` to take it from the locale `@nuxtjs/i18n` currently has active, instead of hardcoding one:
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
export default defineNuxtConfig({
|
|
146
|
+
modules: ['@frontic/nuxt', '@nuxtjs/i18n'],
|
|
147
|
+
|
|
148
|
+
frontic: {
|
|
149
|
+
contextDomain: true,
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
i18n: {
|
|
153
|
+
defaultLocale: 'en',
|
|
154
|
+
locales: [
|
|
155
|
+
{ code: 'en', contextDomain: 'demo-shop.com' },
|
|
156
|
+
{ code: 'de', contextDomain: 'demo-shop.com/de' },
|
|
157
|
+
],
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`contextDomain` on the locale object is a property you add — the module reads it through i18n's `localeProperties`, and each value must match a domain configured in your Frontic project. The resolved domain is part of every cache key, so locales never share a cached response.
|
|
163
|
+
|
|
164
|
+
Per call, any composable accepts `contextDomain` to override it, and `useFronticClient({ contextDomain: false })` sends none at all.
|
|
165
|
+
|
|
133
166
|
## Analytics
|
|
134
167
|
|
|
135
168
|
Listing, search and page events are announced as typed Nuxt hooks, so any vendor can be wired up in one plugin:
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { readFileSync, existsSync, readdirSync } from 'node:fs';
|
|
2
|
-
import { createRequire } from 'node:module';
|
|
3
2
|
import { dirname, join } from 'node:path';
|
|
4
3
|
import { fileURLToPath } from 'node:url';
|
|
5
4
|
import { defineNuxtModule, createResolver, addServerHandler, addServerPlugin, hasNuxtModule, installModule, addImports, addTypeTemplate, addComponentsDir, addComponentExports } from '@nuxt/kit';
|
|
@@ -23,6 +22,18 @@ function readGeneratorSchemaVersion(clientDir) {
|
|
|
23
22
|
return 1;
|
|
24
23
|
}
|
|
25
24
|
}
|
|
25
|
+
function readFetchApiBaseUrl(clientPath) {
|
|
26
|
+
try {
|
|
27
|
+
const source = readFileSync(clientPath, "utf-8");
|
|
28
|
+
return /const servers = \[\s*\{[^}]*url:\s*'([^']+)'/.exec(source)?.[1];
|
|
29
|
+
} catch {
|
|
30
|
+
return void 0;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function collectSitemapDomains(explicitDomains, contextDomain, i18nLocales) {
|
|
34
|
+
const domains = explicitDomains ?? (typeof contextDomain === "string" ? [contextDomain] : contextDomain === true && Array.isArray(i18nLocales) ? i18nLocales.map((locale) => locale?.contextDomain).filter((domain) => typeof domain === "string") : []);
|
|
35
|
+
return domains.map((domain) => domain.toLowerCase().replace(/\/+$/, ""));
|
|
36
|
+
}
|
|
26
37
|
const ALL_COMPOSABLES = ["block", "listing", "search", "tree", "page", "context", "client"];
|
|
27
38
|
function isComposableEnabled(config, name) {
|
|
28
39
|
if (config === true) return true;
|
|
@@ -42,7 +53,8 @@ const module$1 = defineNuxtModule({
|
|
|
42
53
|
// 1 year
|
|
43
54
|
disableContext: false,
|
|
44
55
|
redirectOn301: true,
|
|
45
|
-
throwOn404: true
|
|
56
|
+
throwOn404: true,
|
|
57
|
+
sitemap: false
|
|
46
58
|
},
|
|
47
59
|
meta: {
|
|
48
60
|
name: "frontic",
|
|
@@ -64,6 +76,7 @@ const module$1 = defineNuxtModule({
|
|
|
64
76
|
disableContext = false,
|
|
65
77
|
redirectOn301 = true,
|
|
66
78
|
throwOn404 = true,
|
|
79
|
+
sitemap = false,
|
|
67
80
|
fetchApiSecret
|
|
68
81
|
} = options;
|
|
69
82
|
const COMPONENT_DIR_PATH = componentDir;
|
|
@@ -81,6 +94,7 @@ const module$1 = defineNuxtModule({
|
|
|
81
94
|
);
|
|
82
95
|
}
|
|
83
96
|
const proxyPath = typeof proxyConfig === "string" ? proxyConfig : proxyConfig !== false ? "/api/frontic" : void 0;
|
|
97
|
+
const proxyTimeout = options.proxyTimeout ?? 1e4;
|
|
84
98
|
if (proxyPath && hasFronticClient) {
|
|
85
99
|
addServerHandler({
|
|
86
100
|
route: `${proxyPath}/**`,
|
|
@@ -90,6 +104,34 @@ const module$1 = defineNuxtModule({
|
|
|
90
104
|
if (fetchApiSecret && hasFronticClient) {
|
|
91
105
|
addServerPlugin(resolveModule("./runtime/server/plugins/fetch-secret"));
|
|
92
106
|
}
|
|
107
|
+
let sitemapBaseUrl;
|
|
108
|
+
let sitemapDomains = [];
|
|
109
|
+
if (sitemap && hasFronticClient) {
|
|
110
|
+
if (hasNuxtModule("@nuxtjs/sitemap", nuxt)) {
|
|
111
|
+
console.warn("\n[@frontic/nuxt] sitemap: true is ignored while @nuxtjs/sitemap is installed.\nBoth modules would claim /sitemap.xml. Disable one of them.\n");
|
|
112
|
+
} else {
|
|
113
|
+
sitemapBaseUrl = readFetchApiBaseUrl(fronticClientPath);
|
|
114
|
+
if (!sitemapBaseUrl) {
|
|
115
|
+
console.warn("\n[@frontic/nuxt] sitemap: true but no Fetch API URL found in the generated client.\nRegenerate with the current CLI: npx @frontic/cli generate\n");
|
|
116
|
+
} else {
|
|
117
|
+
addServerHandler({
|
|
118
|
+
middleware: true,
|
|
119
|
+
handler: resolveModule("./runtime/server/middleware/sitemap")
|
|
120
|
+
});
|
|
121
|
+
sitemapDomains = collectSitemapDomains(typeof sitemap === "object" ? sitemap.domains : void 0, contextDomain, nuxt.options.i18n?.locales);
|
|
122
|
+
if (sitemapDomains.length === 0) {
|
|
123
|
+
console.warn(
|
|
124
|
+
"\n[@frontic/nuxt] sitemap is enabled without a domain allowlist, so the route serves\nany well-formed forwarded host through this deployment's secret.\nDeclare your domains via sitemap: { domains: [...] } or contextDomain config.\n"
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
if (hasNuxtModule("@nuxtjs/robots", nuxt)) {
|
|
128
|
+
nuxt.hook("robots:config", (robotsConfig) => {
|
|
129
|
+
robotsConfig.sitemap.push("/sitemap.xml");
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
93
135
|
const blockEnabled = isComposableEnabled(composablesConfig, "block");
|
|
94
136
|
const listingEnabled = isComposableEnabled(composablesConfig, "listing");
|
|
95
137
|
const searchEnabled = isComposableEnabled(composablesConfig, "search");
|
|
@@ -118,21 +160,13 @@ frontic: { composables: false }
|
|
|
118
160
|
);
|
|
119
161
|
}
|
|
120
162
|
const clientDirPath = fronticClientDir;
|
|
121
|
-
const piniaEsmCandidate = anyComposableEnabled ? join(dirname(createRequire(import.meta.url).resolve("pinia/package.json")), "dist/pinia.mjs") : null;
|
|
122
|
-
const piniaEsmPath = piniaEsmCandidate && existsSync(piniaEsmCandidate) ? piniaEsmCandidate : null;
|
|
123
163
|
nuxt.options.vite ||= {};
|
|
124
164
|
nuxt.options.vite.resolve ||= {};
|
|
125
165
|
nuxt.options.vite.resolve.alias ||= {};
|
|
126
166
|
nuxt.options.vite.resolve.alias["@frontic/stack"] = clientDirPath;
|
|
127
|
-
if (piniaEsmPath) {
|
|
128
|
-
nuxt.options.vite.resolve.alias["pinia"] = piniaEsmPath;
|
|
129
|
-
}
|
|
130
167
|
nuxt.hook("nitro:config", (nitroConfig) => {
|
|
131
168
|
nitroConfig.alias ||= {};
|
|
132
169
|
nitroConfig.alias["@frontic/stack"] = clientDirPath;
|
|
133
|
-
if (piniaEsmPath) {
|
|
134
|
-
nitroConfig.alias["pinia"] = piniaEsmPath;
|
|
135
|
-
}
|
|
136
170
|
});
|
|
137
171
|
nuxt.hook("prepare:types", ({ tsConfig }) => {
|
|
138
172
|
tsConfig.compilerOptions ||= {};
|
|
@@ -254,6 +288,28 @@ declare module '#app' {
|
|
|
254
288
|
${listingHooks}${pageHooks} }
|
|
255
289
|
}
|
|
256
290
|
|
|
291
|
+
export {}
|
|
292
|
+
`
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
if (anyComposableEnabled || proxyPath && hasFronticClient) {
|
|
296
|
+
const errorsModule = resolveModule("./runtime/types/errors");
|
|
297
|
+
addTypeTemplate({
|
|
298
|
+
filename: "types/frontic-fetch-error.d.ts",
|
|
299
|
+
getContents: () => `import type { FronticFetchError } from '${errorsModule}'
|
|
300
|
+
|
|
301
|
+
declare module '#app' {
|
|
302
|
+
interface RuntimeNuxtHooks {
|
|
303
|
+
'frontic:fetch:error': (payload: FronticFetchError) => void | Promise<void>
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
declare module 'nitropack/types' {
|
|
308
|
+
interface NitroRuntimeHooks {
|
|
309
|
+
'frontic:fetch:error': (payload: FronticFetchError) => void | Promise<void>
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
257
313
|
export {}
|
|
258
314
|
`
|
|
259
315
|
});
|
|
@@ -278,7 +334,10 @@ export {}
|
|
|
278
334
|
}
|
|
279
335
|
};
|
|
280
336
|
nuxt.options.runtimeConfig.frontic = {
|
|
281
|
-
fetchApiSecret: fetchApiSecret ?? ""
|
|
337
|
+
fetchApiSecret: fetchApiSecret ?? "",
|
|
338
|
+
sitemapBaseUrl: sitemapBaseUrl ?? "",
|
|
339
|
+
sitemapDomains,
|
|
340
|
+
proxyTimeout
|
|
282
341
|
};
|
|
283
342
|
if (isFronticUiInitialized(ROOT_DIR_PATH)) {
|
|
284
343
|
const componentsPath = await resolvePath(COMPONENT_DIR_PATH);
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { useQuery } from "@pinia/colada";
|
|
2
|
+
import { computed, toValue } from "vue";
|
|
3
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
2
4
|
import { fetchBlockQuery } from "./blocks.js";
|
|
3
5
|
import { useFronticClient } from "./useFronticClient.js";
|
|
4
6
|
export function useFronticBlock(name, key, options) {
|
|
5
|
-
const _client = useFronticClient();
|
|
7
|
+
const _client = useFronticClient({ contextDomain: false });
|
|
8
|
+
const autoContextDomain = resolveContextDomain();
|
|
9
|
+
const resolvedContextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
6
10
|
const blockQuery = fetchBlockQuery({
|
|
7
11
|
name,
|
|
8
12
|
key,
|
|
9
13
|
contextKey: options?.contextKey,
|
|
10
|
-
contextDomain:
|
|
14
|
+
contextDomain: resolvedContextDomain,
|
|
11
15
|
requestUrl: options?.requestUrl,
|
|
12
16
|
staleTime: options?.staleTime,
|
|
13
17
|
gcTime: options?.gcTime,
|
|
@@ -10,10 +10,10 @@ export interface UseFronticClientOptions {
|
|
|
10
10
|
*/
|
|
11
11
|
proxy?: boolean | string;
|
|
12
12
|
/**
|
|
13
|
-
* Override contextDomain
|
|
14
|
-
* - `false`:
|
|
13
|
+
* Override contextDomain resolution
|
|
14
|
+
* - `false`: Send no domain
|
|
15
15
|
* - `string`: Use specific domain
|
|
16
|
-
* - `undefined`:
|
|
16
|
+
* - `undefined`: Resolve from module config, or the active i18n locale when it is `true`
|
|
17
17
|
*/
|
|
18
18
|
contextDomain?: false | string;
|
|
19
19
|
/**
|
|
@@ -34,26 +34,4 @@ export interface UseFronticClientOptions {
|
|
|
34
34
|
*/
|
|
35
35
|
secret?: string;
|
|
36
36
|
}
|
|
37
|
-
/**
|
|
38
|
-
* Creates an SSR-aware Frontic client with automatic proxy and context injection
|
|
39
|
-
*
|
|
40
|
-
* @param options - Optional configuration to override defaults
|
|
41
|
-
* @returns Type-safe Frontic client instance
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* ```ts
|
|
45
|
-
* // Default behavior (proxy on client, auto contextDomain)
|
|
46
|
-
* const client = useFronticClient()
|
|
47
|
-
* const product = await client.block('ProductCard', productId)
|
|
48
|
-
*
|
|
49
|
-
* // Force direct API (bypass proxy)
|
|
50
|
-
* const directClient = useFronticClient({ proxy: false })
|
|
51
|
-
*
|
|
52
|
-
* // Custom proxy path
|
|
53
|
-
* const customClient = useFronticClient({ proxy: '/api/custom-frontic' })
|
|
54
|
-
*
|
|
55
|
-
* // Disable contextDomain auto-injection
|
|
56
|
-
* const noContextClient = useFronticClient({ contextDomain: false })
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
37
|
export declare function useFronticClient(options?: UseFronticClientOptions): FronticClient;
|
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
import { useRuntimeConfig, useRequestURL } from "nuxt/app";
|
|
1
|
+
import { useRuntimeConfig, useRequestURL, useNuxtApp } from "nuxt/app";
|
|
2
2
|
import { createClient } from "@frontic/stack/generated-client";
|
|
3
|
-
import {
|
|
3
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
4
|
+
import { toFetchErrorDetail } from "../utils/describe-error.js";
|
|
5
|
+
import { FRONTIC_FETCH_ERROR_VERSION } from "../types/errors.js";
|
|
6
|
+
function withDefaults(defaults, reqOptions) {
|
|
7
|
+
if (!reqOptions) return defaults;
|
|
8
|
+
const provided = Object.fromEntries(Object.entries(reqOptions).filter(([, value]) => value !== void 0));
|
|
9
|
+
return { ...defaults, ...provided };
|
|
10
|
+
}
|
|
4
11
|
export function useFronticClient(options) {
|
|
5
12
|
const config = useRuntimeConfig();
|
|
6
13
|
const fronticConfig = config.public.frontic;
|
|
@@ -11,14 +18,6 @@ export function useFronticClient(options) {
|
|
|
11
18
|
if (typeof options?.proxy === "string") return options.proxy;
|
|
12
19
|
return import.meta.server ? void 0 : fronticConfig?.proxyPath;
|
|
13
20
|
};
|
|
14
|
-
const resolveContextDomain = () => {
|
|
15
|
-
if (options?.contextDomain === false) return void 0;
|
|
16
|
-
if (typeof options?.contextDomain === "string") return options.contextDomain;
|
|
17
|
-
const configDomain = fronticConfig?.contextDomain;
|
|
18
|
-
if (typeof configDomain === "string") return configDomain;
|
|
19
|
-
if (configDomain === true) return resolveI18nContextDomain();
|
|
20
|
-
return void 0;
|
|
21
|
-
};
|
|
22
21
|
const resolveRequestUrl = () => {
|
|
23
22
|
if (options?.requestUrl === false) return void 0;
|
|
24
23
|
if (typeof options?.requestUrl === "string") return options.requestUrl;
|
|
@@ -31,49 +30,61 @@ export function useFronticClient(options) {
|
|
|
31
30
|
}
|
|
32
31
|
return void 0;
|
|
33
32
|
};
|
|
33
|
+
const nuxtApp = useNuxtApp();
|
|
34
34
|
const proxyUrl = resolveProxyUrl();
|
|
35
|
-
const contextDomain = resolveContextDomain();
|
|
35
|
+
const contextDomain = resolveContextDomain(options?.contextDomain);
|
|
36
36
|
const requestUrlValue = resolveRequestUrl();
|
|
37
37
|
const secret = resolveSecret();
|
|
38
38
|
const baseClient = createClient({ proxyUrl });
|
|
39
|
+
function reporting(operation, identity, reqOptions, run) {
|
|
40
|
+
return run().catch((error) => {
|
|
41
|
+
const payload = {
|
|
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
|
+
...contextDomain && { contextDomain },
|
|
47
|
+
...reqOptions?.contextKey && { contextKey: reqOptions.contextKey },
|
|
48
|
+
...requestUrlValue && { requestUrl: requestUrlValue },
|
|
49
|
+
...proxyUrl && { proxyUrl },
|
|
50
|
+
...toFetchErrorDetail(error),
|
|
51
|
+
version: FRONTIC_FETCH_ERROR_VERSION
|
|
52
|
+
};
|
|
53
|
+
void Promise.resolve(nuxtApp.callHook("frontic:fetch:error", payload)).catch(() => {
|
|
54
|
+
});
|
|
55
|
+
throw error;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
39
58
|
const client = {
|
|
40
|
-
block: (name, key, reqOptions) =>
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
...reqOptions
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
...secret && { secret },
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
...secret && { secret },
|
|
57
|
-
|
|
58
|
-
}),
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
...contextDomain && { contextDomain },
|
|
70
|
-
...secret && { secret },
|
|
71
|
-
...reqOptions
|
|
72
|
-
}),
|
|
73
|
-
contextUpdate: (context, token, reqOptions) => baseClient.contextUpdate(context, token, {
|
|
74
|
-
...secret && { secret },
|
|
75
|
-
...reqOptions
|
|
76
|
-
})
|
|
59
|
+
block: (name, key, reqOptions) => reporting(
|
|
60
|
+
"block",
|
|
61
|
+
{ name: String(name) },
|
|
62
|
+
reqOptions,
|
|
63
|
+
() => baseClient.block(name, key, withDefaults({ ...contextDomain && { contextDomain }, ...requestUrlValue && { requestUrl: requestUrlValue }, ...secret && { secret } }, reqOptions))
|
|
64
|
+
),
|
|
65
|
+
listing: (name, params, reqOptions) => reporting(
|
|
66
|
+
"listing",
|
|
67
|
+
{ name: String(name) },
|
|
68
|
+
reqOptions,
|
|
69
|
+
() => baseClient.listing(name, params, withDefaults({ ...contextDomain && { contextDomain }, ...requestUrlValue && { requestUrl: requestUrlValue }, ...secret && { secret } }, reqOptions))
|
|
70
|
+
),
|
|
71
|
+
tree: (name, reqOptions) => reporting(
|
|
72
|
+
"tree",
|
|
73
|
+
{ name: String(name) },
|
|
74
|
+
reqOptions,
|
|
75
|
+
() => baseClient.tree(name, withDefaults({ ...contextDomain && { contextDomain }, ...requestUrlValue && { requestUrl: requestUrlValue }, ...secret && { secret } }, reqOptions))
|
|
76
|
+
),
|
|
77
|
+
page: (slug, reqOptions) => reporting("page", { slug }, reqOptions, () => baseClient.page(slug, withDefaults({ ...requestUrlValue && { requestUrl: requestUrlValue }, ...secret && { secret } }, reqOptions))),
|
|
78
|
+
context: (token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.context(token, withDefaults({ ...secret && { secret } }, reqOptions))),
|
|
79
|
+
contextList: (token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.contextList(token, withDefaults({ ...contextDomain && { contextDomain }, ...secret && { secret } }, reqOptions))),
|
|
80
|
+
contextUpdate: (context, token, reqOptions) => reporting("context", {}, reqOptions, () => baseClient.contextUpdate(context, token, withDefaults({ ...secret && { secret } }, reqOptions))),
|
|
81
|
+
// The Frontic domain is an explicit parameter, so no contextDomain injection
|
|
82
|
+
sitemap: (domain, index, reqOptions) => reporting(
|
|
83
|
+
"sitemap",
|
|
84
|
+
{ domain },
|
|
85
|
+
reqOptions,
|
|
86
|
+
() => baseClient.sitemap(domain, index, withDefaults({ ...requestUrlValue && { requestUrl: requestUrlValue }, ...secret && { secret } }, reqOptions))
|
|
87
|
+
)
|
|
77
88
|
};
|
|
78
89
|
return client;
|
|
79
90
|
}
|
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { useQuery } from "@pinia/colada";
|
|
2
|
+
import { computed, toValue } from "vue";
|
|
3
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
2
4
|
import { fetchListingQuery } from "./listings.js";
|
|
3
5
|
import { useFronticClient } from "./useFronticClient.js";
|
|
4
6
|
export function useFronticListing(name, ...args) {
|
|
5
7
|
const [rawParams, options] = args;
|
|
6
8
|
const params = rawParams ?? {};
|
|
7
|
-
const _client = useFronticClient();
|
|
9
|
+
const _client = useFronticClient({ contextDomain: false });
|
|
10
|
+
const autoContextDomain = resolveContextDomain();
|
|
11
|
+
const resolvedContextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
8
12
|
const listingQuery = fetchListingQuery({
|
|
9
13
|
name,
|
|
10
14
|
params,
|
|
11
15
|
query: options?.query,
|
|
12
16
|
contextKey: options?.contextKey,
|
|
13
|
-
contextDomain:
|
|
17
|
+
contextDomain: resolvedContextDomain,
|
|
14
18
|
requestUrl: options?.requestUrl,
|
|
15
19
|
staleTime: options?.staleTime,
|
|
16
20
|
gcTime: options?.gcTime,
|
|
@@ -4,32 +4,25 @@ import { useQuery } from "@pinia/colada";
|
|
|
4
4
|
import { fetchPageQuery } from "./pages.js";
|
|
5
5
|
import { useFronticClient } from "./useFronticClient.js";
|
|
6
6
|
import { emitOnce, bindRouteReset, FRONTIC_ANALYTICS_VERSION } from "./analytics.js";
|
|
7
|
-
import {
|
|
7
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
8
8
|
export function useFronticPage(slug, options) {
|
|
9
9
|
const nuxtApp = useNuxtApp();
|
|
10
10
|
bindRouteReset(nuxtApp);
|
|
11
11
|
const requestURL = useRequestURL();
|
|
12
12
|
const config = useRuntimeConfig();
|
|
13
13
|
const fronticConfig = config.public.frontic;
|
|
14
|
+
const autoContextDomain = resolveContextDomain();
|
|
15
|
+
const resolvedContextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
14
16
|
const pageSlug = computed(() => {
|
|
15
17
|
if (slug) return toValue(slug);
|
|
16
18
|
const pathname = requestURL.pathname.replace(/\/+$/, "");
|
|
17
|
-
|
|
18
|
-
const optionDomain = options?.contextDomain ? toValue(options.contextDomain) : void 0;
|
|
19
|
-
if (typeof optionDomain === "string") {
|
|
20
|
-
domain = optionDomain;
|
|
21
|
-
} else if (typeof fronticConfig?.contextDomain === "string") {
|
|
22
|
-
domain = fronticConfig.contextDomain;
|
|
23
|
-
} else if (fronticConfig?.contextDomain === true) {
|
|
24
|
-
domain = resolveI18nContextDomain();
|
|
25
|
-
}
|
|
26
|
-
return `${domain ?? requestURL.host}${pathname}`;
|
|
19
|
+
return `${resolvedContextDomain.value ?? requestURL.host}${pathname}`;
|
|
27
20
|
});
|
|
28
|
-
const _client = useFronticClient();
|
|
21
|
+
const _client = useFronticClient({ contextDomain: false });
|
|
29
22
|
const pageQuery = fetchPageQuery({
|
|
30
23
|
slug: pageSlug,
|
|
31
24
|
contextKey: options?.contextKey,
|
|
32
|
-
contextDomain:
|
|
25
|
+
contextDomain: resolvedContextDomain,
|
|
33
26
|
requestUrl: options?.requestUrl,
|
|
34
27
|
staleTime: options?.staleTime,
|
|
35
28
|
gcTime: options?.gcTime,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { useState, useNuxtApp } from "nuxt/app";
|
|
2
|
-
import { computed,
|
|
2
|
+
import { computed, ref, toValue, watch } from "vue";
|
|
3
3
|
import { useQuery, useInfiniteQuery, useQueryCache, setInfiniteQueryData } from "@pinia/colada";
|
|
4
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
4
5
|
import { useDebounceFn } from "@vueuse/core";
|
|
5
6
|
import {
|
|
6
7
|
makeLogicalFilter,
|
|
@@ -8,7 +9,8 @@ import {
|
|
|
8
9
|
removeFilter,
|
|
9
10
|
isRangeFilterValue,
|
|
10
11
|
manageRangeFilter,
|
|
11
|
-
removeRangeFilter
|
|
12
|
+
removeRangeFilter,
|
|
13
|
+
seedFilterLists
|
|
12
14
|
} from "../utils/filter-helpers.js";
|
|
13
15
|
import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
|
|
14
16
|
import { fetchListingQuery, LISTING_QUERY_KEYS } from "./listings.js";
|
|
@@ -18,13 +20,14 @@ export function useFronticSearch(name, ...args) {
|
|
|
18
20
|
const [rawParams, options] = args;
|
|
19
21
|
const params = rawParams ?? {};
|
|
20
22
|
const queryCache = useQueryCache();
|
|
21
|
-
const _client = useFronticClient();
|
|
23
|
+
const _client = useFronticClient({ contextDomain: false });
|
|
22
24
|
const listingName = name;
|
|
23
25
|
const nuxtApp = useNuxtApp();
|
|
24
26
|
bindRouteReset(nuxtApp);
|
|
25
27
|
const cacheKey = options?.cacheKey ?? String(name);
|
|
26
28
|
const contextKey = options?.contextKey;
|
|
27
|
-
const
|
|
29
|
+
const autoContextDomain = resolveContextDomain();
|
|
30
|
+
const contextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
28
31
|
const requestUrl = options?.requestUrl;
|
|
29
32
|
const searchTermThreshold = options?.searchTermThreshold ?? 2;
|
|
30
33
|
const searchDebounce = options?.searchDebounce ?? 200;
|
|
@@ -36,7 +39,6 @@ export function useFronticSearch(name, ...args) {
|
|
|
36
39
|
const disableSearch = options?.disableSearch ?? false;
|
|
37
40
|
const disableFilter = options?.disableFilter ?? false;
|
|
38
41
|
const disableSorting = options?.disableSorting ?? false;
|
|
39
|
-
const limit = options?.limit;
|
|
40
42
|
const staleTime = options?.staleTime ?? 1e3 * 60 * 5;
|
|
41
43
|
const infinite = options?.infinite ?? false;
|
|
42
44
|
const initialPage = Math.max(1, Math.floor(options?.initialPage ?? 1));
|
|
@@ -54,13 +56,16 @@ export function useFronticSearch(name, ...args) {
|
|
|
54
56
|
}
|
|
55
57
|
const filterConfig = filter ?? {};
|
|
56
58
|
const sortConfig = sorting ?? {};
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
const
|
|
59
|
+
const seededFilters = seedFilterLists(options?.initialFilters, orFilter);
|
|
60
|
+
const seededSort = options?.initialSort && isSortAllowed(options.initialSort, sortConfig) ? parseSortString(options.initialSort) : void 0;
|
|
61
|
+
const seededSearch = options?.initialSearch?.trim() ? options.initialSearch : void 0;
|
|
62
|
+
const searchTerm = useState(`${cacheKey}-searchTerm`, () => seededSearch ?? "");
|
|
63
|
+
const _orFilterList = useState(`${cacheKey}-orFilterList`, () => seededFilters.or);
|
|
64
|
+
const _andFilterList = useState(`${cacheKey}-andFilterList`, () => seededFilters.and);
|
|
65
|
+
const _rangeFilterList = useState(`${cacheKey}-rangeFilterList`, () => seededFilters.range);
|
|
66
|
+
const _sortQuery = useState(`${cacheKey}-sortQuery`, () => seededSort ?? void 0);
|
|
62
67
|
const _page = useState(`${cacheKey}-page`, () => void 0);
|
|
63
|
-
const _search = useState(`${cacheKey}-search`, () =>
|
|
68
|
+
const _search = useState(`${cacheKey}-search`, () => seededSearch);
|
|
64
69
|
const searchState = useState(`${cacheKey}-searchState`, () => ({
|
|
65
70
|
active: {
|
|
66
71
|
filter: {},
|
|
@@ -90,7 +95,7 @@ export function useFronticSearch(name, ...args) {
|
|
|
90
95
|
sort: !disableSorting ? _sortQuery.value : void 0,
|
|
91
96
|
search: !disableSearch ? _search.value : void 0,
|
|
92
97
|
filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value), ..._rangeFilterList.value] : void 0,
|
|
93
|
-
limit
|
|
98
|
+
limit: toValue(options?.limit)
|
|
94
99
|
})
|
|
95
100
|
);
|
|
96
101
|
const queryConfig = {
|
|
@@ -239,7 +244,7 @@ export function useFronticSearch(name, ...args) {
|
|
|
239
244
|
function emitListingResolved(response, trigger, changedFilter) {
|
|
240
245
|
const pageData = response.page;
|
|
241
246
|
const page = pageData?.current ?? 1;
|
|
242
|
-
const
|
|
247
|
+
const limit = pageData?.limit ?? 0;
|
|
243
248
|
const items = response.items ?? [];
|
|
244
249
|
const payload = {
|
|
245
250
|
listing: String(listingName),
|
|
@@ -252,7 +257,7 @@ export function useFronticSearch(name, ...args) {
|
|
|
252
257
|
page,
|
|
253
258
|
resultCount: items.length,
|
|
254
259
|
totalCount: response.total ?? 0,
|
|
255
|
-
items: toAnalyticsItems(items, (page - 1) *
|
|
260
|
+
items: toAnalyticsItems(items, (page - 1) * limit),
|
|
256
261
|
version: FRONTIC_ANALYTICS_VERSION
|
|
257
262
|
};
|
|
258
263
|
if (trigger === "initial") {
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
import { computed } from "vue";
|
|
1
|
+
import { computed, toValue } from "vue";
|
|
2
2
|
import { useQuery } from "@pinia/colada";
|
|
3
|
+
import { resolveContextDomain } from "../utils/resolve-context-domain.js";
|
|
3
4
|
import { fetchTreeQuery } from "./trees.js";
|
|
4
5
|
import { useFronticClient } from "./useFronticClient.js";
|
|
5
6
|
export function useFronticTree(name, options) {
|
|
6
|
-
const _client = useFronticClient();
|
|
7
|
+
const _client = useFronticClient({ contextDomain: false });
|
|
8
|
+
const autoContextDomain = resolveContextDomain();
|
|
9
|
+
const resolvedContextDomain = computed(() => toValue(options?.contextDomain) ?? autoContextDomain);
|
|
7
10
|
const treeQuery = fetchTreeQuery({
|
|
8
11
|
name,
|
|
9
12
|
key: options?.key,
|
|
10
13
|
depth: options?.depth,
|
|
11
14
|
contextKey: options?.contextKey,
|
|
12
|
-
contextDomain:
|
|
15
|
+
contextDomain: resolvedContextDomain,
|
|
13
16
|
requestUrl: options?.requestUrl,
|
|
14
17
|
staleTime: options?.staleTime,
|
|
15
18
|
gcTime: options?.gcTime,
|
|
@@ -1,21 +1,59 @@
|
|
|
1
1
|
import { proxyRequest, getHeader, createError, defineEventHandler } from "h3";
|
|
2
|
-
import { useRuntimeConfig } from "nitropack/runtime";
|
|
2
|
+
import { useRuntimeConfig, useNitroApp } from "nitropack/runtime";
|
|
3
|
+
import { toFetchErrorDetail, isTimeoutError } from "../../../utils/describe-error.js";
|
|
4
|
+
import { FRONTIC_FETCH_ERROR_VERSION } from "../../../types/errors.js";
|
|
5
|
+
const DEFAULT_PROXY_TIMEOUT_MS = 1e4;
|
|
3
6
|
export default defineEventHandler(async (event) => {
|
|
4
7
|
const targetUrl = getHeader(event, "fs-target-url");
|
|
8
|
+
function report(error, status) {
|
|
9
|
+
const payload = {
|
|
10
|
+
operation: "proxy",
|
|
11
|
+
...targetUrl && { targetUrl },
|
|
12
|
+
...getHeader(event, "fs-context") && { contextKey: getHeader(event, "fs-context") },
|
|
13
|
+
...getHeader(event, "fs-domain") && { contextDomain: getHeader(event, "fs-domain") },
|
|
14
|
+
...getHeader(event, "fs-request-url") && { requestUrl: getHeader(event, "fs-request-url") },
|
|
15
|
+
...toFetchErrorDetail(error),
|
|
16
|
+
status,
|
|
17
|
+
version: FRONTIC_FETCH_ERROR_VERSION
|
|
18
|
+
};
|
|
19
|
+
const hooks = useNitroApp().hooks;
|
|
20
|
+
void Promise.resolve(hooks.callHook("frontic:fetch:error", payload)).catch(() => {
|
|
21
|
+
});
|
|
22
|
+
}
|
|
5
23
|
if (!targetUrl) {
|
|
6
|
-
|
|
24
|
+
const badRequest = createError({
|
|
7
25
|
statusCode: 400,
|
|
8
26
|
statusMessage: "Bad Request",
|
|
9
27
|
message: "Missing fs-target-url header"
|
|
10
28
|
});
|
|
29
|
+
report(badRequest, 400);
|
|
30
|
+
throw badRequest;
|
|
11
31
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
32
|
+
try {
|
|
33
|
+
if (event.node?.req?.headers) {
|
|
34
|
+
delete event.node.req.headers["fs-target-url"];
|
|
35
|
+
delete event.node.req.headers["cookie"];
|
|
36
|
+
delete event.node.req.headers["authorization"];
|
|
37
|
+
}
|
|
38
|
+
const config = useRuntimeConfig(event);
|
|
39
|
+
const fetchApiSecret = config.frontic?.fetchApiSecret;
|
|
40
|
+
if (fetchApiSecret && !getHeader(event, "fs-secret") && event.node?.req?.headers) {
|
|
41
|
+
event.node.req.headers["fs-secret"] = fetchApiSecret;
|
|
42
|
+
}
|
|
43
|
+
const configured = config.frontic?.proxyTimeout;
|
|
44
|
+
const timeout = typeof configured === "number" ? configured : DEFAULT_PROXY_TIMEOUT_MS;
|
|
45
|
+
const signal = timeout > 0 ? AbortSignal.timeout(timeout) : void 0;
|
|
46
|
+
return await proxyRequest(event, targetUrl, signal ? { fetchOptions: { signal } } : void 0);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
const detail = toFetchErrorDetail(error);
|
|
49
|
+
const timedOut = isTimeoutError(error);
|
|
50
|
+
const status = timedOut ? 504 : detail.status ?? 500;
|
|
51
|
+
report(error, status);
|
|
52
|
+
throw createError({
|
|
53
|
+
statusCode: status,
|
|
54
|
+
statusMessage: timedOut ? "Gateway Timeout" : "Bad Gateway",
|
|
55
|
+
message: detail.message,
|
|
56
|
+
cause: error
|
|
57
|
+
});
|
|
19
58
|
}
|
|
20
|
-
return proxyRequest(event, targetUrl);
|
|
21
59
|
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { defineEventHandler, getHeader, getRequestHost, setResponseHeader, setResponseStatus, createError } from "h3";
|
|
2
|
+
import { useRuntimeConfig, defineCachedFunction } from "nitropack/runtime";
|
|
3
|
+
const SITEMAP_PATH = /^(\/.*)?\/sitemap(\d*)\.xml$/;
|
|
4
|
+
const DOMAIN_SHAPE = /^[a-z0-9.-]+(?::\d+)?(?:\/[a-z0-9._~%-]+)*$/;
|
|
5
|
+
const CACHE_MAX_AGE_SECONDS = 600;
|
|
6
|
+
const fetchSitemap = defineCachedFunction(
|
|
7
|
+
async (baseUrl, secret, domain, index) => {
|
|
8
|
+
const headers = { "fs-domain": domain };
|
|
9
|
+
if (secret) headers["fs-secret"] = secret;
|
|
10
|
+
const response = await fetch(`${baseUrl}/sitemap${index}.xml`, { headers });
|
|
11
|
+
if (response.status === 404) {
|
|
12
|
+
throw createError({ statusCode: 404, message: "Sitemap not found" });
|
|
13
|
+
}
|
|
14
|
+
if (!response.ok) {
|
|
15
|
+
throw createError({ statusCode: 502, message: `Sitemap upstream responded with ${response.status}` });
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
body: await response.text(),
|
|
19
|
+
etag: response.headers.get("etag") ?? void 0,
|
|
20
|
+
lastModified: response.headers.get("last-modified") ?? void 0
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
name: "frontic-sitemap",
|
|
25
|
+
maxAge: CACHE_MAX_AGE_SECONDS,
|
|
26
|
+
swr: true,
|
|
27
|
+
getKey: (_baseUrl, _secret, domain, index) => `${domain}:${index || "0"}`,
|
|
28
|
+
shouldBypassCache: () => !!import.meta.dev
|
|
29
|
+
}
|
|
30
|
+
);
|
|
31
|
+
export default defineEventHandler(async (event) => {
|
|
32
|
+
const path = event.path.split("?")[0] ?? "";
|
|
33
|
+
const match = SITEMAP_PATH.exec(path);
|
|
34
|
+
if (!match) return;
|
|
35
|
+
const config = useRuntimeConfig(event);
|
|
36
|
+
const baseUrl = config.frontic?.sitemapBaseUrl;
|
|
37
|
+
if (!baseUrl) return;
|
|
38
|
+
const host = getRequestHost(event, { xForwardedHost: true });
|
|
39
|
+
const domain = `${host}${match[1] ?? ""}`.toLowerCase();
|
|
40
|
+
const index = match[2] ?? "";
|
|
41
|
+
const allowedDomains = config.frontic?.sitemapDomains ?? [];
|
|
42
|
+
if (domain.length > 255 || !DOMAIN_SHAPE.test(domain) || allowedDomains.length > 0 && !allowedDomains.includes(domain)) {
|
|
43
|
+
throw createError({ statusCode: 404, message: "Sitemap not found" });
|
|
44
|
+
}
|
|
45
|
+
const sitemap = await fetchSitemap(baseUrl, config.frontic?.fetchApiSecret ?? "", domain, index);
|
|
46
|
+
if (sitemap.etag && getHeader(event, "if-none-match") === sitemap.etag) {
|
|
47
|
+
setResponseStatus(event, 304);
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
setResponseHeader(event, "Content-Type", "text/xml; charset=utf-8");
|
|
51
|
+
setResponseHeader(event, "Cache-Control", `public, max-age=0, s-maxage=${CACHE_MAX_AGE_SECONDS}, stale-while-revalidate=3600`);
|
|
52
|
+
if (sitemap.etag) setResponseHeader(event, "ETag", sitemap.etag);
|
|
53
|
+
if (sitemap.lastModified) setResponseHeader(event, "Last-Modified", sitemap.lastModified);
|
|
54
|
+
return sitemap.body;
|
|
55
|
+
});
|
|
@@ -31,4 +31,6 @@ export interface FronticClient {
|
|
|
31
31
|
region: string;
|
|
32
32
|
locale: string;
|
|
33
33
|
}, token: string, config?: RequestOptions): Promise<Context>;
|
|
34
|
+
/** Fetch the sitemap XML for a Frontic domain, optionally a sub-sitemap by index (starting at 1) */
|
|
35
|
+
sitemap(domain: string, index?: number | null, config?: RequestOptions): Promise<string>;
|
|
34
36
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Payload for the `frontic:fetch:error` hook.
|
|
3
|
+
*
|
|
4
|
+
* Fired wherever a Frontic call fails, so failures can be reported centrally
|
|
5
|
+
* instead of wired up per call site.
|
|
6
|
+
*
|
|
7
|
+
* Unlike the analytics hooks, this one fires on the server as well as the
|
|
8
|
+
* client: a request that dies during SSR is exactly the failure worth
|
|
9
|
+
* reporting, and suppressing it would hide the ones that matter most.
|
|
10
|
+
*/
|
|
11
|
+
/** Which client call failed. `contextList` and `contextUpdate` both report as `context`. */
|
|
12
|
+
export type FronticFetchOperation = 'block' | 'listing' | 'tree' | 'page' | 'context' | 'proxy' | 'sitemap';
|
|
13
|
+
export interface FronticFetchError {
|
|
14
|
+
operation: FronticFetchOperation;
|
|
15
|
+
/** Block, listing or tree name. Absent for `page`, `context`, `proxy` and `sitemap`. */
|
|
16
|
+
name?: string;
|
|
17
|
+
/** Page slug. Present for `page` only. */
|
|
18
|
+
slug?: string;
|
|
19
|
+
/** Frontic domain the sitemap was requested for. Present for `sitemap` only. */
|
|
20
|
+
domain?: string;
|
|
21
|
+
/** Resolved context domain the call was made under */
|
|
22
|
+
contextDomain?: string;
|
|
23
|
+
/** Context token the call was made under */
|
|
24
|
+
contextKey?: string;
|
|
25
|
+
/** The page URL the call originated from */
|
|
26
|
+
requestUrl?: string;
|
|
27
|
+
/** Proxy path in use, absent when the call went direct */
|
|
28
|
+
proxyUrl?: string;
|
|
29
|
+
/** Upstream URL, for proxy failures */
|
|
30
|
+
targetUrl?: string;
|
|
31
|
+
/** HTTP status. Absent when the failure never reached a response. */
|
|
32
|
+
status?: number;
|
|
33
|
+
/**
|
|
34
|
+
* The `cause` chain, outermost first. `cause` is non-enumerable, so this is
|
|
35
|
+
* the only place the real reason — ECONNRESET, ETIMEDOUT, DNS, TLS — survives
|
|
36
|
+
* serialisation.
|
|
37
|
+
*/
|
|
38
|
+
chain: string[];
|
|
39
|
+
/** The chain as one line, for logs */
|
|
40
|
+
message: string;
|
|
41
|
+
/** The original error, for `captureException` */
|
|
42
|
+
error: unknown;
|
|
43
|
+
/** Bumped only on a breaking payload shape change, never on added fields. */
|
|
44
|
+
version: number;
|
|
45
|
+
}
|
|
46
|
+
/** Bumped only on a breaking payload shape change, never on added fields. */
|
|
47
|
+
export declare const FRONTIC_FETCH_ERROR_VERSION = 1;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const FRONTIC_FETCH_ERROR_VERSION = 1;
|
|
@@ -10,6 +10,7 @@ export type { FronticClient } from './client.js';
|
|
|
10
10
|
export type { FronticRequestOptions, FronticQueryOptions, InclusionMode, FilterField, SortField, SortString, SortStringOf, ListingQuery, ListingEnvelope, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationStats, Pagination, FilterData, AggregationData, FilterGroup, AggregationGroup, } from './listing.js';
|
|
11
11
|
export type { RangeFilterValue } from '../utils/filter-helpers.js';
|
|
12
12
|
export type { FronticAnalyticsItem, FronticListingTrigger, FronticListingResolved, FronticSearchCommitted, FronticPageResolved } from '../composables/analytics.js';
|
|
13
|
+
export type { FronticFetchError, FronticFetchOperation } from './errors.js';
|
|
13
14
|
export type { SearchState, UseFronticSearchOptions, UseSearchReturn } from './search.js';
|
|
14
15
|
export type { UseFronticClientOptions } from '../composables/useFronticClient.js';
|
|
15
16
|
export type { UseFronticBlockOptions } from '../composables/useFronticBlock.js';
|
|
@@ -72,6 +72,19 @@ export interface FronticOptions {
|
|
|
72
72
|
* @default true
|
|
73
73
|
*/
|
|
74
74
|
proxy?: boolean | string;
|
|
75
|
+
/**
|
|
76
|
+
* Milliseconds before the proxy gives up on the Frontic API.
|
|
77
|
+
*
|
|
78
|
+
* Without a bound, a stalled upstream holds the request for undici's 300s
|
|
79
|
+
* default — long past the point the page is lost, and long enough to exhaust
|
|
80
|
+
* the server's connection pool. A timeout surfaces as a 504 through
|
|
81
|
+
* `frontic:fetch:error`.
|
|
82
|
+
*
|
|
83
|
+
* Set `0` to disable, which restores the unbounded behaviour.
|
|
84
|
+
*
|
|
85
|
+
* @default 10000
|
|
86
|
+
*/
|
|
87
|
+
proxyTimeout?: number;
|
|
75
88
|
/**
|
|
76
89
|
* Context domain for scope/region/locale resolution and page slug construction.
|
|
77
90
|
*
|
|
@@ -125,6 +138,23 @@ export interface FronticOptions {
|
|
|
125
138
|
* @default true
|
|
126
139
|
*/
|
|
127
140
|
throwOn404?: boolean;
|
|
141
|
+
/**
|
|
142
|
+
* Serve the project's Frontic sitemap from this app
|
|
143
|
+
*
|
|
144
|
+
* Registers a server route answering `/sitemap.xml` (and `/sitemapN.xml`
|
|
145
|
+
* for split sitemaps) on every locale prefix, proxying the Fetch API
|
|
146
|
+
* sitemap for the matching domain. Requires the generated Frontic client.
|
|
147
|
+
*
|
|
148
|
+
* The route derives the Frontic domain from the (client-controlled)
|
|
149
|
+
* forwarded host, bounded to the app's declared domains. `domains` declares
|
|
150
|
+
* them explicitly; without it the allowlist comes from `contextDomain`
|
|
151
|
+
* config, and with neither the route accepts any well-formed host.
|
|
152
|
+
*
|
|
153
|
+
* @default false
|
|
154
|
+
*/
|
|
155
|
+
sitemap?: boolean | {
|
|
156
|
+
domains?: string[];
|
|
157
|
+
};
|
|
128
158
|
/**
|
|
129
159
|
* API secret for authenticating Fetch API requests
|
|
130
160
|
* Required for protected environments (e.g., development/staging)
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Type definitions for the useFronticSearch composable.
|
|
5
5
|
* These types provide type-safe filtering, sorting, and pagination for Frontic search listings.
|
|
6
6
|
*/
|
|
7
|
-
import type { Ref, ShallowRef } from 'vue';
|
|
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
10
|
import type { FronticRequestOptions, FronticQueryOptions, ListingFieldConfig, SortStringOf, UiFilter, UiSort } from './listing.js';
|
|
@@ -84,6 +84,34 @@ export interface UseFronticSearchOptions<TSearch extends ListingName = ListingNa
|
|
|
84
84
|
* Controls how long to wait after the user stops typing before triggering a search request.
|
|
85
85
|
*/
|
|
86
86
|
searchDebounce?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Search term to start from, committed before the first query runs.
|
|
89
|
+
*
|
|
90
|
+
* The debounced input path cannot carry a term that arrives with the request:
|
|
91
|
+
* on the server the timer never fires before the render finishes, and on the
|
|
92
|
+
* client the hydrated value never changes, so the watcher never sees it. Seed
|
|
93
|
+
* it here instead — a `?name=` restored on the server reaches the first query.
|
|
94
|
+
*
|
|
95
|
+
* An empty or whitespace-only value is treated as no search. Unlike the typed
|
|
96
|
+
* path this is not subject to `searchTermThreshold`: the threshold exists to
|
|
97
|
+
* stop a request per keystroke, and a term that arrived with the request was
|
|
98
|
+
* not typed — dropping it would render results that contradict the URL.
|
|
99
|
+
*/
|
|
100
|
+
initialSearch?: string;
|
|
101
|
+
/**
|
|
102
|
+
* Filters to start from, keyed by field, in the same shape `filterResult`
|
|
103
|
+
* takes. Range values are recognised by shape; every other field is routed
|
|
104
|
+
* through `orFilter` exactly as an interaction would route it.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* initialFilters: { hersteller: ['Atomic'], 'price.amount': { from: 20, to: 100 } }
|
|
108
|
+
*/
|
|
109
|
+
initialFilters?: Partial<Record<keyof TFilters & string, unknown>>;
|
|
110
|
+
/**
|
|
111
|
+
* Sort to start from, in the same `'field:order'` form `sortResult` takes.
|
|
112
|
+
* Ignored when the sorting config disallows it, like any other sort.
|
|
113
|
+
*/
|
|
114
|
+
initialSort?: SortStringOf<TSorts>;
|
|
87
115
|
/**
|
|
88
116
|
* Analytics thresholds, deliberately separate from the UX knobs above.
|
|
89
117
|
* The debounce that keeps a listing responsive and the delay that decides a
|
|
@@ -169,8 +197,12 @@ export interface UseFronticSearchOptions<TSearch extends ListingName = ListingNa
|
|
|
169
197
|
/**
|
|
170
198
|
* Number of items per page (sent as `limit` to the Frontic API).
|
|
171
199
|
* When omitted, the backend default is used.
|
|
200
|
+
*
|
|
201
|
+
* Accepts a ref: a page size that depends on something resolved after setup
|
|
202
|
+
* enters the query key when it changes, so the listing refetches rather than
|
|
203
|
+
* keeping the size it was created with.
|
|
172
204
|
*/
|
|
173
|
-
limit?: number
|
|
205
|
+
limit?: MaybeRef<number | undefined>;
|
|
174
206
|
/**
|
|
175
207
|
* Enable infinite scroll mode.
|
|
176
208
|
* When true, loadNext()/loadPrev() append/prepend items from adjacent pages
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error description for the `frontic:fetch:error` hook.
|
|
3
|
+
*
|
|
4
|
+
* Connection-level failures arrive as a bare "Bad Gateway" or "fetch failed"
|
|
5
|
+
* with the actual reason — ECONNRESET, ETIMEDOUT, DNS, TLS — buried in `cause`.
|
|
6
|
+
* `cause` is non-enumerable, so it is absent from `console.error(err)` and from
|
|
7
|
+
* anything that serialises the error, and has to be walked explicitly.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Flatten an error and its `cause` chain, outermost first.
|
|
11
|
+
*
|
|
12
|
+
* Returned as an array rather than a joined string so a consumer can send the
|
|
13
|
+
* frames to an error tracker individually; {@link toFetchErrorDetail} joins
|
|
14
|
+
* them for logs.
|
|
15
|
+
*/
|
|
16
|
+
export declare function describeErrorChain(error: unknown): string[];
|
|
17
|
+
/**
|
|
18
|
+
* Whether a failure — or anything in its cause chain — is an abort or timeout.
|
|
19
|
+
*
|
|
20
|
+
* The chain matters: h3's `sendProxy` catches every fetch failure and rethrows
|
|
21
|
+
* `createError({ status: 502, cause: error })`, so by the time a handler sees
|
|
22
|
+
* it the outermost error is an H3Error carrying a 502 and the real
|
|
23
|
+
* `TimeoutError` sits two levels down. Testing only the top-level error can
|
|
24
|
+
* never see a timeout.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isTimeoutError(error: unknown): boolean;
|
|
27
|
+
export interface FronticFetchErrorDetail {
|
|
28
|
+
/** The original error, unwrapped, for `captureException` */
|
|
29
|
+
error: unknown;
|
|
30
|
+
/** The cause chain, outermost first */
|
|
31
|
+
chain: string[];
|
|
32
|
+
/** The chain as one line, for logs */
|
|
33
|
+
message: string;
|
|
34
|
+
/** HTTP status, absent when the failure never reached a response */
|
|
35
|
+
status?: number;
|
|
36
|
+
}
|
|
37
|
+
/** Describe a failure once, so every call site reports it the same way. */
|
|
38
|
+
export declare function toFetchErrorDetail(error: unknown): FronticFetchErrorDetail;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const MAX_CAUSE_DEPTH = 5;
|
|
2
|
+
export function describeErrorChain(error) {
|
|
3
|
+
const chain = [];
|
|
4
|
+
let current = error;
|
|
5
|
+
for (let depth = 0; current instanceof Error && depth < MAX_CAUSE_DEPTH; depth++) {
|
|
6
|
+
const code = current.code;
|
|
7
|
+
chain.push(`${current.name}${code ? `(${code})` : ""}: ${current.message}`);
|
|
8
|
+
current = current.cause;
|
|
9
|
+
}
|
|
10
|
+
return chain.length > 0 ? chain : [String(error)];
|
|
11
|
+
}
|
|
12
|
+
export function isTimeoutError(error) {
|
|
13
|
+
let current = error;
|
|
14
|
+
for (let depth = 0; current instanceof Error && depth < MAX_CAUSE_DEPTH; depth++) {
|
|
15
|
+
const code = current.code;
|
|
16
|
+
if (current.name === "TimeoutError" || current.name === "AbortError" || code === "ETIMEDOUT" || code === "ABORT_ERR") {
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
current = current.cause;
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
function statusOf(error) {
|
|
24
|
+
const e = error;
|
|
25
|
+
for (const candidate of [e?.statusCode, e?.status, e?.response?.status]) {
|
|
26
|
+
if (typeof candidate === "number") return candidate;
|
|
27
|
+
}
|
|
28
|
+
return void 0;
|
|
29
|
+
}
|
|
30
|
+
export function toFetchErrorDetail(error) {
|
|
31
|
+
const chain = describeErrorChain(error);
|
|
32
|
+
return {
|
|
33
|
+
error,
|
|
34
|
+
chain,
|
|
35
|
+
message: chain.join(" <- "),
|
|
36
|
+
...statusOf(error) !== void 0 && { status: statusOf(error) }
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -146,3 +146,16 @@ export declare function hasFilter<T = Record<string, unknown>>(filterList: Equal
|
|
|
146
146
|
* @returns Array of current filter values, or empty array if no filter exists
|
|
147
147
|
*/
|
|
148
148
|
export declare function getFilterValues<T = Record<string, unknown>>(filterList: EqualsFilter<T>[], field: keyof T & string): T[keyof T][];
|
|
149
|
+
/**
|
|
150
|
+
* Split a field -> value map into the three lists the query is built from.
|
|
151
|
+
*
|
|
152
|
+
* Routes each field exactly as the mutators would: range values by shape, and
|
|
153
|
+
* everything else into the or- or and-list depending on `orFields`. Seeded
|
|
154
|
+
* state therefore produces the same query an interaction would, rather than a
|
|
155
|
+
* second parallel notion of what a filter means.
|
|
156
|
+
*/
|
|
157
|
+
export declare function seedFilterLists<T = Record<string, unknown>>(initial: Partial<Record<keyof T & string, unknown>> | undefined, orFields: Array<keyof T & string>): {
|
|
158
|
+
or: EqualsFilter<T>[];
|
|
159
|
+
and: EqualsFilter<T>[];
|
|
160
|
+
range: RangeFilter[];
|
|
161
|
+
};
|
|
@@ -70,3 +70,17 @@ export function getFilterValues(filterList, field) {
|
|
|
70
70
|
if (!filter) return [];
|
|
71
71
|
return Array.isArray(filter.value) ? filter.value : [filter.value];
|
|
72
72
|
}
|
|
73
|
+
export function seedFilterLists(initial, orFields) {
|
|
74
|
+
const lists = { or: [], and: [], range: [] };
|
|
75
|
+
if (!initial) return lists;
|
|
76
|
+
for (const [field, value] of Object.entries(initial)) {
|
|
77
|
+
if (value === void 0 || value === null) continue;
|
|
78
|
+
if (isRangeFilterValue(value)) {
|
|
79
|
+
lists.range = manageRangeFilter(lists.range, field, value);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const target = orFields.includes(field) ? "or" : "and";
|
|
83
|
+
lists[target] = manageFilter(lists[target], field, value);
|
|
84
|
+
}
|
|
85
|
+
return lists;
|
|
86
|
+
}
|
|
@@ -1 +1,15 @@
|
|
|
1
1
|
export declare function resolveI18nContextDomain(): string | undefined;
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the contextDomain a request will actually carry.
|
|
4
|
+
*
|
|
5
|
+
* The client injects this into every request; the composables key on it, so
|
|
6
|
+
* that responses fetched under different domains never share a cache entry.
|
|
7
|
+
* Both sides must call this — deriving the request from one value and the
|
|
8
|
+
* query key from another is what FSC-4523 was.
|
|
9
|
+
*
|
|
10
|
+
* Reads `useNuxtApp()` when the module config is `true`, so call it during
|
|
11
|
+
* setup rather than from a lazily evaluated query key.
|
|
12
|
+
*
|
|
13
|
+
* @param override - A per-call domain, or `false` to send none.
|
|
14
|
+
*/
|
|
15
|
+
export declare function resolveContextDomain(override?: false | string): string | undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useNuxtApp } from "nuxt/app";
|
|
1
|
+
import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
2
2
|
export function resolveI18nContextDomain() {
|
|
3
3
|
try {
|
|
4
4
|
const app = useNuxtApp();
|
|
@@ -15,3 +15,11 @@ export function resolveI18nContextDomain() {
|
|
|
15
15
|
}
|
|
16
16
|
return void 0;
|
|
17
17
|
}
|
|
18
|
+
export function resolveContextDomain(override) {
|
|
19
|
+
if (override === false) return void 0;
|
|
20
|
+
if (typeof override === "string") return override;
|
|
21
|
+
const configDomain = useRuntimeConfig().public.frontic?.contextDomain;
|
|
22
|
+
if (typeof configDomain === "string") return configDomain;
|
|
23
|
+
if (configDomain === true) return resolveI18nContextDomain();
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
package/package.json
CHANGED