@frontic/nuxt 0.8.4 → 1.0.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.
Files changed (52) hide show
  1. package/README.md +30 -2
  2. package/dist/module.d.mts +2 -132
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +63 -7
  5. package/dist/runtime/composables/analytics.d.ts +82 -0
  6. package/dist/runtime/composables/analytics.js +38 -0
  7. package/dist/runtime/composables/blocks.d.ts +24 -22
  8. package/dist/runtime/composables/blocks.js +16 -16
  9. package/dist/runtime/composables/index.d.ts +1 -1
  10. package/dist/runtime/composables/listings.d.ts +22 -13
  11. package/dist/runtime/composables/listings.js +24 -25
  12. package/dist/runtime/composables/pages.d.ts +21 -18
  13. package/dist/runtime/composables/pages.js +15 -16
  14. package/dist/runtime/composables/trees.d.ts +24 -22
  15. package/dist/runtime/composables/trees.js +15 -25
  16. package/dist/runtime/composables/useFronticBlock.d.ts +22 -13
  17. package/dist/runtime/composables/useFronticBlock.js +19 -2
  18. package/dist/runtime/composables/useFronticClient.d.ts +6 -3
  19. package/dist/runtime/composables/useFronticContext.d.ts +12 -0
  20. package/dist/runtime/composables/useFronticContext.js +71 -9
  21. package/dist/runtime/composables/useFronticListing.d.ts +23 -19
  22. package/dist/runtime/composables/useFronticListing.js +22 -3
  23. package/dist/runtime/composables/useFronticPage.d.ts +35 -16
  24. package/dist/runtime/composables/useFronticPage.js +36 -7
  25. package/dist/runtime/composables/useFronticSearch.d.ts +4 -96
  26. package/dist/runtime/composables/useFronticSearch.js +179 -51
  27. package/dist/runtime/composables/useFronticTree.d.ts +23 -14
  28. package/dist/runtime/composables/useFronticTree.js +19 -2
  29. package/dist/runtime/server/plugins/fetch-secret.d.ts +2 -0
  30. package/dist/runtime/server/plugins/fetch-secret.js +20 -0
  31. package/dist/runtime/types/client.d.ts +34 -0
  32. package/dist/runtime/types/client.js +0 -0
  33. package/dist/runtime/types/index.d.ts +8 -3
  34. package/dist/runtime/types/listing.d.ts +113 -251
  35. package/dist/runtime/types/options.d.ts +139 -0
  36. package/dist/runtime/types/options.js +0 -0
  37. package/dist/runtime/types/query.d.ts +88 -0
  38. package/dist/runtime/types/query.js +0 -0
  39. package/dist/runtime/types/registry.d.ts +272 -0
  40. package/dist/runtime/types/registry.js +0 -0
  41. package/dist/runtime/types/search.d.ts +56 -36
  42. package/dist/runtime/utils/errors.d.ts +22 -0
  43. package/dist/runtime/utils/errors.js +3 -0
  44. package/dist/runtime/utils/index.d.ts +2 -0
  45. package/dist/runtime/utils/index.js +2 -0
  46. package/dist/runtime/utils/query-keys.d.ts +27 -0
  47. package/dist/runtime/utils/query-keys.js +18 -0
  48. package/dist/runtime/utils/state-helpers.d.ts +3 -6
  49. package/dist/runtime/utils/state-helpers.js +7 -8
  50. package/dist/types.d.mts +2 -2
  51. package/package.json +15 -15
  52. package/dist/runtime/frontic-stack.d.ts +0 -168
package/README.md CHANGED
@@ -10,6 +10,7 @@ Nuxt module for building with the [Frontic](https://frontic.com) API and [Fronti
10
10
  - **Page routing** - Dynamic page resolution with automatic redirects and 404 handling
11
11
  - **Context management** - Locale and region switching with cookie persistence
12
12
  - **Infinite scroll** - Bidirectional infinite loading with deep-link support via Pinia Colada's `useInfiniteQuery`
13
+ - **Analytics hooks** - Typed `frontic:listing:resolved`, `frontic:search:committed` and `frontic:page:resolved` events for any analytics vendor
13
14
  - **Built-in proxy** - CORS-free API requests through your Nuxt server
14
15
 
15
16
  ## Installation
@@ -71,7 +72,8 @@ const { result, state, searchTerm, filterResult, sortResult, loadNext } = useFro
71
72
  Simple listing access:
72
73
 
73
74
  ```typescript
74
- const { listing, status, refresh } = useFronticListing('FeaturedProducts', { limit: 10 })
75
+ // Second argument is the listing's parameters; query options go in the third
76
+ const { listing, status, error } = useFronticListing('CategoryProducts', { categoryKey: 'shoes' }, { query: { limit: 10 } })
75
77
  ```
76
78
 
77
79
  ### useFronticBlock
@@ -79,9 +81,11 @@ const { listing, status, refresh } = useFronticListing('FeaturedProducts', { lim
79
81
  Fetch single blocks (products, categories):
80
82
 
81
83
  ```typescript
82
- const { block, status } = useFronticBlock('Product', 'product-handle')
84
+ const { block, status, error } = useFronticBlock('ProductCard', 'product-handle')
83
85
  ```
84
86
 
87
+ Every data composable returns `status` and `error` alongside its data, plus `refresh` and `refetch`.
88
+
85
89
  ### useFronticTree
86
90
 
87
91
  Hierarchical menu trees:
@@ -126,6 +130,30 @@ export default defineNuxtConfig({
126
130
  })
127
131
  ```
128
132
 
133
+ ## Analytics
134
+
135
+ Listing, search and page events are announced as typed Nuxt hooks, so any vendor can be wired up in one plugin:
136
+
137
+ ```typescript
138
+ export default defineNuxtPlugin((nuxtApp) => {
139
+ nuxtApp.hook('frontic:listing:resolved', (payload) => {
140
+ if (payload.trigger === 'initial') {
141
+ track('view_item_list', { list: payload.listing, count: payload.resultCount })
142
+ }
143
+ })
144
+ })
145
+ ```
146
+
147
+ Hooks are client-only and deduplicated per route entry. Payload types are importable from `@frontic/nuxt/types` when you factor handlers out of the plugin.
148
+
149
+ ## TypeScript
150
+
151
+ Composable typing comes from your generated client (`npx @frontic/cli generate`): block, listing and tree names, listing parameters, filter and sort fields, and response types all resolve to your project's schema, and invalid names fail the typecheck. Helper types are available from `@frontic/nuxt/types`:
152
+
153
+ ```typescript
154
+ import type { ResponseOf, ListingQuery, SortString, FronticClient } from '@frontic/nuxt/types'
155
+ ```
156
+
129
157
  ## Documentation
130
158
 
131
159
  Full documentation at [docs.frontic.com](https://docs.frontic.com)
package/dist/module.d.mts CHANGED
@@ -1,137 +1,7 @@
1
1
  import { NuxtModule } from '@nuxt/schema';
2
+ import { FronticOptions } from '../dist/runtime/types/options.js';
3
+ export { FronticComposable, FronticComposablesConfig, FronticOptions } from '../dist/runtime/types/options.js';
2
4
 
3
- /**
4
- * Available Frontic composables that can be enabled/disabled
5
- *
6
- * - 'block': useFronticBlock - Fetch single blocks (products, categories)
7
- * - 'listing': useFronticListing - Fetch listings with caching
8
- * - 'search': useFronticSearch - Full-featured search with filters/sorting
9
- * - 'tree': useFronticTree - Fetch hierarchical menu trees
10
- * - 'page': useFronticPage - Dynamic page routing
11
- * - 'context': useFronticContext - Locale/region management
12
- * - 'client': useFronticClient - Low-level API client
13
- */
14
- type FronticComposable = 'block' | 'listing' | 'search' | 'tree' | 'page' | 'context' | 'client';
15
- /**
16
- * Frontic composables configuration
17
- * - true: Enable all composables (default)
18
- * - false or []: Disable all composables
19
- * - string[]: Enable only specified composables
20
- */
21
- type FronticComposablesConfig = boolean | FronticComposable[];
22
- /**
23
- * Frontic module configuration options
24
- */
25
- interface FronticOptions {
26
- /**
27
- * Prefix for all auto-imported Frontic UI components.
28
- * Set to 'Ui' to get `<UiButton>`, or leave empty for `<Button>`.
29
- * @default ''
30
- */
31
- componentsPrefix: string;
32
- /**
33
- * Directory that the components live in.
34
- * @default "@/components/ui"
35
- */
36
- componentDir: string;
37
- /**
38
- * Configure which Frontic composables to auto-import
39
- *
40
- * When a composable is disabled, it will not be auto-imported during the Nuxt build.
41
- * This means you won't get type errors or warnings—the composable simply won't exist.
42
- * Use this to reduce bundle size by excluding composables you don't need.
43
- *
44
- * Available composables:
45
- * - 'block': useFronticBlock - Fetch single blocks
46
- * - 'listing': useFronticListing - Fetch listings
47
- * - 'search': useFronticSearch - Search with filters/sorting
48
- * - 'tree': useFronticTree - Fetch hierarchical menu trees
49
- * - 'page': useFronticPage - Dynamic page routing
50
- * - 'context': useFronticContext - Locale/region management
51
- * - 'client': useFronticClient - Low-level API client
52
- *
53
- * @example
54
- * composables: true // Enable all (default)
55
- * composables: false // Disable all
56
- * composables: ['listing', 'page', 'client'] // Enable specific ones
57
- *
58
- * @default true
59
- */
60
- composables?: FronticComposablesConfig;
61
- /**
62
- * Enable/configure the API proxy for CORS prevention
63
- * - true: Enable proxy at default path '/api/frontic'
64
- * - false: Disable proxy
65
- * - string: Enable proxy at custom path
66
- *
67
- * @default true
68
- */
69
- proxy?: boolean | string;
70
- /**
71
- * Context domain for scope/region/locale resolution and page slug construction.
72
- *
73
- * Controls which Frontic domain is used across all composables:
74
- * - useFronticPage: prepended to the pathname to construct the page slug
75
- * - useFronticBlock/Listing/Context: injected as contextDomain request option
76
- *
77
- * - string: Static domain (e.g. 'shop.com')
78
- * - true: Read `contextDomain` property from current @nuxtjs/i18n locale object
79
- *
80
- * When not set, useFronticPage derives the domain from the request URL host.
81
- *
82
- * @example 'demo-shop.com'
83
- * @example true
84
- */
85
- contextDomain?: string | boolean;
86
- /**
87
- * Cookie name for persisting the context token
88
- * @default 'fs-context'
89
- */
90
- contextCookieName?: string;
91
- /**
92
- * Cookie max age in seconds for context token
93
- * @default 31536000 (1 year)
94
- */
95
- contextCookieMaxAge?: number;
96
- /**
97
- * Disable automatic context fetching and cookie management in useFronticContext
98
- *
99
- * When true:
100
- * - The context endpoint will NOT be called automatically on mount
101
- * - No context cookie will be set automatically
102
- * - You must manually call `refresh()` to fetch contexts
103
- * - You are responsible for storing and managing the context token
104
- *
105
- * Use this when you want full control over context management,
106
- * or when integrating with an existing locale/region system.
107
- *
108
- * @default false
109
- */
110
- disableContext?: boolean;
111
- /**
112
- * Automatically redirect on 301 responses
113
- * Can be overridden per-request in useFronticPage
114
- * @default true
115
- */
116
- redirectOn301?: boolean;
117
- /**
118
- * Throw a 404 error when page is not found
119
- * Can be overridden per-request in useFronticPage
120
- * @default true
121
- */
122
- throwOn404?: boolean;
123
- /**
124
- * API secret for authenticating Fetch API requests
125
- * Required for protected environments (e.g., development/staging)
126
- * Stored in private runtime config (server-only, never exposed to browser)
127
- *
128
- * For client-side requests, the secret is automatically injected by the proxy
129
- *
130
- * @example process.env.FRONTIC_FETCH_SECRET
131
- */
132
- fetchApiSecret?: string;
133
- }
134
5
  declare const module$1: NuxtModule<FronticOptions>;
135
6
 
136
7
  export { module$1 as default };
137
- export type { FronticComposable, FronticComposablesConfig, FronticOptions };
package/dist/module.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "frontic",
3
3
  "configKey": "frontic",
4
- "version": "0.7.0",
4
+ "version": "1.0.0",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.0.0"
7
7
  },
8
8
  "builder": {
9
- "@nuxt/module-builder": "1.0.2",
9
+ "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "unknown"
11
11
  }
12
12
  }
package/dist/module.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
1
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { defineNuxtModule, createResolver, addServerHandler, hasNuxtModule, installModule, addImports, addComponentsDir, addComponentExports } from '@nuxt/kit';
5
+ import { defineNuxtModule, createResolver, addServerHandler, addServerPlugin, hasNuxtModule, installModule, addImports, addTypeTemplate, addComponentsDir, addComponentExports } from '@nuxt/kit';
6
6
 
7
7
  function isFronticUiInitialized(rootDir) {
8
8
  const configPath = join(rootDir, "components.json");
@@ -15,6 +15,14 @@ function isFronticUiInitialized(rootDir) {
15
15
  }
16
16
  }
17
17
  const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
18
+ function readGeneratorSchemaVersion(clientDir) {
19
+ try {
20
+ const metadata = JSON.parse(readFileSync(join(clientDir, "metadata.json"), "utf-8"));
21
+ return typeof metadata.generator?.schemaVersion === "number" ? metadata.generator.schemaVersion : 1;
22
+ } catch {
23
+ return 1;
24
+ }
25
+ }
18
26
  const ALL_COMPOSABLES = ["block", "listing", "search", "tree", "page", "context", "client"];
19
27
  function isComposableEnabled(config, name) {
20
28
  if (config === true) return true;
@@ -22,6 +30,7 @@ function isComposableEnabled(config, name) {
22
30
  if (Array.isArray(config)) return config.includes(name);
23
31
  return true;
24
32
  }
33
+ const MODULE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
25
34
  const module$1 = defineNuxtModule({
26
35
  defaults: {
27
36
  componentsPrefix: "",
@@ -38,7 +47,7 @@ const module$1 = defineNuxtModule({
38
47
  meta: {
39
48
  name: "frontic",
40
49
  configKey: "frontic",
41
- version: "0.7.0",
50
+ version: MODULE_VERSION,
42
51
  compatibility: {
43
52
  nuxt: ">=4.0.0"
44
53
  }
@@ -66,6 +75,11 @@ const module$1 = defineNuxtModule({
66
75
  const fronticClientDir = join(ROOT_DIR_PATH, ".frontic");
67
76
  const fronticClientPath = join(fronticClientDir, fronticClientFile);
68
77
  const hasFronticClient = existsSync(fronticClientPath);
78
+ if (hasFronticClient && readGeneratorSchemaVersion(fronticClientDir) < 2) {
79
+ console.warn(
80
+ "\n[@frontic/nuxt] Your generated Frontic client is outdated for this module version.\nComposable name and response types will not resolve (parameters typed as `never`).\nRegenerate with the current CLI: npx @frontic/cli generate\n"
81
+ );
82
+ }
69
83
  const proxyPath = typeof proxyConfig === "string" ? proxyConfig : proxyConfig !== false ? "/api/frontic" : void 0;
70
84
  if (proxyPath && hasFronticClient) {
71
85
  addServerHandler({
@@ -73,6 +87,9 @@ const module$1 = defineNuxtModule({
73
87
  handler: resolveModule("./runtime/server/api/frontic/[...path]")
74
88
  });
75
89
  }
90
+ if (fetchApiSecret && hasFronticClient) {
91
+ addServerPlugin(resolveModule("./runtime/server/plugins/fetch-secret"));
92
+ }
76
93
  const blockEnabled = isComposableEnabled(composablesConfig, "block");
77
94
  const listingEnabled = isComposableEnabled(composablesConfig, "listing");
78
95
  const searchEnabled = isComposableEnabled(composablesConfig, "search");
@@ -101,7 +118,8 @@ frontic: { composables: false }
101
118
  );
102
119
  }
103
120
  const clientDirPath = fronticClientDir;
104
- const piniaEsmPath = anyComposableEnabled ? join(dirname(createRequire(import.meta.url).resolve("pinia/package.json")), "dist/pinia.mjs") : null;
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;
105
123
  nuxt.options.vite ||= {};
106
124
  nuxt.options.vite.resolve ||= {};
107
125
  nuxt.options.vite.resolve.alias ||= {};
@@ -138,6 +156,7 @@ frontic: { composables: false }
138
156
  if (anyComposableEnabled) {
139
157
  const composablesDir = resolve(runtimeDir, "composables");
140
158
  const utilsDir = resolve(runtimeDir, "utils");
159
+ addImports([{ name: "isApiError", from: join(utilsDir, "errors") }]);
141
160
  if (clientEnabled) {
142
161
  addImports([{ name: "useFronticClient", from: join(composablesDir, "useFronticClient") }]);
143
162
  }
@@ -202,10 +221,47 @@ frontic: { composables: false }
202
221
  addImports([{ name: "useFronticContext", from: join(composablesDir, "useFronticContext") }]);
203
222
  }
204
223
  }
224
+ if (contextEnabled) {
225
+ addTypeTemplate({
226
+ filename: "types/frontic-context-hooks.d.ts",
227
+ getContents: () => `import type { FronticContext } from '${resolveModule("./runtime/composables/useFronticContext")}'
228
+
229
+ declare module '#app' {
230
+ interface RuntimeNuxtHooks {
231
+ 'frontic:context:ready': (context: FronticContext) => void | Promise<void>
232
+ 'frontic:context:updated': (context: FronticContext) => void | Promise<void>
233
+ }
234
+ }
235
+
236
+ export {}
237
+ `
238
+ });
239
+ }
240
+ if (searchEnabled || pageEnabled) {
241
+ const analyticsModule = resolveModule("./runtime/composables/analytics");
242
+ const listingHooks = searchEnabled ? ` 'frontic:listing:resolved': (payload: FronticListingResolved) => void | Promise<void>
243
+ 'frontic:search:committed': (payload: FronticSearchCommitted) => void | Promise<void>
244
+ ` : "";
245
+ const pageHooks = pageEnabled ? ` 'frontic:page:resolved': (payload: FronticPageResolved) => void | Promise<void>
246
+ ` : "";
247
+ const imported = [searchEnabled && "FronticListingResolved", searchEnabled && "FronticSearchCommitted", pageEnabled && "FronticPageResolved"].filter(Boolean).join(", ");
248
+ addTypeTemplate({
249
+ filename: "types/frontic-analytics-hooks.d.ts",
250
+ getContents: () => `import type { ${imported} } from '${analyticsModule}'
251
+
252
+ declare module '#app' {
253
+ interface RuntimeNuxtHooks {
254
+ ${listingHooks}${pageHooks} }
255
+ }
256
+
257
+ export {}
258
+ `
259
+ });
260
+ }
205
261
  nuxt.options.runtimeConfig.public.frontic = {
206
262
  hasFronticClient,
207
- proxyPath,
208
- contextDomain,
263
+ proxyPath: proxyPath ?? "",
264
+ contextDomain: contextDomain ?? false,
209
265
  contextCookieName,
210
266
  contextCookieMaxAge,
211
267
  disableContext,
@@ -222,7 +278,7 @@ frontic: { composables: false }
222
278
  }
223
279
  };
224
280
  nuxt.options.runtimeConfig.frontic = {
225
- fetchApiSecret
281
+ fetchApiSecret: fetchApiSecret ?? ""
226
282
  };
227
283
  if (isFronticUiInitialized(ROOT_DIR_PATH)) {
228
284
  const componentsPath = await resolvePath(COMPONENT_DIR_PATH);
@@ -0,0 +1,82 @@
1
+ import type { Page } from '../types/registry.js';
2
+ /**
3
+ * Analytics hook payloads and per-app emission bookkeeping.
4
+ *
5
+ * Bookkeeping lives on `nuxtApp`, never in `useState`. `useState` is serialized
6
+ * into the SSR payload, so a client that hydrated a server-written fingerprint
7
+ * would treat the first paint as already counted and never emit `initial`.
8
+ */
9
+ /** Absolute position of an item within the full result set, plus its raw row. */
10
+ export interface FronticAnalyticsItem {
11
+ key: string;
12
+ index: number;
13
+ data: unknown;
14
+ }
15
+ export type FronticListingTrigger = 'initial' | 'term' | 'filter' | 'sort' | 'page' | 'loadMore' | 'reset';
16
+ export interface FronticListingResolved {
17
+ listing: string;
18
+ cacheKey: string;
19
+ trigger: FronticListingTrigger;
20
+ term?: string;
21
+ filters: Record<string, unknown>;
22
+ changedFilter?: {
23
+ field: string;
24
+ value?: unknown;
25
+ action: 'add' | 'remove';
26
+ };
27
+ sort?: {
28
+ field: string;
29
+ order: 'asc' | 'desc';
30
+ };
31
+ page: number;
32
+ resultCount: number;
33
+ totalCount: number;
34
+ items: FronticAnalyticsItem[];
35
+ version: number;
36
+ }
37
+ export interface FronticSearchCommitted {
38
+ term: string;
39
+ cacheKey: string;
40
+ resultCount: number;
41
+ page: number;
42
+ version: number;
43
+ }
44
+ export interface FronticPageResolved {
45
+ page: Page;
46
+ version: number;
47
+ }
48
+ /** Bumped only on a breaking payload shape change, never on added fields. */
49
+ export declare const FRONTIC_ANALYTICS_VERSION = 1;
50
+ /**
51
+ * Minimal view of the Nuxt app. The hook names are typed for consuming apps
52
+ * through the module's type template; inside the package `#app` is not
53
+ * resolvable, so `RuntimeNuxtHooks` cannot be augmented here and `callHook` is
54
+ * called untyped — the same reason `useFronticContext` casts.
55
+ */
56
+ type NuxtAppLike = {
57
+ callHook: unknown;
58
+ };
59
+ /**
60
+ * Reset dedup bookkeeping on navigation, so returning to a listing counts as a
61
+ * new view. `nuxtApp` survives client-side navigation; without this, the back
62
+ * button into a category would report nothing — the dominant pattern in a
63
+ * catalogue, and an undercount that inflates every per-view rate downstream.
64
+ *
65
+ * Registered once per app instance, on first use.
66
+ */
67
+ export declare function bindRouteReset(nuxtApp: NuxtAppLike): void;
68
+ /** Announce a payload. Hooks are fire-and-forget; a slow listener never blocks a refresh. */
69
+ export declare function emit(nuxtApp: NuxtAppLike, hook: string, payload: unknown): void;
70
+ /**
71
+ * Emit once per dedup key for the current route entry, for events that are not
72
+ * caused by a method call. A `data` watcher fires once per call site, so the
73
+ * first paint of a listing would otherwise be announced once per mounted
74
+ * component. Intent-driven events do not go through here: each is one user
75
+ * action already, and deduping them would swallow a filter re-applied twice.
76
+ *
77
+ * Returns whether the payload was emitted.
78
+ */
79
+ export declare function emitOnce(nuxtApp: NuxtAppLike, dedupKey: string, hook: string, payload: unknown): boolean;
80
+ /** Build the analytics item list, carrying absolute index across pages. */
81
+ export declare function toAnalyticsItems(items: unknown[], indexOffset: number): FronticAnalyticsItem[];
82
+ export {};
@@ -0,0 +1,38 @@
1
+ export const FRONTIC_ANALYTICS_VERSION = 1;
2
+ function runtimeFor(nuxtApp) {
3
+ const app = nuxtApp;
4
+ return app._fronticAnalytics ??= {};
5
+ }
6
+ export function bindRouteReset(nuxtApp) {
7
+ const runtime = runtimeFor(nuxtApp);
8
+ if (runtime.routeBound) return;
9
+ const router = nuxtApp.$router;
10
+ if (typeof router?.afterEach !== "function") return;
11
+ runtime.routeBound = true;
12
+ router.afterEach(() => {
13
+ runtime.seen?.clear();
14
+ });
15
+ }
16
+ function isServer(nuxtApp) {
17
+ return Boolean(nuxtApp.ssrContext);
18
+ }
19
+ export function emit(nuxtApp, hook, payload) {
20
+ if (isServer(nuxtApp)) return;
21
+ void nuxtApp.callHook(hook, payload);
22
+ }
23
+ export function emitOnce(nuxtApp, dedupKey, hook, payload) {
24
+ if (isServer(nuxtApp)) return false;
25
+ const runtime = runtimeFor(nuxtApp);
26
+ const seen = runtime.seen ??= /* @__PURE__ */ new Set();
27
+ if (seen.has(dedupKey)) return false;
28
+ seen.add(dedupKey);
29
+ emit(nuxtApp, hook, payload);
30
+ return true;
31
+ }
32
+ export function toAnalyticsItems(items, indexOffset) {
33
+ return items.map((data, i) => ({
34
+ key: String(data?.key ?? ""),
35
+ index: indexOffset + i,
36
+ data
37
+ }));
38
+ }
@@ -1,18 +1,11 @@
1
- /**
2
- * Block Query Factory
3
- *
4
- * Provides query key management and query factory functions for Frontic blocks.
5
- * Compatible with both @pinia/colada and useAsyncData patterns.
6
- */
7
- import type { FrontstackClient } from '@frontic/stack/generated-client';
8
- import type { Blocks, Responses } from '@frontic/stack/generated-types';
9
1
  import type { MaybeRef } from 'vue';
10
- import type { FronticRequestOptions } from '../types/listing.js';
11
- export interface FetchBlockConfig<TBlock extends string> extends FronticRequestOptions {
2
+ import type { FronticClient } from '../types/client.js';
3
+ import type { BlockName, ResponseOf } from '../types/registry.js';
4
+ import type { FronticRequestOptions, FronticQueryOptions } from '../types/listing.js';
5
+ export interface FetchBlockConfig<TBlock extends string> extends FronticRequestOptions, FronticQueryOptions {
12
6
  name: TBlock;
13
7
  key: MaybeRef<string>;
14
- staleTime?: number;
15
- _client?: FrontstackClient;
8
+ _client?: FronticClient;
16
9
  }
17
10
  /**
18
11
  * Query key factory for block queries
@@ -22,14 +15,17 @@ export interface FetchBlockConfig<TBlock extends string> extends FronticRequestO
22
15
  * ```ts
23
16
  * BLOCK_QUERY_KEYS.root // ['blocks']
24
17
  * BLOCK_QUERY_KEYS.block('ProductCard') // ['blocks', 'ProductCard']
25
- * BLOCK_QUERY_KEYS.detail('ProductCard', 'abc123', 'context-token')
26
- * // ['blocks', 'ProductCard', 'abc123', 'context-token']
18
+ * BLOCK_QUERY_KEYS.detail('ProductCard', 'abc123', 'context-token', 'shop.com')
19
+ * // ['blocks', 'ProductCard', 'abc123', { context: 'context-token', domain: 'shop.com' }]
27
20
  * ```
28
21
  */
29
22
  export declare const BLOCK_QUERY_KEYS: {
30
- root: string[];
31
- block: <TBlock extends string>(blockName: TBlock) => string[];
32
- detail: <TBlock extends string>(blockName: TBlock, key: string, contextKey?: string) => string[];
23
+ root: readonly ["blocks"];
24
+ block: <TBlock extends string>(blockName: TBlock) => readonly ["blocks", TBlock];
25
+ detail: <TBlock extends string>(blockName: TBlock, key: string, contextKey?: string, contextDomain?: string) => readonly ["blocks", TBlock, string, {
26
+ readonly context: string | null;
27
+ readonly domain: string | null;
28
+ }];
33
29
  };
34
30
  /**
35
31
  * Generic query factory for fetching blocks
@@ -41,21 +37,27 @@ export declare const BLOCK_QUERY_KEYS: {
41
37
  * const blockQuery = fetchBlockQuery({
42
38
  * name: 'ProductCard',
43
39
  * key: productId,
44
- * contextKey: token.value
40
+ * contextKey: token
45
41
  * })
46
42
  *
47
43
  * const { data, status } = useQuery(blockQuery)
48
44
  *
49
45
  * // With useAsyncData
50
46
  * const { data, status } = useAsyncData(
51
- * blockQuery.key().join('-'),
47
+ * createBlockCacheKey(blockQuery.key()),
52
48
  * blockQuery.query
53
49
  * )
54
50
  * ```
55
51
  */
56
- export declare function fetchBlockQuery<TBlock extends keyof Blocks>(config: FetchBlockConfig<TBlock>): {
57
- key: () => string[];
58
- query: () => Promise<Responses[TBlock]>;
52
+ export declare function fetchBlockQuery<TBlock extends BlockName>(config: FetchBlockConfig<TBlock>): {
53
+ placeholderData?: ((previousData: ResponseOf<TBlock> | undefined) => ResponseOf<TBlock> | undefined) | undefined;
54
+ enabled: () => boolean;
55
+ gcTime?: number | undefined;
56
+ key: () => readonly ["blocks", TBlock, string, {
57
+ readonly context: string | null;
58
+ readonly domain: string | null;
59
+ }];
60
+ query: () => Promise<ResponseOf<TBlock>>;
59
61
  staleTime: number;
60
62
  };
61
63
  /**
@@ -1,32 +1,32 @@
1
- function unwrapRef(ref) {
2
- return typeof ref === "object" && ref !== null && "value" in ref ? ref.value : ref;
3
- }
1
+ import { toValue } from "vue";
2
+ import { DEFAULT_STALE_TIME, requestContextSlot } from "../utils/query-keys.js";
4
3
  export const BLOCK_QUERY_KEYS = {
5
4
  root: ["blocks"],
6
5
  block: (blockName) => [...BLOCK_QUERY_KEYS.root, blockName],
7
- detail: (blockName, key, contextKey) => [...BLOCK_QUERY_KEYS.block(blockName), key, contextKey ?? "default"]
6
+ detail: (blockName, key, contextKey, contextDomain) => [...BLOCK_QUERY_KEYS.block(blockName), key, requestContextSlot(contextKey, contextDomain)]
8
7
  };
9
8
  export function fetchBlockQuery(config) {
10
9
  return {
11
- key: () => {
12
- const key = unwrapRef(config.key);
13
- const contextKey = unwrapRef(config.contextKey);
14
- return BLOCK_QUERY_KEYS.detail(config.name, key, contextKey);
15
- },
10
+ key: () => BLOCK_QUERY_KEYS.detail(config.name, toValue(config.key), toValue(config.contextKey), toValue(config.contextDomain)),
16
11
  query: async () => {
17
12
  let client = config._client;
18
13
  if (!client) {
19
14
  const { useFronticClient } = await import("./useFronticClient.js");
20
15
  client = useFronticClient();
21
16
  }
22
- const key = unwrapRef(config.key);
23
- const contextKey = unwrapRef(config.contextKey);
24
- const contextDomain = unwrapRef(config.contextDomain);
25
- const requestUrl = unwrapRef(config.requestUrl);
26
- return await client.block(config.name, key, { contextKey, contextDomain, requestUrl });
17
+ return await client.block(config.name, toValue(config.key), {
18
+ contextKey: toValue(config.contextKey),
19
+ contextDomain: toValue(config.contextDomain),
20
+ requestUrl: toValue(config.requestUrl)
21
+ });
27
22
  },
28
- staleTime: config.staleTime ?? 1e3 * 60 * 5
29
- // 5 minutes default
23
+ staleTime: config.staleTime ?? DEFAULT_STALE_TIME,
24
+ ...config.gcTime !== void 0 && { gcTime: config.gcTime },
25
+ // A block cannot be fetched without a key; the caller's `enabled` gates on top
26
+ enabled: () => !!toValue(config.key) && (toValue(config.enabled) ?? true),
27
+ // keepPreviousData: show the previous entry's data while a changed key
28
+ // (new context, new block key) loads; never written to the cache
29
+ ...config.keepPreviousData !== false && { placeholderData: (previousData) => previousData }
30
30
  };
31
31
  }
32
32
  export function createBlockCacheKey(keyArray) {
@@ -22,4 +22,4 @@ export type { UseFronticTreeOptions } from './useFronticTree.js';
22
22
  export { fetchTreeQuery, TREE_QUERY_KEYS, createTreeCacheKey } from './trees.js';
23
23
  export type { FetchTreeConfig } from './trees.js';
24
24
  export { useFronticContext } from './useFronticContext.js';
25
- export type { UseFronticContextOptions } from './useFronticContext.js';
25
+ export type { UseFronticContextOptions, FronticContext } from './useFronticContext.js';