@wpnuxt/core 2.0.0-alpha.2 → 2.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wpnuxt",
3
3
  "configKey": "wpNuxt",
4
- "version": "2.0.0-alpha.1",
4
+ "version": "2.0.0-alpha.3",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { defu } from 'defu';
2
- import { promises, cpSync, existsSync, statSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import { promises, cpSync, existsSync, statSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { mkdir, writeFile } from 'node:fs/promises';
3
4
  import { join } from 'node:path';
4
5
  import { useLogger, createResolver, resolveFiles, defineNuxtModule, addPlugin, addImports, addComponentsDir, addTemplate, addTypeTemplate, hasNuxtModule, installModule } from '@nuxt/kit';
5
6
  import { upperFirst } from 'scule';
@@ -64,16 +65,18 @@ const _parseDoc = async (doc) => {
64
65
  throw error;
65
66
  }
66
67
  };
67
- function processSelections(selections, level, query) {
68
+ function processSelections(selections, level, query, canExtract = true) {
68
69
  if (!selections || selections.length === 0) return;
69
- if (selections.length === 1 && selections[0]?.kind === "Field") {
70
- query.nodes?.push(selections[0].name.value.trim());
70
+ const firstSelection = selections[0];
71
+ const hasSingleField = selections.length === 1 && firstSelection?.kind === "Field";
72
+ if (hasSingleField && canExtract && firstSelection.kind === "Field") {
73
+ query.nodes?.push(firstSelection.name.value.trim());
71
74
  }
72
75
  selections.forEach((s) => {
73
76
  if (s.kind === "FragmentSpread") {
74
77
  query.fragments?.push(s.name.value.trim());
75
78
  } else if (s.selectionSet?.selections) {
76
- processSelections(s.selectionSet.selections, level + 1, query);
79
+ processSelections(s.selectionSet.selections, level + 1, query, canExtract && hasSingleField);
77
80
  }
78
81
  });
79
82
  }
@@ -110,13 +113,9 @@ async function prepareContext(ctx) {
110
113
  const fragmentSuffix = q.fragments?.length && q.nodes?.includes("nodes") ? "[]" : "";
111
114
  return q.fragments?.length ? q.fragments.map((f) => `${f}Fragment${fragmentSuffix}`).join(" | ") : "any";
112
115
  };
113
- const queryFnExp = (q, typed = false, lazy = false) => {
114
- const baseName = fnName(q.name);
115
- const functionName = lazy ? `useLazy${q.name}` : baseName;
116
+ const queryFnExp = (q, typed = false) => {
117
+ const functionName = fnName(q.name);
116
118
  if (!typed) {
117
- if (lazy) {
118
- return `export const ${functionName} = (params, options) => useWPContent('${q.name}', [${formatNodes(q.nodes)}], false, params, { ...options, lazy: true })`;
119
- }
120
119
  return `export const ${functionName} = (params, options) => useWPContent('${q.name}', [${formatNodes(q.nodes)}], false, params, options)`;
121
120
  }
122
121
  return ` export const ${functionName}: (params?: ${q.name}QueryVariables, options?: WPContentOptions) => WPContentResult<${getFragmentType(q)}>`;
@@ -131,8 +130,7 @@ async function prepareContext(ctx) {
131
130
  ctx.generateImports = () => {
132
131
  const imports = [];
133
132
  queries.forEach((f) => {
134
- imports.push(queryFnExp(f, false, false));
135
- imports.push(queryFnExp(f, false, true));
133
+ imports.push(queryFnExp(f, false));
136
134
  });
137
135
  mutations.forEach((m) => {
138
136
  imports.push(mutationFnExp(m, false));
@@ -192,8 +190,7 @@ async function prepareContext(ctx) {
192
190
  "declare module '#wpnuxt' {"
193
191
  ];
194
192
  queries.forEach((f) => {
195
- declarations.push(queryFnExp(f, true, false));
196
- declarations.push(queryFnExp(f, true, true));
193
+ declarations.push(queryFnExp(f, true));
197
194
  });
198
195
  mutations.forEach((m) => {
199
196
  declarations.push(mutationFnExp(m, true));
@@ -202,18 +199,14 @@ async function prepareContext(ctx) {
202
199
  return declarations.join("\n");
203
200
  };
204
201
  ctx.fnImports = [
205
- // Auto-import query composables (regular and lazy variants)
206
- ...queries.flatMap((fn) => [
207
- { from: "#wpnuxt", name: fnName(fn.name) },
208
- { from: "#wpnuxt", name: `useLazy${fn.name}` }
209
- ]),
202
+ // Auto-import query composables
203
+ ...queries.map((fn) => ({ from: "#wpnuxt", name: fnName(fn.name) })),
210
204
  // Auto-import mutation composables
211
205
  ...mutations.map((m) => ({ from: "#wpnuxt", name: mutationFnName(m.name) }))
212
206
  ];
213
207
  logger.debug("generated WPNuxt composables: ");
214
208
  queries.forEach((f) => {
215
209
  logger.debug(` ${fnName(f.name)}()`);
216
- logger.debug(` useLazy${f.name}()`);
217
210
  });
218
211
  mutations.forEach((m) => {
219
212
  logger.debug(` ${mutationFnName(m.name)}()`);
@@ -409,8 +402,8 @@ const module$1 = defineNuxtModule({
409
402
  addPlugin(resolver.resolve("./runtime/plugins/graphqlConfig"));
410
403
  addPlugin(resolver.resolve("./runtime/plugins/graphqlErrors"));
411
404
  const mergedQueriesFolder = await mergeQueries(nuxt, wpNuxtConfig, resolver);
412
- setupServerOptions(nuxt, resolver, logger);
413
- setupClientOptions(nuxt, resolver, logger);
405
+ await setupServerOptions(nuxt, resolver, logger);
406
+ await setupClientOptions(nuxt, resolver, logger);
414
407
  if (wpNuxtConfig.downloadSchema) {
415
408
  const schemaPath = join(nuxt.options.rootDir, "schema.graphql");
416
409
  logger.debug(`Validating WordPress endpoint: ${wpNuxtConfig.wordpressUrl}${wpNuxtConfig.graphqlEndpoint}`);
@@ -443,7 +436,9 @@ const module$1 = defineNuxtModule({
443
436
  configureVercelSettings(nuxt, logger);
444
437
  addImports([
445
438
  { name: "useWPContent", as: "useWPContent", from: resolver.resolve("./runtime/composables/useWPContent") },
446
- { name: "useAsyncWPContent", as: "useAsyncWPContent", from: resolver.resolve("./runtime/composables/useWPContent") }
439
+ { name: "useAsyncWPContent", as: "useAsyncWPContent", from: resolver.resolve("./runtime/composables/useWPContent") },
440
+ { name: "getRelativeImagePath", as: "getRelativeImagePath", from: resolver.resolve("./runtime/util/images") },
441
+ { name: "usePrevNextPost", as: "usePrevNextPost", from: resolver.resolve("./runtime/composables/usePrevNextPost") }
447
442
  // Note: useGraphqlMutation is auto-imported via nuxt-graphql-middleware with includeComposables: true
448
443
  ]);
449
444
  addComponentsDir({
@@ -558,7 +553,7 @@ export default defineGraphqlServerOptions({
558
553
  }
559
554
  })
560
555
  `;
561
- function setupServerOptions(nuxt, _resolver, logger) {
556
+ async function setupServerOptions(nuxt, _resolver, logger) {
562
557
  const serverDir = nuxt.options.serverDir;
563
558
  const targetPath = join(serverDir, "graphqlMiddleware.serverOptions.ts");
564
559
  if (existsSync(targetPath)) {
@@ -566,9 +561,9 @@ function setupServerOptions(nuxt, _resolver, logger) {
566
561
  return;
567
562
  }
568
563
  if (!existsSync(serverDir)) {
569
- mkdirSync(serverDir, { recursive: true });
564
+ await mkdir(serverDir, { recursive: true });
570
565
  }
571
- writeFileSync(targetPath, SERVER_OPTIONS_TEMPLATE);
566
+ await writeFile(targetPath, SERVER_OPTIONS_TEMPLATE);
572
567
  logger.debug("Created graphqlMiddleware.serverOptions.ts with WPNuxt defaults (cookie/auth forwarding)");
573
568
  }
574
569
  const CLIENT_OPTIONS_TEMPLATE = `import { defineGraphqlClientOptions } from '@wpnuxt/core/client-options'
@@ -600,7 +595,7 @@ export default defineGraphqlClientOptions<{
600
595
  }
601
596
  })
602
597
  `;
603
- function setupClientOptions(nuxt, _resolver, logger) {
598
+ async function setupClientOptions(nuxt, _resolver, logger) {
604
599
  const appDir = nuxt.options.dir.app;
605
600
  const targetPath = join(appDir, "graphqlMiddleware.clientOptions.ts");
606
601
  if (existsSync(targetPath)) {
@@ -608,9 +603,9 @@ function setupClientOptions(nuxt, _resolver, logger) {
608
603
  return;
609
604
  }
610
605
  if (!existsSync(appDir)) {
611
- mkdirSync(appDir, { recursive: true });
606
+ await mkdir(appDir, { recursive: true });
612
607
  }
613
- writeFileSync(targetPath, CLIENT_OPTIONS_TEMPLATE);
608
+ await writeFile(targetPath, CLIENT_OPTIONS_TEMPLATE);
614
609
  logger.debug("Created graphqlMiddleware.clientOptions.ts with WPNuxt defaults (preview mode support)");
615
610
  }
616
611
  function configureVercelSettings(nuxt, logger) {
File without changes
@@ -0,0 +1,22 @@
1
+ import { useWPContent } from "./useWPContent.js";
2
+ export async function usePrevNextPost(currentSlug) {
3
+ const { data, execute } = useWPContent("Posts", ["posts", "nodes"], false, { limit: 100 });
4
+ await execute();
5
+ const allPosts = data.value || [];
6
+ if (!allPosts.length) {
7
+ return { prev: null, next: null };
8
+ }
9
+ const cleanSlug = currentSlug.replace(/^\/|\/$/g, "");
10
+ const currentIndex = allPosts.findIndex(
11
+ (post) => post.slug === cleanSlug
12
+ );
13
+ if (currentIndex === -1) {
14
+ return { prev: null, next: null };
15
+ }
16
+ const prevPost = currentIndex < allPosts.length - 1 ? allPosts[currentIndex + 1] : null;
17
+ const nextPost = currentIndex > 0 ? allPosts[currentIndex - 1] : null;
18
+ return {
19
+ prev: prevPost ?? null,
20
+ next: nextPost ?? null
21
+ };
22
+ }
@@ -1,10 +1,32 @@
1
1
  import { getRelativeImagePath } from "../util/images.js";
2
2
  import { computed, useAsyncGraphqlQuery } from "#imports";
3
+ function defaultGetCachedData(key, nuxtApp, ctx) {
4
+ if (nuxtApp.isHydrating) {
5
+ return nuxtApp.payload.data[key];
6
+ }
7
+ if (ctx.cause === "refresh:manual" || ctx.cause === "refresh:hook") {
8
+ return void 0;
9
+ }
10
+ return nuxtApp.payload.data[key] ?? nuxtApp.static.data[key];
11
+ }
3
12
  export const useWPContent = (queryName, nodes, fixImagePaths, params, options) => {
13
+ const { clientCache, cacheKey, getCachedData: userGetCachedData, ...restOptions } = options ?? {};
14
+ const graphqlCaching = clientCache === false ? { client: false } : restOptions.graphqlCaching ?? { client: true };
15
+ const paramsKey = params ? JSON.stringify(params) : "{}";
16
+ const baseKey = `wpnuxt-${String(queryName)}-${paramsKey}`;
17
+ const finalKey = cacheKey ? `${baseKey}-${cacheKey}` : baseKey;
18
+ const effectiveGetCachedData = userGetCachedData ?? (clientCache === false ? () => void 0 : defaultGetCachedData);
19
+ const mergedOptions = {
20
+ ...restOptions,
21
+ graphqlCaching,
22
+ // Explicit key ensures consistent cache lookups
23
+ key: finalKey,
24
+ getCachedData: effectiveGetCachedData
25
+ };
4
26
  const { data, pending, refresh, execute, clear, error, status } = useAsyncGraphqlQuery(
5
27
  queryName,
6
28
  params ?? {},
7
- options
29
+ mergedOptions
8
30
  );
9
31
  const transformedData = computed(() => {
10
32
  const queryResult = data.value && typeof data.value === "object" && data.value !== null && "data" in data.value ? data.value.data : void 0;
@@ -1,6 +1,5 @@
1
- import { defineNuxtPlugin } from "nuxt/app";
2
- import { useGraphqlState, useRuntimeConfig } from "#imports";
3
- export default defineNuxtPlugin((_NuxtApp) => {
1
+ import { defineNuxtPlugin, useGraphqlState, useRuntimeConfig } from "#imports";
2
+ export default defineNuxtPlugin(() => {
4
3
  const state = useGraphqlState();
5
4
  if (!state) {
6
5
  return;
@@ -1,4 +1,4 @@
1
- import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
1
+ import { defineNuxtPlugin, useNuxtApp } from "#imports";
2
2
  export default defineNuxtPlugin(() => {
3
3
  const nuxtApp = useNuxtApp();
4
4
  nuxtApp.hook("nuxt-graphql-middleware:errors", (errors) => {
@@ -8,8 +8,10 @@
8
8
 
9
9
  // Stub for #imports
10
10
  export const computed: any
11
+ export const defineNuxtPlugin: any
11
12
  export const useAsyncGraphqlQuery: any
12
13
  export const useGraphqlState: any
14
+ export const useNuxtApp: any
13
15
  export const useRuntimeConfig: any
14
16
  export const useRoute: any
15
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wpnuxt/core",
3
- "version": "2.0.0-alpha.2",
3
+ "version": "2.0.0-alpha.4",
4
4
  "description": "Nuxt module for WordPress integration via GraphQL (WPGraphQL)",
5
5
  "keywords": [
6
6
  "nuxt",