nuxt-kirby 4.2.0 → 5.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 (35) hide show
  1. package/README.md +4 -4
  2. package/dist/module.d.mts +49 -41
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +159 -136
  5. package/dist/runtime/composables/$kirby.d.ts +7 -32
  6. package/dist/runtime/composables/$kirby.js +48 -61
  7. package/dist/runtime/composables/$kql.d.ts +1 -28
  8. package/dist/runtime/composables/$kql.js +7 -48
  9. package/dist/runtime/composables/useKirbyData.d.ts +31 -20
  10. package/dist/runtime/composables/useKirbyData.js +19 -30
  11. package/dist/runtime/composables/useKql.d.ts +5 -23
  12. package/dist/runtime/composables/useKql.js +10 -26
  13. package/dist/runtime/server/cache.d.ts +2 -0
  14. package/dist/runtime/server/cache.js +77 -0
  15. package/dist/runtime/server/imports.d.ts +3 -21
  16. package/dist/runtime/server/imports.js +11 -20
  17. package/dist/runtime/server/path.d.ts +9 -0
  18. package/dist/runtime/server/path.js +56 -0
  19. package/dist/runtime/server/proxy.d.ts +20 -0
  20. package/dist/runtime/server/proxy.js +118 -0
  21. package/dist/runtime/server/stream.d.ts +5 -0
  22. package/dist/runtime/server/stream.js +20 -0
  23. package/dist/runtime/types.d.ts +50 -15
  24. package/dist/runtime/types.js +1 -0
  25. package/dist/runtime/utils.d.ts +5 -16
  26. package/dist/runtime/utils.js +10 -15
  27. package/package.json +5 -4
  28. package/dist/runtime/cache.d.ts +0 -11
  29. package/dist/runtime/cache.js +0 -25
  30. package/dist/runtime/kirby-types.d.ts +0 -1
  31. package/dist/runtime/kirby-types.js +0 -0
  32. package/dist/runtime/path.d.ts +0 -6
  33. package/dist/runtime/path.js +0 -10
  34. package/dist/runtime/server/handler.d.ts +0 -2
  35. package/dist/runtime/server/handler.js +0 -179
package/README.md CHANGED
@@ -19,7 +19,7 @@
19
19
 
20
20
  ## Setup
21
21
 
22
- Add the module to a project on Nuxt 4 or later:
22
+ Add the module to a project on Nuxt 4.6 or a later Nuxt 4 release:
23
23
 
24
24
  ```bash
25
25
  npx nuxt module add kirby
@@ -30,9 +30,9 @@ npx nuxt module add kirby
30
30
  Set your Kirby credentials in `.env`. This example uses basic authentication with the [KQL plugin](https://github.com/getkirby/kql); [Getting Started](https://nuxt-kirby.byjohann.dev/essentials/getting-started) sets up token authentication instead:
31
31
 
32
32
  ```ini
33
- KIRBY_BASE_URL=https://kirby.example.com
34
- KIRBY_API_USERNAME=your-username
35
- KIRBY_API_PASSWORD=your-password
33
+ NUXT_KIRBY_URL=https://kirby.example.com
34
+ NUXT_KIRBY_CREDENTIALS_USERNAME=your-username
35
+ NUXT_KIRBY_CREDENTIALS_PASSWORD=your-password
36
36
  ```
37
37
 
38
38
  And send queries in your template:
package/dist/module.d.mts CHANGED
@@ -1,82 +1,96 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
- import { KirbyQueryRequest } from 'kirby-types';
2
+ import { ServerKirbyConfig, PublicKirbyConfig, KirbyAuth, BasicCredentials, AllowedRoute } from '../dist/runtime/types.js';
3
3
 
4
4
  interface ModuleOptions {
5
5
  /**
6
- * Kirby base URL, like `https://kirby.example.com`.
6
+ * URL of the Kirby instance, like `https://kirby.example.com`.
7
7
  *
8
- * @default process.env.KIRBY_BASE_URL
8
+ * @remarks
9
+ * `NUXT_KIRBY_URL` overrides it at runtime, in client mode `NUXT_PUBLIC_KIRBY_URL`.
10
+ *
11
+ * @default process.env.NUXT_KIRBY_URL
9
12
  */
10
13
  url?: string;
11
14
  /**
12
- * Kirby KQL API endpoint path.
15
+ * Path of the KQL endpoint below the Kirby URL.
16
+ *
17
+ * @remarks
18
+ * The default allowed routes and the composables take it from the build, so a
19
+ * `NUXT_KIRBY_KQL_PATH` set at runtime splits the paths.
13
20
  *
14
21
  * @default 'api/kql' for `bearer` authentication, 'api/query' otherwise
15
22
  */
16
23
  kqlPath?: string;
17
24
  /**
18
- * Kirby API authentication method.
25
+ * How requests authenticate with the Kirby instance.
26
+ *
27
+ * @remarks
28
+ * The default `kqlPath` follows it at build time, so a `NUXT_KIRBY_AUTH` set at runtime leaves
29
+ * KQL queries on the build's path.
19
30
  *
20
31
  * @default 'basic'
21
32
  */
22
- auth?: 'basic' | 'bearer' | 'none';
33
+ auth?: KirbyAuth;
23
34
  /**
24
35
  * Token for bearer authentication.
25
36
  *
26
- * @default process.env.KIRBY_API_TOKEN
37
+ * @remarks
38
+ * `NUXT_KIRBY_TOKEN` overrides it at runtime, in client mode `NUXT_PUBLIC_KIRBY_TOKEN`.
39
+ *
40
+ * @default process.env.NUXT_KIRBY_TOKEN
27
41
  */
28
42
  token?: string;
29
43
  /**
30
- * Username/password pair for basic authentication.
44
+ * Username and password for basic authentication.
45
+ *
46
+ * @remarks
47
+ * `NUXT_KIRBY_CREDENTIALS_USERNAME` and `NUXT_KIRBY_CREDENTIALS_PASSWORD` override them at
48
+ * runtime, in client mode `NUXT_PUBLIC_KIRBY_CREDENTIALS_USERNAME` and
49
+ * `NUXT_PUBLIC_KIRBY_CREDENTIALS_PASSWORD`.
31
50
  *
32
- * @default { username: process.env.KIRBY_API_USERNAME, password: process.env.KIRBY_API_PASSWORD }
51
+ * @default { username: process.env.NUXT_KIRBY_CREDENTIALS_USERNAME, password: process.env.NUXT_KIRBY_CREDENTIALS_PASSWORD }
33
52
  */
34
- credentials?: {
35
- username: string;
36
- password: string;
37
- };
53
+ credentials?: BasicCredentials;
38
54
  /**
39
- * Send queries straight from the browser instead of through the server-side proxy.
55
+ * Whether every request goes straight to Kirby, from the browser and during SSR, instead of
56
+ * through the server proxy.
40
57
  *
41
58
  * @remarks
42
- * Leaving this off is what keeps your token out of the client bundle. Turn it on only for an
59
+ * Client mode publishes the Kirby URL and credentials to the browser. Turn it on only for an
43
60
  * instance whose credentials may be public, or one that needs none.
44
61
  *
45
62
  * An explicit `false` holds even with SSR disabled; the default flips there because a
46
63
  * client-rendered app often has no server to proxy through.
47
64
  *
48
- * @default false, or true if Nuxt SSR is disabled
65
+ * @default false, or true if Nuxt SSR is disabled and neither `forwardCookies`, `allowedRoutes` nor `server.cache` is set
49
66
  */
50
67
  client?: boolean;
51
68
  /**
52
- * Forward the visitor's cookies to Kirby.
69
+ * Whether the server proxy forwards the visitor's cookie to Kirby and, on a request the browser
70
+ * sends, Kirby's cookies back to the visitor.
53
71
  *
54
72
  * @remarks
55
73
  * A Kirby session lives in a cookie, so without this a logged-in visitor still receives the
56
- * logged-out response. Turning it on skips the server-side cache, whether or not the visitor
57
- * actually sent a cookie – one stored response is shared between all visitors.
58
- *
59
- * Individual calls override this through the `forwardCookies` option of `useKql`, `useKirbyData`,
60
- * `$kql` and `$kirby`.
74
+ * logged-out response. Turning it on turns the server cache off – one stored response is shared
75
+ * between all visitors – and makes the server proxy refuse requests the browser marks
76
+ * cross-site.
61
77
  *
62
78
  * @default false
63
79
  */
64
80
  forwardCookies?: boolean;
65
81
  /**
66
- * Prefetch custom KQL queries at build-time.
82
+ * Routes the server proxy may forward. It refuses every request that matches none.
67
83
  *
68
84
  * @remarks
69
- * The queries will be fully typed and importable from `#nuxt-kirby`.
85
+ * A list of your own replaces the default, so it has to name the KQL path for KQL queries to
86
+ * pass.
70
87
  *
71
- * @default {}
88
+ * @default [{ path: '**', methods: ['GET', 'HEAD'] }, { path: kqlPath, methods: ['POST'] }]
72
89
  */
73
- prefetch?: Record<string, KirbyQueryRequest | {
74
- query: KirbyQueryRequest;
75
- language: string;
76
- }>;
90
+ allowedRoutes?: AllowedRoute[];
77
91
  server?: {
78
92
  /**
79
- * Enable server-side caching of queries using the Nitro cache API.
93
+ * Whether KQL queries and `GET` requests are answered from the server cache.
80
94
  *
81
95
  * @see https://v2.nitro.build/guide/cache
82
96
  */
@@ -96,26 +110,20 @@ interface ModuleOptions {
96
110
  */
97
111
  swr?: boolean;
98
112
  /**
99
- * Number of seconds to cache the query response.
113
+ * Number of seconds a response stays in the server cache.
100
114
  *
101
115
  * @see https://v2.nitro.build/guide/cache#options
102
116
  * @default 1
103
117
  */
104
118
  maxAge?: number;
105
- /**
106
- * Log verbose errors to the console if a query fails.
107
- *
108
- * @remarks
109
- * This will log the full query to the console. Depending on the content of the query, this could be a security risk.
110
- *
111
- * @default false
112
- */
113
- verboseErrors?: boolean;
114
119
  };
115
120
  }
116
121
  declare module '@nuxt/schema' {
117
122
  interface RuntimeConfig {
118
- kirby: ModuleOptions;
123
+ kirby: ServerKirbyConfig;
124
+ }
125
+ interface PublicRuntimeConfig {
126
+ kirby: PublicKirbyConfig;
119
127
  }
120
128
  }
121
129
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
package/dist/module.json CHANGED
@@ -2,9 +2,9 @@
2
2
  "name": "nuxt-kirby",
3
3
  "configKey": "kirby",
4
4
  "compatibility": {
5
- "nuxt": ">=4.0.0"
5
+ "nuxt": ">=4.6.0 <5"
6
6
  },
7
- "version": "4.2.0",
7
+ "version": "5.0.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.4",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -1,64 +1,75 @@
1
1
  import process from 'node:process';
2
- import { useLogger, defineNuxtModule, createResolver, addServerHandler, addImports, addTemplate } from '@nuxt/kit';
2
+ import { useLogger, defineNuxtModule, createResolver, addServerHandler, addImports, addServerImports, addTemplate } from '@nuxt/kit';
3
3
  import { defu } from 'defu';
4
4
  import { join, relative } from 'pathe';
5
- import { pascalCase } from 'scule';
6
- import { withLeadingSlash } from 'ufo';
7
- import { ofetch } from 'ofetch';
8
- import { createAuthHeader, createLanguageHeader } from '../dist/runtime/utils.js';
5
+ import { withLeadingSlash, joinURL } from 'ufo';
6
+ import { AUTH_METHODS } from '../dist/runtime/types.js';
9
7
 
10
8
  const name = "nuxt-kirby";
11
9
 
12
10
  const logger = useLogger("nuxt-kirby");
13
11
 
14
- async function prefetchQueries(options) {
15
- const results = /* @__PURE__ */ new Map();
16
- if (!options.prefetch || Object.keys(options.prefetch).length === 0)
17
- return results;
18
- if (!options.url) {
19
- logger.error("Skipping KQL prefetch, since no Kirby base URL is provided");
20
- return results;
12
+ const REMOVED_OPTIONS = {
13
+ prefetch: "Fetch the query in a nuxt-prepare script instead."
14
+ };
15
+ const REMOVED_SERVER_OPTIONS = {
16
+ verboseErrors: "The server proxy passes Kirby's answer to a failed request on as it is, and no longer logs the request."
17
+ };
18
+ const RENAMED_VARIABLES = [
19
+ [
20
+ "KIRBY_BASE_URL",
21
+ "NUXT_KIRBY_URL",
22
+ (options) => Boolean(options.url)
23
+ ],
24
+ [
25
+ "KIRBY_API_TOKEN",
26
+ "NUXT_KIRBY_TOKEN",
27
+ (options) => Boolean(options.token)
28
+ ],
29
+ [
30
+ "KIRBY_API_USERNAME",
31
+ "NUXT_KIRBY_CREDENTIALS_USERNAME",
32
+ (options) => Boolean(options.credentials?.username)
33
+ ],
34
+ [
35
+ "KIRBY_API_PASSWORD",
36
+ "NUXT_KIRBY_CREDENTIALS_PASSWORD",
37
+ (options) => Boolean(options.credentials?.password)
38
+ ]
39
+ ];
40
+ const MIGRATION_GUIDE_URL = "https://nuxt-kirby.byjohann.dev/advanced/migration";
41
+ function assertValidOptions(input, env) {
42
+ const options = input;
43
+ const optionErrors = [];
44
+ for (const [key, replacement] of Object.entries(REMOVED_OPTIONS)) {
45
+ if (options[key] !== void 0)
46
+ optionErrors.push(`The \`${key}\` option was removed. ${replacement}`);
21
47
  }
22
- for (const key of Object.keys(options.prefetch)) {
23
- if (key === pascalCase(key)) {
24
- logger.error(`Prefetch query key "${key}" conflicts with its PascalCase type name. Please use a different key (e.g., "${key.charAt(0).toLowerCase() + key.slice(1)}")`);
25
- }
48
+ for (const [key, replacement] of Object.entries(REMOVED_SERVER_OPTIONS)) {
49
+ if (options.server?.[key] !== void 0)
50
+ optionErrors.push(`The \`server.${key}\` option was removed. ${replacement}`);
26
51
  }
27
- const start = Date.now();
28
- for (const [key, query] of Object.entries(options.prefetch)) {
29
- const language = "language" in query ? query.language : void 0;
30
- if (language && !query.query) {
31
- logger.error(`Prefetch KQL query "${key}" requires the "query" property in multi-language mode`);
32
- continue;
33
- }
34
- try {
35
- results.set(
36
- key,
37
- await ofetch(options.kqlPath, {
38
- baseURL: options.url,
39
- method: "POST",
40
- body: language ? query.query : query,
41
- headers: {
42
- ...createLanguageHeader(language),
43
- ...createAuthHeader(options)
44
- }
45
- })
46
- );
47
- } catch (error) {
48
- const _error = error;
49
- logger.error(
50
- `Prefetch KQL query "${key}" failed${_error.status ? ` with status code ${_error.status}:
51
- ${JSON.stringify(_error.data, void 0, 2)}` : `: ${_error}`}`
52
- );
53
- }
52
+ for (const [oldName, newName, hasValue] of RENAMED_VARIABLES) {
53
+ if (env[oldName] && !env[newName] && !hasValue(options))
54
+ optionErrors.push(`The \`${oldName}\` environment variable is no longer read. Rename it to \`${newName}\`.`);
54
55
  }
55
- if (results.size > 0) {
56
- const firstKey = results.keys().next().value;
57
- logger.info(
58
- `Prefetched ${results.size === 1 ? "" : `${results.size} `}KQL ${results.size === 1 ? `query "${firstKey}"` : "queries"} in ${Date.now() - start}ms`
59
- );
56
+ if (!AUTH_METHODS.includes(options.auth))
57
+ optionErrors.push(`The \`auth\` option is \`${JSON.stringify(options.auth)}\`. Set it to ${new Intl.ListFormat("en", { type: "disjunction" }).format(AUTH_METHODS.map((method) => `\`${method}\``))}.`);
58
+ if (options.client === true) {
59
+ if (options.forwardCookies)
60
+ optionErrors.push("Both `client` and `forwardCookies` are set. Client mode skips the server proxy, so there is no visitor cookie to forward. Pass `credentials: 'include'` to a request for the browser to send its own cookie for the Kirby URL.");
61
+ if (options.allowedRoutes)
62
+ optionErrors.push("Both `client` and `allowedRoutes` are set. Client mode publishes the Kirby credentials and skips the server proxy, so the allowed routes protect nothing.");
63
+ if (options.server?.cache)
64
+ optionErrors.push("Both `client` and `server.cache` are set. Client mode skips the server proxy, so no response reaches the server cache.");
65
+ }
66
+ if (optionErrors.length) {
67
+ throw new Error([
68
+ "Invalid Nuxt Kirby options:",
69
+ ...optionErrors.map((optionError) => `- ${optionError}`),
70
+ `See the migration guide: ${MIGRATION_GUIDE_URL}`
71
+ ].join("\n"));
60
72
  }
61
- return results;
62
73
  }
63
74
 
64
75
  const module$1 = defineNuxtModule({
@@ -66,127 +77,139 @@ const module$1 = defineNuxtModule({
66
77
  name,
67
78
  configKey: "kirby",
68
79
  compatibility: {
69
- nuxt: ">=4.0.0"
80
+ // The server proxy is written for Nitro 2, which Nuxt 5 replaces.
81
+ nuxt: ">=4.6.0 <5"
70
82
  }
71
83
  },
72
- defaults: {
73
- url: process.env.KIRBY_BASE_URL || "",
84
+ // Nuxt applies a `NUXT_KIRBY_*` variable to the runtime config only once the server runs. Read here
85
+ // as well, a variable set for the build alone reaches a server that is deployed without it.
86
+ defaults: () => ({
87
+ url: process.env.NUXT_KIRBY_URL || "",
74
88
  kqlPath: "",
75
89
  auth: "basic",
76
- token: process.env.KIRBY_API_TOKEN || "",
90
+ token: process.env.NUXT_KIRBY_TOKEN || "",
77
91
  credentials: {
78
- username: process.env.KIRBY_API_USERNAME || "",
79
- password: process.env.KIRBY_API_PASSWORD || ""
92
+ username: process.env.NUXT_KIRBY_CREDENTIALS_USERNAME || "",
93
+ password: process.env.NUXT_KIRBY_CREDENTIALS_PASSWORD || ""
80
94
  },
81
95
  // Left unset, so that an explicit `false` survives `ssr: false`.
82
96
  client: void 0,
83
97
  forwardCookies: false,
84
- prefetch: {},
98
+ // Left unset, because `defu` would join a list of the app's own with a default one.
99
+ allowedRoutes: void 0,
85
100
  server: {
86
101
  cache: false,
87
102
  storage: "cache",
88
103
  swr: false,
89
- maxAge: 1,
90
- verboseErrors: false
104
+ maxAge: 1
91
105
  }
92
- },
93
- async setup(options, nuxt) {
106
+ }),
107
+ setup(moduleOptions, nuxt) {
94
108
  const moduleName = name;
95
- if (!options.url)
96
- logger.error("Missing `KIRBY_BASE_URL` environment variable");
97
- if (options.auth === "basic" && (!options.credentials || !options.credentials.username || !options.credentials.password))
98
- logger.error("Missing `KIRBY_API_USERNAME` and `KIRBY_API_PASSWORD` environment variable for basic authentication");
99
- if (options.auth === "bearer" && !options.token)
100
- logger.error("Missing `KIRBY_API_TOKEN` environment variable for bearer authentication");
101
- options.kqlPath ||= options.auth === "bearer" ? "api/kql" : "api/query";
102
- if (options.client == null) {
103
- options.client = !nuxt.options.ssr;
104
- if (options.client)
105
- logger.info("Kirby requests are client-only because SSR is disabled. Set `client: false` to keep them on the server proxy.");
106
- }
107
- if (options.server) {
108
- options.server.storage ||= "cache";
109
- options.server.storage = withLeadingSlash(options.server.storage);
110
- }
111
- const { prefetch, ...runtimeOptions } = options;
112
- nuxt.options.runtimeConfig.kirby = defu(
113
- nuxt.options.runtimeConfig.kirby,
114
- runtimeOptions
115
- );
116
- const publicOptions = options.client ? {
109
+ const runtimeOptions = nuxt.options.runtimeConfig.kirby;
110
+ const options = {
111
+ ...defu(runtimeOptions, moduleOptions),
112
+ // `defu` would join the two lists.
113
+ allowedRoutes: runtimeOptions?.allowedRoutes ?? moduleOptions.allowedRoutes
114
+ };
115
+ assertValidOptions(options, process.env);
116
+ const kqlPath = options.kqlPath || (options.auth === "bearer" ? "api/kql" : "api/query");
117
+ const isDefaultClient = options.client == null && !nuxt.options.ssr && !options.forwardCookies && !options.allowedRoutes && !options.server?.cache;
118
+ if (isDefaultClient)
119
+ logger.info("Sending requests straight to Kirby because SSR is disabled. Set `client: false` to keep them on the server proxy.");
120
+ const client = options.client ?? isDefaultClient;
121
+ if (options.forwardCookies && options.server?.cache)
122
+ logger.warn("Both `forwardCookies` and `server.cache` are set. Cookie forwarding turns the server cache off, because one stored response is shared between all visitors.");
123
+ const serverConfig = {
117
124
  url: options.url,
118
- kqlPath: options.kqlPath,
125
+ kqlPath,
119
126
  auth: options.auth,
120
- ...options.auth === "bearer" && { token: options.token },
121
- ...options.auth === "basic" && { credentials: options.credentials },
122
- client: true,
123
- forwardCookies: options.forwardCookies
124
- } : { client: false };
127
+ token: options.token,
128
+ credentials: options.credentials,
129
+ forwardCookies: options.forwardCookies,
130
+ allowedRoutes: options.allowedRoutes ?? [
131
+ {
132
+ path: "**",
133
+ methods: ["GET", "HEAD"]
134
+ },
135
+ {
136
+ path: kqlPath,
137
+ methods: ["POST"]
138
+ }
139
+ ],
140
+ server: {
141
+ cache: options.server.cache,
142
+ // The Nitro storage mountpoint requires a leading slash.
143
+ storage: withLeadingSlash(options.server.storage || "cache"),
144
+ swr: options.server.swr,
145
+ maxAge: options.server.maxAge
146
+ }
147
+ };
148
+ nuxt.options.runtimeConfig.kirby = serverConfig;
149
+ const publicConfig = client ? {
150
+ client,
151
+ kqlPath,
152
+ url: serverConfig.url,
153
+ auth: serverConfig.auth,
154
+ ...serverConfig.auth === "bearer" && { token: serverConfig.token },
155
+ ...serverConfig.auth === "basic" && { credentials: serverConfig.credentials }
156
+ } : { client, kqlPath };
125
157
  nuxt.options.runtimeConfig.public.kirby = defu(
126
158
  nuxt.options.runtimeConfig.public.kirby,
127
- publicOptions
159
+ publicConfig
128
160
  );
129
161
  const { resolve } = createResolver(import.meta.url);
130
162
  nuxt.options.build.transpile.push(resolve("runtime"));
163
+ const proxyRoute = joinURL(nuxt.options.nitro.apiBaseURL || "/api", "__kirby__");
131
164
  addServerHandler({
132
- route: "/api/__kirby__/:key",
133
- handler: resolve("runtime/server/handler"),
134
- method: "post"
165
+ route: joinURL(proxyRoute, "**:path"),
166
+ handler: resolve("runtime/server/cache")
135
167
  });
136
- addImports(
137
- [
138
- "$kirby",
139
- "$kql",
140
- "useKirbyData",
141
- "useKql"
142
- ].map((name2) => ({
168
+ const composables = [
169
+ "$kirby",
170
+ "$kql",
171
+ "useKirbyData",
172
+ "useKql"
173
+ ];
174
+ addImports(composables.map((name2) => ({
175
+ name: name2,
176
+ from: resolve(`runtime/composables/${name2}`)
177
+ })));
178
+ nuxt.options.optimization.keyedComposables.push(
179
+ ...["useKirbyData", "useKql"].map((name2) => ({
143
180
  name: name2,
144
- from: resolve(`runtime/composables/${name2}`)
181
+ argumentLength: 3,
182
+ source: resolve(`runtime/composables/${name2}`)
145
183
  }))
146
184
  );
147
- nuxt.hooks.hook("nitro:config", (config) => {
148
- config.imports = defu(config.imports, {
149
- presets: [
150
- {
151
- from: resolve("runtime/server/imports"),
152
- imports: ["$kirby", "$kql"]
153
- }
154
- ]
155
- });
185
+ addServerImports(["$kirby", "$kql"].map((name2) => ({
186
+ name: name2,
187
+ from: resolve("runtime/server/imports")
188
+ })));
189
+ addTemplate({
190
+ filename: `module/${moduleName}.config.mjs`,
191
+ getContents: () => `
192
+ export const proxyRoute = ${JSON.stringify(proxyRoute)}
193
+ `.trimStart()
156
194
  });
157
- nuxt.options.alias[`#${moduleName}`] = join(nuxt.options.buildDir, `module/${moduleName}`);
158
- const prefetchedQueries = await prefetchQueries(options);
159
195
  addTemplate({
160
- filename: `module/${moduleName}.mjs`,
161
- write: true,
162
- getContents() {
163
- return `
164
- // Generated by ${moduleName}
165
- ${[
166
- ...prefetchedQueries.entries()
167
- ].map(([key, response]) => `
168
- export const ${key} = ${JSON.stringify(response?.result || null, void 0, 2)}
169
- `.trimStart()).join("") || `export {}
170
- `}`.trimStart();
171
- }
196
+ filename: `module/${moduleName}.config.d.ts`,
197
+ getContents: () => `
198
+ export declare const proxyRoute: string
199
+ `.trimStart()
172
200
  });
173
- const kirbyTypesPath = relative(join(nuxt.options.buildDir, "module"), resolve("runtime/kirby-types"));
201
+ nuxt.options.alias[`#${moduleName}`] = join(nuxt.options.buildDir, `module/${moduleName}`);
202
+ const importSpecifierFor = (path) => JSON.stringify(relative(join(nuxt.options.buildDir, "module"), resolve(path)));
174
203
  addTemplate({
175
204
  filename: `module/${moduleName}.d.ts`,
176
205
  write: true,
177
- getContents() {
178
- return `
206
+ getContents: () => `
179
207
  // Generated by ${moduleName}
180
- export type * from ${JSON.stringify(kirbyTypesPath)}
181
-
182
- ${[
183
- ...prefetchedQueries.entries()
184
- ].map(([key, response]) => `
185
- export declare const ${key}: ${JSON.stringify(response?.result || null, void 0, 2)}
186
- export type ${pascalCase(key)} = typeof ${key}
187
- `.trimStart()).join("") || `export {}
188
- `}`.trimStart();
189
- }
208
+ export type { AllowedRoute, KirbyFetchOptions, KqlOptions } from ${importSpecifierFor("runtime/types")}
209
+ export type { UseKirbyDataOptions } from ${importSpecifierFor("runtime/composables/useKirbyData")}
210
+ export type { UseKqlOptions } from ${importSpecifierFor("runtime/composables/useKql")}
211
+ export type { NitroKirbyFetchOptions, NitroKqlFetchOptions } from ${importSpecifierFor("runtime/server/imports")}
212
+ `.trimStart()
190
213
  });
191
214
  }
192
215
  });
@@ -1,33 +1,8 @@
1
- import type { NitroFetchOptions } from 'nitropack';
2
- export type KirbyFetchOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'method' | 'headers' | 'query' | 'body' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
3
- /**
4
- * Language code to fetch data for in multi-language Kirby setups.
5
- *
6
- * @remarks
7
- * Travels as the `X-Language` header, which Kirby reads on API routes. Kirby Headless 8.1 also
8
- * reads it on the global-routes catch-all, but only for a path that names no language itself.
9
- */
10
- language?: string;
11
- /**
12
- * Serve a repeated request from the Nuxt payload instead of sending it again.
13
- * @default true
14
- */
15
- payloadCache?: boolean;
16
- /**
17
- * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
18
- *
19
- * @remarks
20
- * Such a request never reads from or writes to the server-side cache, since one stored response
21
- * is shared between all visitors.
22
- */
23
- forwardCookies?: boolean;
24
- /**
25
- * Cache key, generated from the request options by default.
26
- */
27
- key?: string;
28
- };
1
+ import type { MaybeRefOrGetter } from 'vue';
2
+ import type { KirbyFetchOptions } from '../types.js';
29
3
  export declare function $kirby<T = any>(path: string, opts?: KirbyFetchOptions): Promise<T>;
30
- /** Sends the request with nothing cached in front of it. */
31
- export declare function sendKirbyRequest<T = any>(path: string, opts: Omit<KirbyFetchOptions, 'payloadCache'> & {
32
- key: string;
33
- }): Promise<T>;
4
+ /** Warns once when a request is sent while the page hydrates, where the server may have sent it already. */
5
+ export declare function warnAboutHydration(functionName: string, composableName: string): void;
6
+ export declare function createKirbyFetch(): <T = any>(path: string, opts?: Omit<KirbyFetchOptions, "language"> & {
7
+ language?: MaybeRefOrGetter<string | undefined>;
8
+ }) => Promise<T>;